赞
踩
AOP 的特性术语,不同的翻译还会不一样,得在过程中理解
Spring中有五种通知 Advice
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
@Component
public class User {
public void sayHi(String name) {
System.out.println(">>> user hi: " + name);
}
}
@Aspect @Component public class UserAspect { @Pointcut("execution(public * com.x.z..*.*(..))") public void pointCut() { } @Before("pointCut()") public void before() { System.out.println("before advice..."); } @After("pointCut()") public void after() { System.out.println("after advice..."); } @Around("pointCut()") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("around advice before..."); Object proceed = pjp.proceed(); System.out.println("around advice after..."); return proceed; } @AfterReturning(value = "pointCut()") public void afterReturning() { System.out.println("AfterReturning advice..."); } @AfterThrowing(value = "pointCut()") public void afterThrowing() { System.out.println("AfterThrowing advice..."); } } @Configuration @EnableAspectJAutoProxy //一定加的注解, 不然切面不生效 @Import({UserAspect.class, User.class}) public class UserConfig { }
public class UserAopTest {
@Test
public void userAspectTest(){
ApplicationContext act = new AnnotationConfigApplicationContext(UserConfig.class);
User user = act.getBean(User.class);
user.sayHi("小明");
}
}
around advice before...
before advice...
>>> user hi: 小明
AfterReturning advice...
after advice...
around advice after...
很明显,我这个是类代理,所以进入 DynamicAdvisedInterceptor
获取增强链:
aop 流程:
TargetSource targetSource = this.advised.getTargetSource()
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass)
一句话: 生成代理对象,使用责任链式方式调用通知链执行增强方式,最后执行目标方法,达到增强目的
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。