养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

如何使用注解的方式进行AOP功能实现

时间:2024-09-23 13:15:53

如何使用注解的方式进行AOP功能实现

工具/原料

Spring

AOP

Eclipse

方法/步骤

1、AOP指的是在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式。packagecom.gwolf.config;importorg.springframework.context.annotation.Configuration;@ConfigurationpublicclassMainConfigOfAOP{}

如何使用注解的方式进行AOP功能实现

2、要在项目中提供SpringAOP功熹栳缂靖能,需要导入相关的依赖包。<dependency><groupId>org.springframework</爿讥旌护groupId><artifactId>spring-aspects</artifactId><version>4.3.12.RELEASE</version></dependency>

如何使用注解的方式进行AOP功能实现

3、有一个业务,我们需要使用AOP在这个业务的执行前后记录一些日志:packagecom.gwolf.aop;publicclassMathCalculator{publicintdiv(inti,intj){returni/j;}}

如何使用注解的方式进行AOP功能实现

4、定义一个日志切面类,切面类里面的方法需要动态感知业务方瓠鲶陋啼法运行到哪个步骤。这个是通过通知方法控制:有前置通知,后置通知,返回通知,异常通知,环迮滞筋棍绕通知。packagecom.gwolf.aop;importorg.aspectj.lang.annotation.After;importorg.aspectj.lang.annotation.AfterReturning;importorg.aspectj.lang.annotation.Before;importorg.aspectj.lang.annotation.Pointcut;publicclassLogAspects{//切入点表达式@Pointcut("execution(publicintcom.gwolf.aop.MathCalculator.*(..))")publicvoidpointCut(){}@Before("com.gwolf.aop.LogAspects.pointCut()")publicvoidlogStart(){System.out.println("除法运行。。参数列表是:{}");}@After("com.gwolf.aop.LogAspects.pointCut()")publicvoidlogEnd(){System.out.println("除法结束运行。。参数列表是:{}");}@AfterReturning("com.gwolf.aop.LogAspects.pointCut()")publicvoidlogReturn(){System.out.println("除法正常返回。。运行结果是:{}");}publicvoidlogException(){System.out.println("除法异常。。异常是:{}");}}

如何使用注解的方式进行AOP功能实现

5、将切面类和业务逻辑类都加入到容器中。packagecom.gwolf.con酆璁冻嘌fig;importorg.s禊诬娱飑pringframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importcom.gwolf.aop.LogAspects;importcom.gwolf.aop.MathCalculator;@ConfigurationpublicclassMainConfigOfAOP{@BeanpublicMathCalculatorcalculator(){returnnewMathCalculator();}@BeanpublicLogAspectslogAspects(){returnnewLogAspects();}}

如何使用注解的方式进行AOP功能实现

6、使用@Aspect注解告诉Spring哪个类是切面类:

如何使用注解的方式进行AOP功能实现

7、给配置类中加上@EnableAspectJAutoProxy注解开启基于注解的AOP模式。

如何使用注解的方式进行AOP功能实现

8、在junit测试类中执行业务方法。

如何使用注解的方式进行AOP功能实现

© 一点知识