最近学习了spring aop,个人认为AOP的机理实际是将共有的功能部分提取出来,然后再在程序运行时通过配置,可选择性的无缝插入到正在运行的程序中,无需更改被插入的程序,如果需要改变共有功能,只需更改公共部分的代码而不需要更改其他的代码,符合面向对象的 解耦合。
下面通过一个小例子来说明aop的运行机制。例子实现的结果是,人在sing,eat,talking之前都要进行openMouse,之后都要进行closeMouse。
//定义person类,有几个行为方法
public class person {
private SameThing thing; //将切面引进来,从而达到对下面的行为进行通知
public person() {
super();
// TODO Auto-generated constructor stub
}
public person(SameThing thing) {
super();
this.thing = thing;
}
public void sing(){
System.out.println("---person sing a song----");
}
public void eat(){
System.out.println("---person eat----");
}
public void talking(){
System.out.println("---person talking----");
}
}
//该类为公共部分
public class SameThing {
public void openMouse(){
System.out.println("---open mouse----");
}
public void closeMouse(){
System.out.println("---close mouse----");
}
}
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!--初始化Bean到容器中-->
<bean id="openMouse" class="com.nongrj.aop.SameThing">
</bean>
<bean id="person" class="com.nongrj.aop.person">
<!--构造器方式注入一个对象,将该对象引入本类,从而进行对行为进行通知-->
<constructor-arg ref="openMouse"></constructor-arg>
</bean>
<aop:config>
<!-- 定义切面:共有提取部分 -->
<aop:aspect id="aspet" ref="openMouse">
<!-- 定义切点:需要切面切的点-->
<aop:pointcut expression="execution(* *.eat(..))" id="cut"/>
<aop:before pointcut-ref="cut" method="openMouse"/>
<aop:after pointcut-ref="cut" method="closeMouse"/>
<aop:pointcut expression="execution(* *.sing(..))" id="singcut"/>
<aop:before pointcut-ref="singcut" method="openMouse"/>
<aop:after pointcut-ref="singcut" method="closeMouse"/>
</aop:aspect>
</aop:config>
</beans>
//最后为test类
public class TestSpring {
public static void main(String[] args) {
//获取spring容器
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//context.getBean("usv");
person person= (person) context.getBean("person");
person.eat();
person.sing();
}
打印结果为:
---open mouse----
---person eat----
---close mouse----
---open mouse----
---person sing a song----
---close mouse----