AOP示例

在Spring Boot AOP中,可以使用不同类型的切面来定义切点和通知的逻辑。以下是常见的切面类型:

@Before:在目标方法执行之前执行通知。

@After:在目标方法执行之后执行通知,无论方法是否发生异常。

@AfterReturning:在目标方法正常返回后执行通知。

@AfterThrowing:在目标方法抛出异常后执行通知。

@Around:在目标方法前后执行通知,可以控制目标方法的执行。

@Order:用于指定切面的执行顺序,数值越小优先级越高。
通过组合使用上述不同类型的切面,可以实现更复杂的AOP逻辑。例如,可以在@Before通知中进行参数验证,在@AfterReturning通知中记录日志,在@AfterThrowing通知中处理异常等。
除了以上常见的切面类型,还可以自定义切面类型。可以通过实现org.aspectj.lang.annotation.Aspect接口或者使用其他自定义注解来定义切面类型。

@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.YourService.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        System.out.println("执行前日志记录:" + joinPoint.getSignature().getName());
    }
  
    @AfterReturning(pointcut = "execution(* com.example.YourService.*(..))", returning = "result")
    public void afterMethod(JoinPoint joinPoint, Object result) {
        System.out.println("执行后日志记录:" + joinPoint.getSignature().getName());
        System.out.println("返回值:" + result);
    }
}

在上述示例中,我们使用@Aspect注解标记切面类,并使用@Before和@AfterReturning注解定义了两个通知方法。@Before注解表示在目标方法执行前执行,@AfterReturning注解表示在目标方法正常返回后执行。
最后,创建一个服务类,在该类的方法上添加切面注解

@Service
public class YourService {
    @LogBefore
    public void doSomething() {
        System.out.println("执行业务逻辑");
    }
    
    @LogAfterReturning
    public String getResult() {
        return "返回结果";
    }
}
@SpringBootApplication
@EnableAspectJAutoProxy
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

在Spring Boot项目的配置类上添加@EnableAspectJAutoProxy注解,启用AOP代理:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr_树先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值