关于springboot aop的使用

记下笔记,方便日后查询,如有错误,请指出,共同进步

在pom.xml中添加依赖:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

MethodInterceptor是AOP项目中的拦截器,它拦截的目标是方法,即使不是Controller中的方法。 

实现MethodInterceptor拦截器大致也分为两种,一种是实现MethodInterceptor接口,另一种利用Aspect的注解或配置。

本文主要还是说@Aspect注解方式

然后创建Aspect测试类:

package demo.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect   //springboot aop 注解
@Order(-99) 	// 控制多个Aspect的执行顺序,越小越先执行 
@Component
public class AopTest {
		
	    //"@annotation()  拦截指定方法
	    //@Pointcut (execution(public * com.hhsd.modular.celler.controller..*.*(..))) 拦截符合条件的方法
	    @Pointcut("execution(public * demo.controller..*.*(..))") 
	    public void recordLog(){
		System.out.println("执行aop");
	    }
		
	    @Before("recordLog()")
	    public void before() {
	        this.printLog("@Before是在所拦截方法执行之前执行一段逻辑");
	    }
		
	    @Around("recordLog()")
	    public void around(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("@Around是可以同时在所拦截方法的前后执行一段逻辑");
	        this.printLog("@Around 方法执行前");
	        pjp.proceed();
	        this.printLog("@Around 方法执行后");
	    }

	    @After("recordLog()")
	    public void after() {
	        this.printLog("@After 是在所拦截方法执行之后执行一段逻辑");
	    }
		
		    private void printLog(String str){
	        System.out.println(str);
	    }
}

然后测试用的Controller层代码

package demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestAction {
	
	@RequestMapping("/test")
	public void queryUsers(){
            System.out.println("aop test");
        }
}

运行之后的输出:

@Around是可以同时在所拦截方法的前后执行一段逻辑
@Around 方法执行前
@Before是在所拦截方法执行之前执行一段逻辑
aop test
@Around 方法执行后
@After 是在所拦截方法执行之后执行一段逻辑
当你需要使用CGLIB来实现AOP的时候,需要配置spring.aop.proxy-target-class=true,这个默认值是false,不然默认使用的是标准Java的实现。

猜你喜欢

转载自blog.csdn.net/weixin_39591965/article/details/80843039