我正在尝试向我的应用程序添加一个非常简单的方面,该方面负责监视实体中的更改。基本上我想在一个类中的setter被调用之后上升一个标志:
@After("execution(* bg.infosys.avl.transmodel.hibernate.entity.*.set*(*))")
public void entityChangedAdvice(JoinPoint joinPoint){
AvlEntity entity = (AvlEntity) joinPoint.getTarget();
entity.setChanged(true);
}
建议从未运行过,所以我开始尝试更简单的测试,以找出问题所在。我在我的一个名为 getId()的服务中创建了一个测试方法,并在我的xml配置中添加了一个新的建议,如下所示:
<context:annotation-config />
<aop:aspectj-autoproxy />
<!-- ADVICE -->
<bean id="avlEntityChangesAdvice" class="bg.infosys.avl.designer.logging.AvlEntityChangesAdvice"></bean>
<aop:config>
<aop:aspect ref="avlEntityChangesAdvice" id="avlEntityChangesAdviceID" order="1">
<aop:pointcut expression="execution(* bg.infosys.avl.designer.facade.*.*(..))" id="getterPointcut"/>
<aop:after method="entityChangeAdvice" pointcut-ref="getterPointcut" />
</aop:aspect>
</aop:config>
只要包 bg.infosys.avl.designer.facade 中任何类的任何方法都应该调用它。这很有效!
当我更改切入点以定位具有特定名称的方法时:
<context:annotation-config />
<aop:aspectj-autoproxy />
<!-- ADVICE -->
<bean id="avlEntityChangesAdvice" class="bg.infosys.avl.designer.logging.AvlEntityChangesAdvice"></bean>
<aop:config>
<aop:aspect ref="avlEntityChangesAdvice" id="avlEntityChangesAdviceID" order="1">
<aop:pointcut expression="execution(* bg.infosys.avl.designer.facade.*.getId(..))" id="getterPointcut"/>
<aop:after method="entityChangeAdvice" pointcut-ref="getterPointcut" />
</aop:aspect>
</aop:config>
建议根本不被调用。我尝试了各种组合,我尝试了注释,但结果都是一样的。当我尝试定位特定方法或尝试使用像get *这样的通配符时,永远不会调用通知。
我认为这里可能存在一个我不知道的更基本的问题。 有人有什么想法吗?
答案 0 :(得分:1)
在您的情况下,您需要为您的类使用代理,或者您可以实现MethodInterceptor而不是Aspect。因为Spring AOP只适用于spring托管bean。
示例:
@Component
public class Interceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
....do your stuff
}
}