因此,我的问题围绕着如何使用Spring和基于XML的模式,而不是在AspectJ中使用。从网上环顾四周,我一直在试图找出AOP应该采取的方法。一个特殊的场景让我有点困惑;
假设我有许多有n个方法的类,并且我想将我的方面类中的通知应用到某些方法/连接点,但不是全部,我可以看到当使用AspectJ时,这是相当简单的--我只是将我的方面注释应用于应该使用该通知的方法。但是,根据我所看到的基于xml的方法,我必须为这些方法中的每一个创建一个切入点(假设它们不能被一个表达式所涵盖--即每个方法都有一个不同的名称),并且(如果我使用基于代理的方法),为每个目标/类创建一个代理类。从这个意义上说,AspectJ方法似乎要整洁得多。
那么,我对这两种方法的理解是正确的,还是遗漏了Spring的某些部分,这些部分可以为xml方法实现更整洁的解决方案?
很抱歉解释得太长了,但我想尽可能的说清楚.
发布于 2014-10-11 16:29:41
听起来您正在尝试在Spring和AspectJ之间做出决定,但是您假设Spring需要基于XML的配置。您可以为Spring和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和AspectJ,那么比较AspectJ与基于注释的Spring更为明智。
Spring通常更简单(您不需要AspectJ编译器);因此,参考文档推荐Spring而不是AspectJ,除非需要更多异国情调的切入点。
XML :响应OP下面的评论,我们可以使用配置来建议具体的方法:
<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>
(我还没有检查XML的&& args(item)
部分,但我认为我给出的示例可以这样做。如果它不起作用,试着删除它,并相应地编辑答案。
https://stackoverflow.com/questions/26320490
复制相似问题