Spring中可以使用注解或XML文件配置的方式实现AOP。
1、导入jar包

  • com.springsource.net.sf.cglib -2.2.0.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.0.0.RELEASE.jar
  • spring-aspects-4.0.0.RELEASE.jar
  • spring-beans-4.0.0.RELEASE.jar
  • spring-context-4.0.0.RELEASE.jar
  • spring-core-4.0.0.RELEASE.jar
  • spring-expression-4.0.0.RELEASE.jar

aspectaop相关jar包 ---> 资源目录--->jar包资源--->AOP日志打印相关jar包(切面类) 

Spring相关jar包 ---> 资源目录--->jar包资源--->Spring相关jar包 

2、开启基于注解的AOP功能

在Spring的配置文件中加入

<context:component-scan base-package="com.bwlu.aop"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

3、声明一个切面类,并把这个切面类加入到IOC容器中

 1 @Component//加入IOC容器
 2 @Aspect//表示这是一个切面类
 3 public class LogAspect{
 4     //value中为切入点表达式
 5     @Before(value="execution(public void com.bwlu.common.MathCalculatorImpl.*(..))")//前置通知
 6     public void showBeginLog(){
 7         System.out.println("AOP日志开始");
 8     }
 9     @After(value="execution(public void com.bwlu.common.MathCalculatorImpl.*(..))")//后置通知
10     public void showReturnLog(){
11         System.out.println("AOP方法结束");
12     }
13     @AfterThrowing(value="execution(public void com.bwlu.common.MathCalculatorImpl.*(..))")//异常通知
14     public void showExceptionLog(){
15         System.out.println("AOP方法异常");
16     }
17     @AfterReturning(value="execution(public void com.bwlu.common.MathCalculatorImpl.*(..))")//返回通知
18     public void showAfterLog(){
19         System.out.println("AOP方法最终返回");
20     }
21 }

4、被代理的对象也需要加入IOC容器

 1 @Component
 2 public class MathCalculator {
 3     public void add(int i, int j) {
 4         int result=i+j;
 5         System.out.println("目标方法add(int)执行了");
 6     }
 7     public void sub(int i, int j) {
 8         int result=i-j;
 9         System.out.println("目标方法sub执行了");
10     }
11     public void mult(int i, int j) {
12         int result=i*j;
13         System.out.println("目标方法mult执行了");
14     }
15     public void div(int i, int j) {
16         int result=i/j;
17         System.out.println("目标方法div执行了");
18     }
19 }
MathCalculator

相关文章:

  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-17
  • 2022-12-23
  • 2021-05-27
  • 2021-07-13
猜你喜欢
  • 2021-10-10
  • 2021-06-25
  • 2022-02-02
  • 2022-12-23
  • 2021-12-27
相关资源
相似解决方案