Spring_AOP的注解实现
# 1 基础认知
Spring AOP的基础在SpringAOP的Xml配置 已经做了详细的介绍。请移步SpringAOP的Xml配置
# 2 Xml配置
xml中增加 <aop:aspectj-autoproxy>
<!--aop的自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
1
2
2
# 3 注解
标签 | 作用 | 运行时机 |
---|---|---|
@Aspect | 标注切面类 | |
@Before | 指定前置通知 | 切入点执行之前 |
@AfterReturning | 指定后置通知 | 切入点执行之后 |
@Around | 指定环绕通知 | 切入点执行前后都执行 |
@AfterThrowing | 指定异常抛出通知 | 切入点异常抛出时 |
@After | 指定最终通知 | 无论是否抛出异常都执行 |
@Pointcut | 指定切点 | |
@DeclareParents | 指定添加新接口 |
Demo:
@Component("studentAspect")
@Aspect
public class StudentAspect implements People {
@DeclareParents(value = "com.study.aop.Student", defaultImpl = com.study.aop.imp.StudentAspect.class)
public People people;
@Before("execution(void com.study.aop.Student.study(..))")
public void before(JoinPoint joinPoint) {
//System.out.println(joinPoint.getSignature().getName());
System.out.println("before, 前置增强 ... " + joinPoint.getArgs()[0]);
}
//@AfterReturning(pointcut = "execution( * com.study.aop.Student.study(String,String)) && args(course, teacher)")
@AfterReturning(pointcut = "execution( * com.study.aop.Student.study(String,String)) && args(course, teacher)", argNames = "course, teacher")
public void after(String course, String teacher) {
System.out.println("after-returning, 后置增强 ... " + teacher);
}
@Around(value = "execution( * com.study.aop.Student.study(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("around, 环绕增强 ... ");
Object[] args = joinPoint.getArgs();
if (args.length > 0) {
System.out.print("Arguments passed: " );
for (int i = 0; i < args.length; i++) {
System.out.print("arg "+(i+1)+": "+args[i]);
}
}
joinPoint.proceed(args);
System.out.println("around, 运行完 ... ");
}
@AfterThrowing(value = "execution( * com.study.aop.Student.study(..))")
public void throwing() {
System.out.println("after-throwing, 异常增强 ... ");
}
@After(value = "StudentAspect.pointcut(course, teacher)", argNames = "teacher, course")
public void afterAll(String teacher, String course) {
System.out.println("after, 最终通知增强 ... " + course + "_" + teacher);
}
@Override
public void eat() {
System.out.println("吃 吃 吃,就知道吃 ... ");
}
@Pointcut(value = "execution( * com.study.aop.Student.study(String,String)) && args(p1, p2)", argNames = "p1, p2")
public void pointcut(String p1, String p2){}
}
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 4 Git路径
仓库位置:https://github.com/su-dd/demo.git (opens new window)
代码位置:Spring相关/40Demo (opens new window)
Demo路径:https://github.com/su-dd/KnowledgeStack.git
具体路径:JavaWeb/TestCode/_03_Spring/Demo5
编辑 (opens new window)
上次更新: 2023/03/17, 15:46:47