您的位置:首页 > 编程语言 > Java开发

spring Aop 面向切面编程简单实例

2017-06-14 16:46 477 查看
最近画了一点时间研究了一下spring的aop,接下来就先直接放源码:

首先创建一个教师Teacher接口:

package com.sise.aop;
public interface Teacher {
public void teach();
}


然后是一个教师类:

package com.sise.aopimpl;

import com.sise.aop.Teacher;

public class TeacherImpl implements Teacher{

@Override
public void teach() {
// TODO Auto-generated method stub
System.out.println("教师开始教课");
}
}


然后再是写一个学生类:

package com.sise.aopimpl;

public class Student {

public Student() {
// TODO Auto-generated constructor stub
}
public void seats()
{
System.out.println("学生回到教室");
}
public void sayhello()
{
System.out.println("向老师问好");
}
public void ask()
{
System.out.println("上课提问");
}
public void endclass()
{
System.out.println("下课了");
}
}


接下来我们希望在做后期维护的时候能够在教师执行teach方法之前执行student类里面的seats和sayhello方法,在教师执行完teach方法之后执行endclass方法。对于这种情况,在spring里面提供了一种叫做aop的方法来执行;

以下是我的beans.xml的配置文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" xmlns:aop="http://www.springframework.org/schema/aop"
>
<!-- 配置需要被Spring管理的Bean(创建,创建后放在了Spring IOC容器里面)-->

<!-- 表演者 -->
<bean id="TeacherImpl" class="com.sise.aopimpl.TeacherImpl"/>

<!-- 观众 -->
<bean id="Student" class="com.sise.aopimpl.Student"></bean>

<!-- 为接口类设置切点 -->
<aop:config proxy-target-class="true">
<aop:aspect ref="Student">
<!-- 之前 -->
<aop:before pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="seats"/>
<!-- 之前 -->
<aop:before pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="sayhello"/>

<!-- 之后 -->
<aop:after-returning pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="ask"/>

<!-- 之后 -->
<aop:after-throwing pointcut="execution(* com.sise.aopimpl.TeacherImpl.teach(..))" method="endclass"/>
</aop:aspect>
</aop:config>

</beans>


beans.xml所放置的位置如下图所示:



接下来在一个便是测试部分的代码:

package com.sise.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sise.aopimpl.TeacherImpl;

public class Test {

public static void main(String[] args)
{
ApplicationContext apc=new ClassPathXmlApplicationContext("beans.xml");
TeacherImpl teacher=(TeacherImpl) apc.getBean("TeacherImpl");
teacher.teach();
}
}


最后是运行结果的截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: