我正在尝试向我的应用程序添加一个非常简单的方面,该方面负责监视实体的更改。基本上我想在类中的 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* 这样的通配符时,永远不会调用建议。
我认为这里可能存在一个我没有意识到的更根本的问题。 大家有什么想法吗?
最佳答案
在您的情况下,您需要为您的类使用代理,或者您可以实现 MethodInterceptor 而不是 Aspect。因为 Spring AOP 仅适用于 Spring 管理的 bean。
示例:
@Component
public class Interceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
....do your stuff
}
}
关于java - Spring Aspect 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146440/