springboot(5)AOP代理

1、启动aop代理

添加maven依赖

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

向springboot的入口类添加注解@EnableAspectJAutoProxy,使注解@Aspect生效。

2、aspect代理

@Aspect
@Component
public class TestAspect {

    /**
     * 在被拦截的方法执行前运行
     */
    @Before("execution(* com.example.demo.action.*.* (..))")
    public void testBefore() {
        System.out.println("before");
    }

    /**
     * 在被拦截的方法运行后运行
     */
    @After("execution(* com.example.demo.action.*.* (..))")
    public void testAfter() {
        System.out.println("after");
    }

    /**
     * 在被拦截的方法运行时运行
     * @param pjp
     * @throws Throwable
     */
    @Around("execution(* com.example.demo.action.*.* (..))")
    public Object testAround(ProceedingJoinPoint pjp) throws Throwable {
        //在被拦截的方法执行前执行
        System.out.println("before");
        //执行被拦截的方法,并获取该方法返回的值
        Object result = pjp.proceed();
        System.out.println("==========="+result);
        //在被拦截的方法执行后执行
        System.out.println("after");
        return result;
    }

    /**
     * 在被拦截的方法抛出异常时运行
     * @param e
     */
    @AfterThrowing(pointcut="execution(* com.example.demo.action.*.* (..))",throwing="e")
    public void testThrowing(Exception e) {
        System.out.println(e.getMessage());
    }
}

3、pointcut表达式

常用的pointcut表达式为execution,格式如下:
execution([访问修饰符] 返回类型 [申明类型] 方法名(参数名) [异常名])

表达式效果
execution(public * * (..))任意公共方法
execution(* set* (..))任意方法名以”set”开头的方法
execution(* com.wxtx.TestDao.* (..))com.wxtx.TestDao类下的任意方法
execution(* com.wxtx.. (..))com.wxtx包(不包括子包)下的任意方法
execution(* com.wxtx... (..))com.wxtx包及其子包下的任意方法
within(com.wxtx.service.*)com.wxtx.service包(不包括子包)下的任意方法
within(com.wxtx.service..*)com.wxtx.service包(不包括子包)下的任意方法
this(com.wxtx.service.TestService)实现了com.wxtx.service.TestService接口的代理对象的任意方法
target(com.wxtx.service.TestService)实现了com.wxtx.service.TestService接口的目标对象的任意方法
args(java.io.Serializable)任意只接受一个参数,且该参数类型是java.io.Serializable的方法
bean(testService)spring容器中bean名为testSerivce的bean的任意方法
bean(*Service)spring容器中bean名匹配*Serivce的bean的任意方法
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值