Spring AOP面向切面编程案例 (注解驱动开发)

2023-04-25,,

AOP(动态代理):指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式;
【1】导入 aop 模块;Spring AOP:(spring-aspects);
【2】定义一个业务逻辑类(MathCalculator),在业务逻辑运行的时候将日志进行打印(方法之前、方法运行结束、方法出现异常,xxx);
【3】定义一个日志切面(LogAspects):切面类里面的方法需要动态感知 MathCalculator.div 运行到哪里然后执行;

通知方法:
  ■  前置通知(@Before):logStart:在目标方法(div)运行之前运行;
  ■  后置通知(@After)logEnd:在目标方法(div)运行结束之后运行(无论方法正常结束还是异常结束);
  ■  返回通知(@AfterReturning)logReturn:在目标方法(div)正常返回之后运行;
  ■  异常通知(@AfterThrowing)logException:在目标方法(div)出现异常以后运行;
  ■  环绕通知(@Around)动态代理,手动推进目标方法运行(joinPoint.procced());

【4】给切面类的目标方法标注何时何地运行(通知注解);
【5】将切面类和业务逻辑类(目标方法所在类)都加入到容器中;
【6】必须告诉 Spring 哪个类是切面类(给切面类上加一个注解:@Aspect
【7】给配置类中加 @EnableAspectJAutoProxy 【开启基于注解的 aop 模式】

三步1)、将业务逻辑组件和切面类都加入到容器中;告诉 Spring 哪个是切面类(@Aspect
   2)、在切面类上的每一个通知方法上标注通知注解,告诉 Spring 何时何地运行(切入点表达式)
   3)、开启基于注解的 aop 模式;@EnableAspectJAutoProxy

提前导入 aspects 依赖

1 <dependency>
2 <groupId>org.springframework</groupId>
3 <artifactId>spring-aspects</artifactId>
4 <version>5.1.5.RELEASE</version>
5 </dependency>

切面类

 1 /**
2 * 切面类
3 * @Aspect: 告诉Spring当前类是一个切面类
4 */
5 @Aspect
6 public class LogAspects {
7
8 //抽取公共的切入点表达式
9 //1、本类引用
10 //2、其他的切面引用
11 @Pointcut("execution(public int com.atguigu.aop.MathCalculator.*(..))")
12 public void pointCut(){};
13
14 //@Before在目标方法之前切入;切入点表达式(指定在哪个方法切入)
15 @Before("pointCut()")
16 public void logStart(JoinPoint joinPoint){
17 Object[] args = joinPoint.getArgs();
18 System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}");
19 }
20
21 @After("com.atguigu.aop.LogAspects.pointCut()")
22 public void logEnd(JoinPoint joinPoint){
23 System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
24 }
25
26 //JoinPoint一定要出现在参数表的第一位
27 @AfterReturning(value="pointCut()",returning="result")
28 public void logReturn(JoinPoint joinPoint,Object result){
29 System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
30 }
31
32 @AfterThrowing(value="pointCut()",throwing="exception")
33 public void logException(JoinPoint joinPoint,Exception exception){
34 System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
35 }

正常类

1 public class MathCalculator {
2 public int div(int i,int j){
3 System.out.println("MathCalculator...div...");
4 return i/j;
5 }
6 }

配置类

 1 @EnableAspectJAutoProxy
2 @Configuration
3 public class MainConfigOfAOP {
4
5 //业务逻辑类加入容器中
6 @Bean
7 public MathCalculator calculator(){
8 return new MathCalculator();
9 }
10
11 //切面类加入到容器中
12 @Bean
13 public LogAspects logAspects(){
14 return new LogAspects();
15 }
16 }

Spring AOP面向切面编程案例 (注解驱动开发)的相关教程结束。

《Spring AOP面向切面编程案例 (注解驱动开发).doc》

下载本文的Word格式文档,以方便收藏与打印。