Spring学习笔记——第十部分 Aspect Oriented Programming(AOP)
1. 什么是AOP
AOP(Aspect Oriented Programming),意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
2. 使用Spring实现AOP
2.1 方式一:使用原生Spring API接口(主要是SpringAPI接口实现)
<aop:config>
<!--切入点:-->
<aop:pointcut id="pointcut" expression="execution(* com.zhang.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
2.2 方式二:使用自定义类(主要是切面定义)
<bean id="diy" class="com.zhang.diy.PiyPointCut"/>
<aop:config>
<!--自定义切面,ref为要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<!--execution(修饰符 返回值 包名.类名/接口名.方法名(参数列表))-->
<!--(..)表示所有参数,(*)表示一个参数,(*,String)表示第一个参数为任何值,第二个参数为String)-->
<aop:pointcut id="point" expression="execution(* com.zhang.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
public class PiyPointCut {
public void before(){
System.out.println("前");
}
public void after(){
System.out.println("后");
}
}
2.3 方式三:使用注解实现
<bean id="annotationPiontCut" class="com.zhang.diy.AnnotationPointCut"/>
<aop:aspectj-autoproxy/>
@Aspect
public class AnnotationPointCut {
@Before("execution(* com.zhang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("前");
}
@After("execution(* com.zhang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("后");
}
}