最近看了SpringAop的源码实现 大概记录一下aop的源码流程
创建一个最简单的一个测试类
package com.zcg.learn.Test;
import org.aopalliance.aop.Advice;
import org.junit.Test;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.tests.aop.advice.CountingAfterReturningAdvice;
import org.springframework.tests.aop.advice.CountingBeforeAdvice;
import com.zcg.learn.UserService;
import com.zcg.learn.UserServiceImpl;
/**
* SpringAop源码分析测试类
* @author zcg
* 2018/3/1
*
*/
public class SpringAopTest {
/**
* 创建代理
*/
@Test
public void createProxyTest() {
Object target = new UserServiceImpl();
ProxyFactory pf = new ProxyFactory(target);
//CountingBeforeAdvice 前置通知计数器
CountingBeforeAdvice countingBeforeAdvice = new CountingBeforeAdvice();
pf.addAdvice(countingBeforeAdvice);
UserService service = (UserService) pf.getProxy();
service.addUser();
}
/**
* 动态添加 移除通知
*/
@Test
public void createProxyTest2() {
Object target = new UserServiceImpl();
ProxyFactory pf = new ProxyFactory(target);
UserService service = (UserService) pf.getProxy();
Advised advised = (Advised) service;
CountingBeforeAdvice countingBeforeAdvice = new CountingBeforeAdvice();
CountingAfterReturningAdvice countingAfterReturningAdvice = new CountingAfterReturningAdvice();
advised.addAdvice(countingAfterReturningAdvice);
advised.addAdvice(countingBeforeAdvice);
service.addUser();
advised.removeAdvice(countingAfterReturningAdvice);
service.addUser();
}
@Test
public void createProxyAspectJByTest() {
Object target = new UserServiceImpl();
AspectJProxyFactory pf = new AspectJProxyFactory(target);
AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
advisor.set)");
CountingBeforeAdvice counting = new CountingBeforeAdvice();
advisor.setAdvice(counting);
pf.addAdvisor(advisor);
UserService userService = pf.getProxy();
userService.addUser();
/**
* advice 通知拦截器
* advisor 通知加切入点适配器
*/
}
}
其中测试方式
@Test
public void createProxyTest() {
Object target = new UserServiceImpl();
ProxyFactory pf = new ProxyFactory(target);
//CountingBeforeAdvice 前置通知计数器
CountingBeforeAdvice countingBeforeAdvice = new CountingBeforeAdvice();
pf.addAdvice(countingBeforeAdvice);
UserService service = (UserService) pf.getProxy();
service.addUser();
}
1.target 以构造参数的形式放入在ProxyFactory中,实际上将该tartget放入在AdvisedSupport类中
2.countingBeforeAdvice 为Spring Aop自带的前置通知计数