因此,我的问题主要围绕将Spring AOP与基于XML的架构结合使用,而不是与AspectJ结合使用。通过在线浏览,我一直在尝试找出采用AOP的方法。一种情况使我有些困惑。
假设我有许多具有n个方法的类,并且我想将我的方面类的建议应用于某些方法/连接点,但不是全部,我可以看到在使用AspectJ时这将非常简单-我只是应用我的方面注释应使用建议的方法。但是,从我所看到的基于xml的方法的角度来看,我必须为这些方法中的每一个创建一个切入点(假设它们不能被一个表达式覆盖,即每个方法都有一个不同的名称)和(如果我是使用基于代理的方法)每个目标/类的代理类。从这个意义上讲,AspectJ方法看起来更整洁。
那么,我对这两种方法的理解是正确的,还是我错过了可以实现xml方法更整洁解决方案的Spring AOP的某些部分?
很抱歉,冗长的解释,但我想让情况尽可能清楚...
听起来您正在尝试在Spring AOP和AspectJ之间做出选择,但是您假设Spring AOP需要基于XML的配置。没有。您可以对Spring AOP和AspectJ都使用AspectJ批注:
package com.example.app;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
@Aspect
public class NotificationAspect {
@Autowired private NotificationGateway notificationGateway;
@Pointcut("execution(* com.example.app.ItemDeleter.delete(com.example.app.Item))")
private void deleteItemOps() { }
@AfterReturning(pointcut = "deleteItemOps() && args(item)")
public void notifyDelete(Item item) {
notificationGateway.notify(item, ConfigManagementEvent.OP_DELETE);
}
}
因此,如果您尝试比较Spring AOP和AspectJ,则将AspectJ与基于注释的Spring AOP进行比较比较明智。
Spring AOP通常更简单(您不需要AspectJ编译器);因此,除非您需要更多特殊的切入点,否则参考文档建议使用Spring AOP而不是AspectJ。
更新:响应以下OP的评论,我们可以使用XML配置来建议特定的方法:
<aop:config>
<aop:pointcut
id="deleteItemOps"
expression="execution(* com.example.app.ItemDeleter.delete(com.example.app.Item))" />
<aop:advisor
advice-ref="notificationAdvice"
pointcut-ref="deleteItemOps() && args(item)" />
</aop:config>
如果您想将切入点直接嵌入中<aop:advisor>
,也可以这样做:
<aop:config>
<aop:advisor
advice-ref="notificationAdvice"
pointcut="execution(* com.example.app.ItemDeleter.delete(com.example.app.Item)) && args(item)" />
</aop:config>
(我还没有检查&& args(item)
XML配置的一部分,但是我认为我给出的示例是可以的。如果它不起作用,请尝试将其删除并随意相应地编辑答案。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句