2
votes

I've run into a strange problem that I am having difficulty tracking down. I have an class (ServiceErrorInterceptor) defined as an @Aspect which is instantiated via XML configuration as a singleton bean. The XML configuration allows me to inject its dependent beans.

In my normal workflow, everything works fine. The aspect class is properly instantiated, and whenever the advice is called, the injected beans are as I would expect.

However, when I run my JUnit test, all my injected beans are null. This leads me to the conclusion that the advice is called from a different bean - not the same singleton bean that was instantiated by Spring. To further validate my hypothesis, I put a breakpoint on a setter which is called during the instantiation, and see that the bean id is not the same as the bean id if I put a breakpoint in my advice.

Is there some special configuration I must enable in my JUnit class to rectify this? My test class is already annotate with:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { 
        "classpath:spring/applicationContext-base.xml", 
        "classpath:spring/applicationContext-calculateServices.xml", 
        "classpath:spring/applicationContext-dom.xml"})
public class LendingSimulationServiceImplTest {
...
...
}

I've looked through the logs (I enabled spring trace logs), but don't see anything that stands out. And posting the entire log here would likely be overkill. If there is value in a specific part of the log please let me know and I will post it.

I'm able to post my code for the aspect, my junit and my config if that is helpful.

application-context.xml snippet:

<!-- SPRING ASPECT BEAN.  POINTCUT DEFINED IN BEAN WITH ANNOTATION -->
<bean id="serviceErrorInterceptor" class="com.cws.cs.lendingsimulationservice.error.ServiceErrorInterceptor" scope="singleton">
    <property name="errorMessageProvider" ref="resourceBundleProviderImpl"/>
    <property name="defaultLocale">
        <util:constant static-field="java.util.Locale.ENGLISH" />
    </property>
</bean>

Any suggestions would be appreciated.

EDIT

My bean is implemented as:

@Aspect
public class ServiceErrorInterceptor {

    /**
     * Logger
     */
    private static final Logger logger = LoggerFactory.getLogger(ServiceErrorInterceptor.class);

    /**
     * SOAP Header data
     */
    @Autowired
    private SOAPHeaderData soapHeaderData;

    public ServiceErrorInterceptor(){
        int x = 0;
        x=x+1;

    }

    /**
     * Exception Interceptor. 
     * @param ex
     */
    @AfterThrowing(pointcut = "execution(* com.cws.cs.lendingsimulationservice.process.CalculatorProcess.calculate (..))", throwing = "ex")
    public void errorInterceptor(Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error Message Interceptor started");
        }

    }

The relevant portions of my pom:

    <!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core, 
        spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <!-- Support for AspectJ Annotations -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${org.aspectj}</version>
    </dependency>

I've done further debugging and putting a breakpoint in the dummy constructor, I get the following results:

  • with @Aspect and XML configuration, the constructor is called twice (different bean ids)
  • if I remove the @Aspect annotation then it is only called once.
  • If leave the @Aspect but remove the XML configuration, then the constructor isn't even called.
  • If I use an @Component annotation in combination with @Aspect (but without any XML configuration), then the bean is constructed twice.
  • Oddly enough, however, with both the @Component and @Aspect annotations AND the XML configuration, the constructor is still only called twice.

So then why would having both the XML configuration and the @Aspect annotation cause the constructor to be called twice with two different bean ids?

I have further validated that if I move the entire AOP definition into the XML configuration (removing the @Aspect and @Pointcut annotations) then the bean is only constructed once.

END EDIT

Thanks,

Eric

3

3 Answers

1
votes

Does your aspect by any chance have any of the autodetect annotations (@Component, @Service) etc, apart from @Aspect - if it does, that could be one reason why a different bean seems to be present along with the one defined in your configuration.

Also, just scan through all your configuration to make sure that you are not declaring this bean elsewhere.

There is nothing special that needs to be done at the Junit level that I am aware of.

1
votes

After a lot of discussion with the folks over at the SpringSource STS forum (see this thread), it turns out that the issue is related to the AJDT configuration. At the moment, AJ is weaving in the aspect, and Spring is locating the aspect on the Classpath, so they are both being executed.

Unfortunately, the AJ maven plugin is missing a configuration parameter to allow for exclusion of weaving; the current configuration excludes both LTW and CTW.

So, the workaround at the moment is to add -xmlConfigured to the AJ compiler flags and then specify an aop.xml file in aop.xml management which only lists the AJ aspects that you want to include in the project.

To get this to work, add '-xmlConfigured' to the Project Properties 'Non-standard compiler options' and then in AspectJBuild>'aop.xml management' point it at a simple aop.xml file:

<aspectj> 
    <aspects> 
       <aspect name="com.fooMyNewNoneSpringAspect"/>
    </aspects> 
</aspectj>

Thanks to Andy Clement at the STS forum for this discovery and workaround. He will be raising JIRA issues to further address this shortcoming in the maven plugin.

0
votes

A possible way you might find yourself in the same situation: you used the new operator rather than letting Spring inject your service.

Remember, we're not in AspectJ compile time weaving here. Nope, we're using Spring AOP proxies, so Spring must instantiate the object and dress it with proxies. If you were silly, like myself, and created a new service inside your tests, you won't get any AOP.

All the more reason to do compile time weaving with AspectJ and skip over all of the drawbacks of Spring AOP such as runtime weaving startup delay, inability to weave non-public and non-final classes.