关于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的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值