003SpringAOP003基于注解使用


1 配置类

编写配置类代码代替配置文件,扫描包并开启AspectJ功能:

1 @Configuration
2 @ComponentScan(basePackages = {"com"})
3 @EnableAspectJAutoProxy(proxyTargetClass = true)
4 public class AspectConfig {
5 }

2 业务核心类

编写业务核心类代码,使用注解加入到IOC容器:

1 @Component
2 public class Calculator {
3     public int add(int i, int j) {
4         System.out.println("add...");
5         return i + j;
6     }
7 }

3 切面类和通知方法

编写切面类代码,并使用注解配置切入点表达式和通知方法:

 1 @Component
 2 @Aspect
 3 @Order(1)
 4 public class AspectWork {
 5     @Pointcut(value = "execution(public int com.service.Calculator.*(int, int))")
 6     public void pointcut() {
 7     }
 8     @Before(value = "pointcut()")
 9     public void workBefore() {
10         System.out.println("WorkBefore...");
11     }
12     @After(value = "pointcut()")
13     public void workAfter() {
14         System.out.println("WorkAfter...");
15     }
16     @AfterReturning(value = "pointcut()", returning = "result")
17     public void workAfterReturning(Object result) {
18         System.out.println("WorkAfterReturning...");
19     }
20     @AfterThrowing(value = "pointcut()", throwing = "exception")
21     public void workAfterThrowing(Throwable exception) {
22         System.out.println("WorkAfterThrowing...");
23     }
24     // @Around(value = "pointcut()")
25     public Object workAround(ProceedingJoinPoint joinPoint) {
26         Object result = null;
27         try {
28             System.out.println("workAround...WorkBefore...");
29             result = joinPoint.proceed(joinPoint.getArgs());
30             System.out.println("workAround...WorkAfterReturning...");
31         } catch (Throwable e) {
32             System.out.println("workAround...WorkAfterThrowing...");
33             throw new RuntimeException();
34         } finally {
35             System.out.println("workAround...WorkAfter...");
36         }
37         return result;
38     }
39 }

4 测试类

编写测试类代码:

1 public class AspectTest {
2     AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(AspectConfig.class);
3     @Test
4     public void test() {
5         Calculator calculator = ioc.getBean(Calculator.class);
6         calculator.add(1, 3);
7     }
8 }