SpringBoot整合AOP
没事做个Demo案例,首先看下项目结构:
第1步,导入依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
第2步,编写测试类:
@Controller
@RequestMapping("/demo")
public class JNTestDemo {@RequestMapping("/test")@ResponseBodypublic String testMethod(){System.out.println("this is a test method");return "index";}}
第3步,编写Aop配置类:
package com.zhongji.jisuanji22.config;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Aspect
@Component
public class AopConfig {@Pointcut("execution(* com.zhongji.jisuanji22.controller.*.*(..))")public void aop(){}@Before("aop()")public void beforeAdvice(){System.out.println("前置通知");}@After("aop()")public void afterAdvice(){System.out.println("后置通知");}@Around("aop()")public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {System.out.println("环绕通知前");Object o = proceedingJoinPoint.proceed();System.out.println("环绕通知后");return o;}
}
第4步,访问Controller接口路径,得到测试:
控制台输出为:
至此,基本的使用方法完成。
【注:如果传参的话,可参考下列步骤】
1、控制层被测试的方法变化为:
@RequestMapping("/test/{prama}")@ResponseBodypublic String testMethod(@PathVariable String prama){System.out.println("this is a test method"+prama);return "index";}
2、以前置通知为测试方法,则AOP的配置类为:
package com.zhongji.jisuanji22.config;import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Aspect
@Component
public class AopConfig {@Pointcut("execution(* com.zhongji.jisuanji22.controller.*.*(..)) && args(prama,..)")public void aop(String prama){}@Before(value = "aop(prama)")public void beforeAdvice(String prama){System.out.println("前置通知:"+prama);}@After("aop(String)")public void afterAdvice(){System.out.println("后置通知");}@Around("aop(String)")public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {System.out.println("环绕通知前");Object o = proceedingJoinPoint.proceed();System.out.println("环绕通知后");return o;}
}
3、再次执行测试接口:
我们发现控制台:
我们看到,参数已经由Controller层传到了AOP指定的方法中。