在我的方法中,我所有的代码都在一个 if block 中,用于测试特定条件。
public void myMethod() {
if (/* some condition */) {
//do something
}
}
我想通过注释来做到这一点——这意味着注释将执行一些代码,这些代码将“决定”是否应该调用该方法。
@AllowInvokeMethod(/* some parameters to decide */)
public void myMethod() {
//do something (if annotation allows invokation)
}
这可能吗?
最佳答案
您可以使用 Spring AOP 创建一个 ASpect 来建议注释您的自定义注释的方法
例如,创建一个 FilteredExecution 注释以在您的方法上指定
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FilteredExecution{
Class<? extends ExecutionFilter> value();
}
ExecutionFilter 是决定是否执行的接口(interface)
public interface ExecutionFilter{
boolean sholudExecute();
}
然后是看点
@Aspect
@Component
public class FilteredExceutionAspect{
@Around("@annotion(filterAnnotation)")
public void filter(ProceedingJoinPoint pjp , FilteredExecution filterAnnotation){
boolean shouldExecute = checkShouldExecute(filterAnnotation);
if(shouldExecute){
pjp.proceed();
}
}
private boolean checkShouldExecute(FilteredExecution filterAnnotation){
//use reflection to invoke the ExecutionFilter specified on filterAnnotatoon
}
您需要设置您的上下文,以便通过在您的配置类上使用@EnableAspectjAutoProxy 自动代理带有自定义注解的bean
关于java注解判断被注解的方法是否执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248854/