2016-05-16 109 views
5

在我的方法中,我所有的代码都位于if块中,用于测试某些条件。用于确定注释方法是否执行的Java注释

public void myMethod() { 
    if (/* some condition */) { 
     //do something 
    } 
} 

我想通过注释来做到这一点 - 这意味着注释将执行一些代码来“决定”是否应该调用该方法。

@AllowInvokeMethod(/* some parameters to decide */) 
public void myMethod() { 
    //do something (if annotation allows invokation) 
} 

这可能吗?

回答

4

您可以使用Spring AOP创建一个方面提醒,被注释您的自定义注释方法

例如创建一个FilteredExecution注释要对你的方法指定

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface FilteredExecution{ 
    Class<? extends ExecutionFilter> value(); 
} 

ExecutionFilter是决定执行是否应该发生

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 
    } 

你需要设置你的上下文,以便你的bean自定义注释是由usin自动代理的g @EnableAspectjAutoProxy在您的配置类

0

你可以试试这个,上面的metoh文档。 这个注释是节目当方法是调用,并查看 文档meothd

/** 
     * descripcion of the method 
     * @param value , any value 
     */ 
    public void myMethod(String value) { 
    //do something (if annotation allows invokation) 
} 

,如果你把这个结构,你无法看到的文档,当你 调用一些方法,,

//descripcion of the method 
    public void myMethod(String value) { 
     //do something (if annotation allows invokation) 
    } 

在我的情况,它的作品,我希望这对你的作品

+0

“此注释显示方法调用时,并看到文件meothd”不是真的。您可以基于javadoc-comments生成html页面,但是在“调用方法”时不会显示它们。你的意思是任何机会IDE的工具提示?你的回答没有解决OP的问题。 – Turing85

相关问题