簡體   English   中英

Java批注以確定被批注的方法是否執行

[英]Java annotation to determine whether the annotated method executes

在我的方法中,我所有的代碼都在if塊中,用於測試某些條件。

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是一個決定是否執行執行的接口

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。

您可以嘗試一下,在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)
    }

就我而言,它有效,我希望這對您有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM