Radostin Tonev
Radostin Tonev

Reputation: 21

Spring Aspect not working as it should

I am trying to add a very simple aspect to my application which is responsible for monitoring changes in entities. Basically I want to rise a flag after a setter within a class is called like this:

@After("execution(* bg.infosys.avl.transmodel.hibernate.entity.*.set*(*))")
public void entityChangedAdvice(JoinPoint joinPoint){
    AvlEntity entity = (AvlEntity) joinPoint.getTarget();
    entity.setChanged(true);
}

The Advice never ran so I started to try more simple tests in order to find where the problem is. I created a test method in one of my services called getId() and I added a new advice in my xml configuration like this:

<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>   

It should be called whenever any method from any class in the package bg.infosys.avl.designer.facade . This worked!

When I change the pointcut to target a method with specific name like this:

<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>   

The advice is not called at all. I tried all kinds of combinations, I tried with annotations, but the result is all the same. When I try to target a specific method or try to use a wildcard like get* the advice is never called.

I figured that there might be a more fundamental problem here that I am unaware of. Anyone have any ideas?

Upvotes: 2

Views: 1823

Answers (1)

Egor K.
Egor K.

Reputation: 171

In your case you need to use proxy for your class, or you can implements MethodInterceptor instead of Aspect. Because Spring AOP working only for spring managed beans.

example:

@Component
public class Interceptor implements MethodInterceptor {


@Override
public Object invoke(MethodInvocation invocation) throws Throwable {

 ....do your stuff

   }

}

Upvotes: 1

Related Questions