面向切面的Spring

  • 面向切面编程的基本原理
  • 通过POJO创建切面
  • 使用@AspectJ注解
  • 为AspectJ切面注入依赖

面向切面的编程

定义术语

  1. 通知(Advice)
  2. 连接点(Join point)
  3. 切点(Pointcut)
  4. 切面(Aspect)
  5. 引入(introduction)
  6. 织入(Weaving)

使用xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<aop:config expose-proxy="true" proxy-target-class="true">

<aop:pointcut id="test_point_cut" expression="execution(* com.yuda.component.MyTest.*(..))"/>

<aop:aspect ref="my_advice">

<aop:before method="before" pointcut-ref="test_point_cut"/>

<aop:after method="after" pointcut-ref="test_point_cut"/>

<aop:around method="around" pointcut-ref="test_point_cut"/>

<aop:after-returning method="afterReturning" pointcut-ref="test_point_cut" returning="val"/>

</aop:aspect>
</aop:config>

使用注解

xml

1
<aop:aspectj-autoproxy proxy-target-class="true"/>

java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Aspect
public class MyAspect {
@Pointcut("execution(* *.*(..))")
public void myPointCut(){}

@Before("myPointCut()")
public void before() {
System.out.println("MyAspect.before");
}

@After("myPointCut()")
public void after(){
System.out.println("MyAspect.after");
}

@Around("myPointCut()")
public Object around(ProceedingJoinPoint pjp){

Object proceed = null;
try {
System.out.println("前");
System.out.println(pjp.getSignature().getName());
proceed = pjp.proceed();
System.out.println(pjp.getSignature().getName());
System.out.println("后");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return proceed;
}

@AfterReturning(value = "myPointCut()",returning = "val")
public void afterReturning(JoinPoint jp,Object val){
System.out.println("啦啦啦啦"+jp.getSignature().getName());
System.out.println("MyAspect.afterReturning");
}
}