Java 通过向方面传递策略来创建动态建议
我试图根据它提供建议的类/方法,使我的建议更具动态性。正在查找类似以下伪代码的内容:Java 通过向方面传递策略来创建动态建议,java,annotations,aop,aspectj,Java,Annotations,Aop,Aspectj,我试图根据它提供建议的类/方法,使我的建议更具动态性。正在查找类似以下伪代码的内容: class Activity private TheAdviceStrategyInterface activityAdviceStrategy = new ActivityAdviceStrategy(); @Entity(adviceStrategy = activityAdviceStrategy) public void doSomething(ActivityInput ai) { ... }
class Activity
private TheAdviceStrategyInterface activityAdviceStrategy = new ActivityAdviceStrategy();
@Entity(adviceStrategy = activityAdviceStrategy)
public void doSomething(ActivityInput ai) { ... }
当然,我们不能将对象或接口作为注释参数
关于如何实现这一点,有什么“建议”吗?我基本上希望一个方面的注释能够处理非常相似的情况,根据使用注释的类的不同,会有细微的差别
当然,我们不能将对象或接口作为注释
参数。关于如何实现这一点,有什么“建议”吗
1-在实体
界面中创建一个字符串参数,以表示可能的策略:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Entity {
public String adviceStrategy();
}
2-创建一个实现的类,例如:
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;
}
}
通过类AdviceStrategy1
和AdviceStrategy2
实现接口AdviceStrategyInterface
在建议中充分利用这两个方面:
谢谢,我可能会用这个。我也在考虑使用工厂。要么这样,要么重写Advice类中的方法。@john
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Entity {
public String adviceStrategy();
}
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;
}
}
@Aspect
public class TheAdvice {
@Around("@annotation(entity)")
public Object doStuff (ProceedingJoinPoint pjp, Entity entity) {
...
TheAdviceStrategyFactory factory = new TheAdviceStrategyFactory();
TheAdviceStrategyInterface theStrat = factory.getStrategy(entity.adviceStrategy());
....
}
}