了解掌握spring aop(中)

13 篇文章 0 订阅

         接着上一篇博客,这里主要记录一下各种增强的实现,包括前置增强,后置增强,环绕增强,异常抛出增强,引介增强,用@AspectJ来实现(需要注意的一个问题,jdk版本必须在1.5以上)

1.前置增强,业务层和aop拦截代码如下

package com.mimoprint.schedule.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AopService {

    public void testAop(){
        log.info("******测试aop******");
    }

}
package com.mimoprint.schedule.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Slf4j
@Component
public class AdviceAspect {

    @Before("execution(* testAop(..))")
    public void greetTo(){
        log.info("=====前置增强=====");
    }

}

结果: 

 注意aop上面必须有一个@Component注解,不然spring无法读取到这个bean,就没办法前置拦截了。

2.后置增强

    @AfterReturning("execution(* testAop(..))")
    public void after(){
        log.info("=====后置增强=====");
    }

3.环绕增强

    @Around("execution(* testAop(..))")
    public void around(ProceedingJoinPoint joinPoint){
        log.info("=====环绕增强开始=====");
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("catch exception",throwable);
        }
        log.info("=====环绕增强结束=====");
    }

 注意这里引入一个ProceedingJoinPoint对象,里面封装了一些关于切面的使用方法,但是这个对象只在环绕注解中生效

4.异常抛出异常

    @AfterThrowing("execution(* testAop(..))")
    public void afterThrowing(){
        log.info("=====抛出异常增强=====");
    }

       还有一种是引介增强,但是我也不怎么使用,这里就不在去记录了,有空的时候去找一下具体的用法,说不定以后能用到呢,哈哈。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值