spring 基于注解实现aop详细实现代码

需要的包:

没有aspectjrt的话会找不到@AspectJ注解
需要的包
除了以上两个之外,只需要导入

	<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

代码

@Component
@Aspect
@Slf4j
@EnableAspectJAutoProxy//配置允许自动配置切面
public class LogAspectAnnotation {

    @Before("execution(public com.hjf.student.entity.Card getCardById(String))")
    //JoinPoint可以获取切入点方法的信息
    public void before(JoinPoint joinPoint){
        log.debug("aspectJ before");
    }

    @After("execution(public com.hjf.student.entity.Card getCardById(String))")
    public void after(JoinPoint joinPoint){
        log.debug("aspectJ after 最终通知");
    }

    //需要指定接收异常的参数名:throwing = "exception"
    @AfterThrowing(pointcut = "execution(public com.hjf.student.entity.Card getCardById(String))",throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint,Exception exception){
        log.debug("aspectJ afterThrowing");
    }

    //需要指定接收返回值的参数名:returning = "returnValue"
    @AfterReturning(pointcut = "execution(public com.hjf.student.entity.Card getCardById(String))",returning = "returnValue")
    public void afterReturning(JoinPoint joinPoint,Object returnValue){
        log.debug("aspectJ afterReturning 后置通知");
    }

    @Around("execution(public com.hjf.student.entity.Card getCardById(String))")
    public Object around(ProceedingJoinPoint pjp){
        Object target=null;
        try {
            log.debug("aspectJ around 前置通知");
            target = pjp.proceed();
            log.debug("aspectJ around 后置通知");
        } catch (Throwable e) {
            log.debug("aspectJ around 异常通知");
        } finally {
            log.debug("aspectJ around 最终通知");
        }
        return target;
    }
}

另需要配置以下两种的其中一种

  1. 在xml配置文件中开启
<aop:aspectj-autoproxy/>

或者
在切面方法中开启注解

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值