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

spring aop原理

2018-03-07 11:25 190 查看
AOP(Aspect Orient Programming),我们一般称为面向方面(切面)编程,作为面向对象的一种补充,用于处理系统中分布于各个模块的横切关注点,比如事务管理、日志、缓存等等。AOP实现的关键在于AOP框架自动创建的AOP代理,AOP代理主要分为静态代理和动态代理,静态代理的代表为AspectJ;而动态代理则以Spring AOP为代表。本文会分别对AspectJ和Spring AOP的实现进行分析和介绍。

使用AspectJ的编译时增强实现AOP

之前提到,AspectJ是静态代理的增强,所谓的静态代理就是AOP框架会在编译阶段生成AOP代理类,因此也称为编译时增强。举个实例的例子来说。首先我们有一个普通的
Hello
使用AspectJ编写一个Aspect
这里模拟了一个事务的场景,类似于Spring的声明式事务。使用AspectJ的编译器编译
编译完成之后再运行这个
Hello
类,可以看到以下输出
显然,AOP已经生效了,那么究竟AspectJ是如何在没有修改Hello类的情况下为Hello类增加新功能的呢?查看一下编译后的
Hello.class
可以看到,这个类比原来的
Hello.java
多了一些代码,这就是AspectJ的静态代理,它会在编译阶段将Aspect织入Java字节码中, 运行的时候就是经过增强之后的AOP对象。
从Aspect编译后的class文件可以更明显的看出执行的逻辑。
proceed
方法就是回调执行被代理类中的方法。

使用Spring AOP

与AspectJ的静态代理不同,Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改字节码,而是在内存中临时为方法生成一个AOP对象,这个AOP对象包含了目标对象的全部方法,并且在特定的切点做了增强处理,并回调原对象的方法。Spring AOP中的动态代理主要有两种方式,JDK动态代理和CGLIB动态代理。JDK动态代理通过反射来接收被代理的类,并且要求被代理的类必须实现一个接口。JDK动态代理的核心是
InvocationHandler
接口和
Proxy
类。如果目标类没有实现接口,那么Spring AOP会选择使用CGLIB来动态代理目标类。CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成某个类的子类,注意,CGLIB是通过继承的方式做的动态代理,因此如果某个类被标记为
final
,那么它是无法使用CGLIB做动态代理的。为了验证以上的说法,可以做一个简单的测试。首先测试实现接口的情况。定义一个接口
实现类
这里的
@Timer
注解是我自己定义的一个普通注解,用来标记Pointcut。定义Aspect
运行
输出
可以看到类型是
com.sun.proxy.$Proxy53
,也就是前面提到的Proxy类,因此这里Spring AOP使用了JDK的动态代理。再来看看不实现接口的情况,修改
Chinese
运行
输出
可以看到类被CGLIB增强了,也就是动态代理。这里的CGLIB代理就是Spring AOP的代理,这个类也就是所谓的AOP代理,AOP代理类在切点动态地织入了增强处理。

五种类型的通知

Before advice:在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。 
< aop:before>

After advice:当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。 
< aop:after>

After returnadvice:在某连接点正常完成后执行的通知,不包括抛出异常的情况。 
< aop:after-returning>

Around advice:包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法执行的前后实现逻辑,也可以选择不执行方法 
< aop:around>

Afterthrowing advice:在方法抛出异常退出时执行的通知。 
< aop:after-throwing>

 基于Schema的Spring AOP实例

第一步、定义具体业务逻辑模块(目标对象)

两个业务逻辑模块都是基于接口TestAOPDaoImpl .java
public class TestAOPDaoImpl implements TestAOPDao{

@Override
public void addUser() {
System.out.println("添加成功");
}

}
TestAOPServiceImpl.java
public class TestAOPServiceImpl implements TestAOPService{

@Autowired
private TestAOPDao testAOPDao;

@Override
public void addUser() {
testAOPDao.addUser();
}

}

第二步和第三步、 定义切面(即实现通知逻辑)

JointPoint是连接点,aop创建代理后会返回一个连接点,然后在通知中可以通过该连接点实现我们的切面逻辑日志切面
public class LogAdivice{

public void myBeforeAdivice(JoinPoint joinPoint){
String classname = joinPoint.getTarget().getClass().getSimpleName();
String methodname = joinPoint.getSignature().getName();
System.out.println(classname + " ——前置通知——" + methodname);
}

public void myAfterAdivice(JoinPoint joinPoint){
String classname = joinPoint.getTarget().getClass().getSimpleName();
String methodname = joinPoint.getSignature().getName();
System.out.println(classname + " ——后置通知——" + methodname);
}

/**
* 环绕通知将决定要不要执行连接点
* @throws Throwable
*/
public void myAroundAdivice(ProceedingJoinPoint point) throws Throwable{
System.out.println("环绕通知,执行代码前");
//选择执行
point.proceed();
System.out.println("环绕通知,执行代码后");
}
}
时间切面:
public class TimeAdvice {

public void timeBefore(){
System.out.println("beforeTime = " + System.currentTimeMillis());
}

public void timeAfter(){
System.out.println("afterTime = " + System.currentTimeMillis());
}
}
在applicationContext中配置切面:
<context:annotation-config/>
<bean id="testAOPDao" class="com.ssh.dao.impl.TestAOPDaoImpl"/>
<bean id="testAOPService" class="com.ssh.service.impl.TestAOPServiceImpl"/>
<bean id="logAdivice" class="com.ssh.adivice.LogAdivice"/>
<bean id="timeAdvice" class="com.ssh.adivice.TimeAdvice"/>

<aop:config>
<!-- 配置一个切面 -->
<aop:aspect id="logaop" ref="logAdivice" order="2">
<!-- 定义切入点,表示对service的所有方法都进行拦截 -->
<aop:pointcut expression="execution(* com.ssh.service.TestAOPService.*(..))" id="testpointcut"/>
<!-- 定义前置通知 -->
<aop:before method="myBeforeAdivice" pointcut-ref="testpointcut"/>
<!-- 定义后置通知 -->
<aop:after-returning method="myAfterAdivice" pointcut-ref="testpointcut"/>
<!-- 定义环绕通知 -->
<aop:around method="myAroundAdivice" pointcut-ref="testpointcut"/>
</aop:aspect>

<!-- 定义另一个切面 -->
<aop:aspect id="timeaop" ref="timeAdvice" order="1">
<!-- 定义切入点,表示对service的所有方法都进行拦截 -->
<aop:pointcut expression="execution(* com.ssh.service.TestAOPService.*(..))" id="testpointcut"/>
<!-- 定义前置通知 -->
<aop:before method="timeBefore" pointcut-ref="testpointcut"/>
<!-- 定义后置通知 -->
<aop:after-returning method="timeAfter" pointcut-ref="testpointcut"/>
</aop:aspect>
</aop:config>
当有多个切面时,Spring默认是按照切面定义的顺序来执行,也可以通过order属性来配置切面的执行属性,order=1 早于 order=2执行

测试结果

public class AOPTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
TestAOPService service = (TestAOPService) context.getBean("testAOPService");
service.addUser();
}

}


基于@AspectJ注解的AOP实现

第一步、定义具体业务逻辑模块(目标对象)

第一步和上面一样TestAOPDaoImpl .java
public class TestAOPDaoImpl implements TestAOPDao{

@Override
public void addUser() {
System.out.println("添加成功");
}

}
TestAOPServiceImpl.java
public class TestAOPServiceImpl implements TestAOPService{

@Autowired
private TestAOPDao testAOPDao;

@Override
public void addUser() {
testAOPDao.addUser();
}

}

第二步和第三步、 定义切面(即实现通知逻辑)

重点是定义切入点
@Aspect
public class LogAdivice{

//定义一个方法作为切入点id
@Pointcut("execution(* com.ssh.service.TestAOPService.*(..))")
private void allMethod(){}

@Before("allMethod()")
public void myBeforeAdivice(JoinPoint joinPoint){
String classname = joinPoint.getTarget().getClass().getSimpleName();
String methodname = joinPoint.getSignature().getName();
System.out.println(classname + " ——前置通知——" + methodname);
}

@AfterReturning("allMethod()")
public void myAfterAdivice(JoinPoint joinPoint){
String classname = joinPoint.getTarget().getClass().getSimpleName();
String methodname = joinPoint.getSignature().getName();
System.out.println(classname + " ——后置通知——" + methodname);
}

/**
* 环绕通知将决定要不要执行连接点
* @throws Throwable
*/
@Around("allMethod()")
public void myAroundAdivice(ProceedingJoinPoint point) throws Throwable{
System.out.println("环绕通知,执行代码前");
//执行
point.proceed();
System.out.println("环绕通知,执行代码后");
}
}
在applicationContext的配置:
<!-- 打开自动扫描(隐式打开注解管理器) -->
<!-- <context:component-scan base-package="com.ssh"/> -->
<context:annotation-config/>
<bean id="testAOPDao" class="com.ssh.dao.impl.TestAOPDaoImpl"/>
<bean id="testAOPService" class="com.ssh.service.impl.TestAOPServiceImpl"/>
<bean id="logAdivice" class="com.ssh.adivice.LogAdivice"/>
<bean id="timeAdvice" class="com.ssh.adivice.TimeAdvice"/>

<!-- 打开aop注解管理器 -->
<aop:aspectj-autoproxy/>

参考自http://listenzhangbin.com/post/2016/09/spring-aop-cglib/         http://blog.csdn.net/jeffleo/article/details/54136904


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