通过将策略传递给 Aspect 来创建动态建议

问题描述

我试图根据它提供建议的类/方法使我的建议更加动态。寻找类似这个伪代码的东西:

class Activity
   private TheAdviceStrategyInterface activityAdviceStrategy = new ActivityAdviceStrategy();

@Entity(adviceStrategy = activityAdviceStrategy)
public void doSomething(ActivityInput ai) { ... }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Entity {
    public TheAdviceStrategyInterface adviceStrategy();
}
@Aspect
public class TheAdvice {
    @Around("@annotation(entity)")
    public Object doStuff (ProceedingJoinPoint pjp,Entity entity) { 
        ...
        TheAdviceStrategyInterface theStrat = entity.adviceStrategy();
        ....
    }

}

当然我们不能有对象或接口作为注解参数。

关于我如何实现这一点的任何“建议”?我基本上想要一个 Aspect 注释来处理非常相似的情况,略有不同,具体取决于哪个类使用该注释。

解决方法

当然我们不能有对象或接口作为注解 参数。关于如何实现这一点的任何“建议”?

1- 在 Entity 接口中创建一个 String 参数来表示可能的策略:

@Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Entity {
        public String adviceStrategy();
    }

2- 创建一个实现 factory pattern 的类,例如:

public class TheAdviceStrategyFactory {
    
   //use getShape method to get object of type shape 
   public TheAdviceStrategyInterface getStrategy(String strategy){
      if(strategy == null){
         return null;
      }     
      if(strategy.equalsIgnoreCase("Strategy1")){
         return new TheAdviceStrategy1();
         
      } else if(strategy.equalsIgnoreCase("Strategy2")){
         return new TheAdviceStrategy2();
      
      return null;
   }
}

使用类 TheAdviceStrategy1TheAdviceStrategy2 实现接口 TheAdviceStrategyInterface

建议中充分利用两者:

@Aspect
public class TheAdvice {
    @Around("@annotation(entity)")
    public Object doStuff (ProceedingJoinPoint pjp,Entity entity) { 
        ...
        TheAdviceStrategyFactory factory = new TheAdviceStrategyFactory(); 
        TheAdviceStrategyInterface theStrat = factory.getStrategy(entity.adviceStrategy());
        ....
    }

}