我需要几个类中的方法,这些方法必须始终遵循特定的前后模式。
公共(public)无效方法(X x,Y y){
//************重复部分开始 ******************/
AFrameworkClass aFrameworkClass = new AFrameworkClass(this.memberVariable,"SomeString");
尝试{
aFrameworkClass.aFrameworkMethod( x,y);
aFrameworkClass.anotherFrameworkMethod(x,y);
aFrameworkClass.yetAnotherFrameworkMethod(x);
aFrameworkClass.doPreProcessing();
Throwable t = null ;
//************重复部分结束 ******************/
try {
// code will vary according to the business logic
}
catch (Throwable t) {
// code will vary according to the business logic
}
//************重复部分开始 ******************/
aFrameworkClass.doPostProcessing();
} 最后 { aFrameworkClass.doCleanup();
}
//************重复部分结束 ******************/
}
是否可以使用 Spring 框架来完成此方法中重复部分的逻辑,而不必在我的各个类中一遍又一遍地编写这些行?如果是这样怎么办?
最佳答案
绝对可以通过 Spring 的 AOP 支持来完成。您可以将第一部分应用为“before”建议,将第二部分应用为“after-final”建议,或者您可以将两者应用为“around”建议并以编程方式调用目标方法,如下所示:
methodInvocation.invoke(); // returns Object
如果您想在 XML 中声明您的方面,您可以在此处阅读有关如何执行此操作的信息:
http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema-advice-before http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema-advice-after-finally http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj-around-advice
或者,如果您想使用注释来完成此操作,请参阅此处的信息:
http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj
我个人更喜欢使用 XML 来完成此操作,因为无需重新编译应用程序即可更改方面的行为。假设您有一个多模块项目,其中 B 依赖于 A。A 包含可重用建议,并使用顺序、切入点等注释。如果您需要更改该行为,则必须重建 A。如果您在项目 B 中使用 XML要从项目 A 配置方面,不需要重建 A。
我的感觉是,当您在类中定义行为以及如何在 XML 中应用该行为时,建议的可重用性更高。
关于Spring 依赖注入(inject)或切面编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/437373/