Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Aspect not executed when defined in other JAR

I have a project consisting of two subprojects which are both Spring projects and have an applicationContext.xml each.

One is a framework project (which ends up as a JAR) and one is the actual application (which ends up as a WAR and depends on the JAR and imports the JAR's applicationContext.xml into it's own applicationContext.xml).

In the framework project, I've defined an aspect for all public methods.

@Aspect
@Configurable
public class MyAspect {

    @Autowired
    private SomeBean mBean;

    @Pointcut("execution(public * *(..))")
    public void anyPublicMethod() {
    }

    @Before("anyPublicMethod()")
    public void checkAuthorization(JoinPoint pJoinPoint) {
        mBean.doSomething();
    }
}

And I've activated AOP in the applicationContext.xml of the framework (which is imported by the applicationContext.xml of the actual application project).

...
    <context:spring-configured />

    <context:component-scan base-package="com.mypackage" />

    <aop:aspectj-autoproxy/>
...

When testing in the framework project, the aspect gets executed as expected when calling public methods on Spring beans.

As stated above, the framework project is included in the application project as a dependency but the aspect is not executed when calling matching methods (any public) in the application project on any Spring beans.

I've also tried using XML configuration of the aspect. That lead to the same behavior.

like image 908
tobiasbayer Avatar asked Apr 18 '12 06:04

tobiasbayer


1 Answers

IMHO, you can tweak the approach slightly.

The first thing I would do is to delegate configuration of the application context for the war to the web.xml :

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/spring*.xml</param-value>
</context-param>

Secondly I would enable aop in you war file's application context, as this is where you want to use it. It sounds, at the moment, like you are importing the application context with aop configuration just to get it in your web project, which is maybe wrong.

Finally i'm making the assumption that these are runtime and not compiled aspects, in the latter case you would need to recompile with aspectj in your war project regardless of the dependency.

like image 141
MikePatel Avatar answered Oct 27 '22 00:10

MikePatel