顾名思义 AOP(Aspect oriented Programming)字面意思是面向切面编程,aop所带来的好处是能提取具有共同功能的代码块,比如用户取款流程需要用到1.用户密码的验证;2.用户查询余额需要用到密码的验证 那么两者之间的共同密码验证功能的逻辑实现则可以提取出来,提取出来的部分称为切面。以下为aop的小小案例(有两个HelloWord类,它们都需要打印时间毫秒,那么我们可以抽取打印时间作为切面)
1.操作AOP需要用到的jar包为
:
2.创建HellWord的接口,声明两个方法sayHello()dopoint()
package com.aop;
public interface HelloWord {
public void sayHello();
public void dopoint();
}
3.分别实现HellWord接口
package com.aop.hw;
import com.aop.HelloWord;
public class HelloWordImp2 implements HelloWord {
@Override
public void sayHello() {
System.out.println("我是HelloWord2");
}
@Override
public void dopoint() {
System.out.println("我是dopoint2");
}
}
package com.aop.hw;
import com.aop.HelloWord;
public class HelloWordImp1 implements HelloWord {
@Override
public void sayHello() {
System.out.println("我是HelloWord1");
}
@Override
public void dopoint() {
System.out.println("我是dopoint1");
}
}
4.创建一个时间切面TimerAspect类
package com.aop;
public class TimerAspect {
public void timer() {
System.out.println(System.currentTimeMillis());
}
}
5.配置applicationContext.xml文件,注意在配置xml文件的时候,这里expression="execution(* com.aop.hw.*.*(..))"需要注意,两个.*.*代表的是包下的类下的所有方法,<aop:config proxy-target-class="true">这条语句中的proxy-target-calss=“true”需要加入,否则报错
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<bean id="hello1" class="com.aop.hw.HelloWordImp1"></bean>
<bean id="hello2" class="com.aop.hw.HelloWordImp2"></bean>
<bean id="timerAspect" class="com.aop.TimerAspect"></bean>
<aop:config proxy-target-class="true">
<aop:aspect id="timer" ref="timerAspect">
<aop:pointcut id="addAllMethod" expression="execution(* com.aop.hw.*.*(..))" />
<aop:before method="timer" pointcut-ref="addAllMethod" />
<aop:after method="timer" pointcut-ref="addAllMethod" />
</aop:aspect>
</aop:config>
</beans>