【发布时间】:2021-12-29 13:34:07
【问题描述】:
我有一个自定义注解如下
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Testable {
int index();
}
我定义了一个 Aspect 来包裹实际的方法调用
@Aspect
@Component
public class TestableAspect {
@Around("execution(public * *(..)) && @annotation(annotation)")
public Object invokeAndLog(ProceedingJoinPoint joinPoint, Testable annotation) throws Throwable {
return joinPoint.proceed();
}
}
注解的用法如下图
@Testable(index = 1)
public void realMethod() {
//some code here
}
到目前为止一切正常,我可以在 TestableAspect#invokeAndLog 中实现我的登录。
现在我需要验证 index 的值是否不大于 10 例如。
我可以在运行时通过如下更改方面实现来做到这一点
@Around("execution(public * *(..)) && @annotation(annotation)")
public Object invokeAndLog(ProceedingJoinPoint joinPoint, Testable annotation) throws Throwable {
if(annotation.index() > 10){
throw new IllegalStateException("blah");
}
return joinPoint.proceed();
}
但这要求 API 至少被调用一次,而且效率不高。 有没有办法在启动 Spring Boot 应用程序时做到这一点?
【问题讨论】:
-
我想建议和西蒙一样。但是,如果注释可以在 OP 自己的构建过程控制之外的模块中使用,这可能不是一个选项。应该选择哪种方法还取决于实际检查注释条件的实际条件是静态的还是动态的。如果例如它总是
> 10,然后可以在更中心的点进行验证。如果条件根据应用程序状态而变化,则切面实际上可能是更好的方法。
标签: java spring-boot aspectj spring-aop