基于注解的AOP 方式
1.加入jar包
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
spring-aop-4.1.0.RELEASE.jar
spring-aspects-4.1.0.RELEASE.jar
spring-beans-4.1.0.RELEASE.jar
spring-context-4.1.0.RELEASE.jar
spring-core-4.1.0.RELEASE.jar
spring-expression-4.1.0.RELEASE.jar
2.在配置文件中加入AOP的命名空间
3.基于注解的方式
①在配置文件中加入如下配置
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
②把横切关注点的代码抽象到切面的类中
切面首先是一个IOC中的bean,即加入@Component注解
切面还需要加入@Aspect注解
③在类中声明各种通知
@Before 前置通知,在方法执行之前执行
@After 后置通知,在方法执行之后执行
@AfterRunning 返回通知,在方法返回结果之后执行
@AfterThrowing 异常通知,在方法抛出异常之后执行
@Around 环绕通知,围绕着方法执行
③在方法中声明一个类型为JoinPoint的参数就可以访问链接细节
ArithmeticCalculator接口
1 2 3 4 5 6 7 8 9 10 11 |
|
接口实现类 ArithmeticCalculatorImpl.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 |
|
切面类 LoggingAspect.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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
applicationContext.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
基于配置文件的AOP 方式
引入的jar包与基于注解的方式引入的jar包相同
ArithmeticCalculator接口
1 2 3 4 5 6 7 8 9 10 11 |
|
接口实现类 ArithmeticCalculatorImpl.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 |
|
切面类 LoggingAspect.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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
切面类 ValidationAspect.java
1 2 3 4 5 6 7 8 9 10 11 12 |
|
applicationContext-xml.xml
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 |
|
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|