Spring的AOP采用了23种GOF(设计模式)之一的代理模式
作用:
代理模式是 AOP(Aspect Oriented Programming 面向切面编程)的核心实现机制。
AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
Spring中可以AOP横向切入要执行的事件,却又不改变原来的代码,做到低耦合原则。
例如要在纵向的DAO层插入日志事件,为了不改变原有的代码就可以使用AOP横向切入代码来记录日志,SpringMVC中的拦截器的原理也是使用了AOP。
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
第一种:自定义横切类来实现AOP
先到spring-service.xml配置
<!--注册bean-->
<bean id="test" class="top.hcode.config.testPointcut"/>
<!--aop的配置-->
<aop:config>
<!--使用AOP的标签实现-->
<aop:aspect ref="test">
<aop:pointcut id="testPonitcut" expression="execution(* top.hcode.service.ServiceImpl.*(..))"/>
<aop:before pointcut-ref="testPonitcut" method="before"/>
<aop:after pointcut-ref="testPonitcut" method="after"/>
</aop:aspect>
</aop:config>
在项目config目录中编写一个横切类
public class testPointcut {
public void before(){
//写入在切点方法前需要执行的事件程序
}
public void after(){
//写入在切点方法后需要执行的事件程序
}
}
这样只要调用service文件夹里的方法都会执行这个横切事件。
第二种:使用注解实现AOP
先到spring-service.xml配置
<!--注解实现-->
<bean id="annotationPointcut" class="top.hcode.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>
然后再编写一个注解实现的增强类
@Aspect
public class AnnotationPointcut {
@Before("execution(* top.hcode.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---------方法执行前---------");
}
@After("execution(* top.hcode.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---------方法执行后---------");
}
//上面两种相当于下面
@Around("execution(* top.hcode.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前方法");
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后方法");
}
}
通过aop命名空间的声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被隐藏起来了 有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。