1、maven的pom添加aop依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
2、编写一个类,必须在spring boot启动类的包名之下(不然扫描不到);如下:
@Configuration
@Aspect
public class MyAOPConfig {
@Around("@within(org.springframework.stereotype.Controller)")
public Object myAop(final ProceedingJoinPoint pjb) throws Throwable{
try {
Object[] args = pjb.getArgs();
System.out.println("args:" + Arrays.asList(args));
Object o = pjb.proceed();
System.out.println("return:" + o);
return o;
}catch (Throwable e){
throw e;
}
}
}
//@Configration 用于引起spring注意是个管理bean,@Service、@Repository、@Controller、@Component 等注解都行
//@Aspect 表明它是个切面类
//@within 表明是一个通过注解织入的表达式,本例表明所有声明为 controller的类都会被织入,也即所有方法在调用时都会触发;具体表达式有很多,可以参照spring官网
//@aroud表明是在执行前后
//在方法中有打印入参,而spring在@Contrller类的方法中如果要自动注入入参,入参需要用 @PathVariable 修饰;
上述是环切方式,还有一种更简洁,更规范的写法,就是先定义切点Pointcut,然后针对切点编写执行前,执行后的逻辑:
image.png
//定义切点
@Pointcut(value = "execution(* test.boot.HellowordController.*(..))")
private void myAspectPointcut() {
}
//执行前
@Before(value = "myAspectPointcut()")
public void aspectBefore(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
System.out.println("切面执行前:" + Arrays.asList(args));
}
//执行后
@After(value = "myAspectPointcut()")
public void aspectAfter(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
System.out.println("切面执行后:" + Arrays.asList(args));
}
//执行返回值
@AfterReturning(pointcut = "myAspectPointcut()", returning = "result")
public void aspectAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("切面执行后,返回值:" + Arrays.asList(result));
}
//执行抛异常
@AfterThrowing(pointcut = "myAspectPointcut()", throwing = "ex")
public void aspectAfterThrowing(JoinPoint jp, Exception ex) {
System.out.println("切面执行出错");
}
image.png
网友评论