Search code examples
javaspringrestspring-aopspring-annotations

@Autowired doesn't work with interceptor


I'm working on REST service which is developed using Apache-CXF. I'm using Spring 3.1 annotations for wiring the bean. I have written an interceptor which intercepts my REST method for monitoring purposes. To do this, i have to autowire my Monitor class which is added as library in my project. @Autowired doesn't seems to be working in this case and results into NPE. Am i doing anything wrong here ?

@Aspect
@Component
public class ApplicationMonitoring {

Logger logger = LoggerFactory.getLogger(ApplicationMonitoring.class);

@Autowired
private Monitor monitor;

@Around("execution(* com.abc.xyz.rest.CustomerResource.getCustomerByAccountNumber(..))")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
    String methodName = joinPoint.getSignature().getName();

    long start = System.currentTimeMillis();
    try {
        // proceed to original method call
        Object result = joinPoint.proceed();
        monitor.elapsedTime(methodName, System.currentTimeMillis() - start);
            return result;
    } catch (Exception e) {
        throw e;
    }
}

ApplicationContext:

.................
......
<context:spring-configured />

<context:component-scan base-package="com.abc">
    <context:exclude-filter expression="org.springframework.stereotype.Controller"
        type="annotation" />
</context:component-scan>

<context:annotation-config/>  

.............

Solution

  • Found the solution in this blog

    The aspect is a singleton object and is created outside the Spring container. A solution with XML configuration is to use Spring's factory method to retrieve the aspect.

    <bean id="monitoringAspect" class="com.myaapp.ApplicationMonitoring" 
       factory-method="aspectOf" />
    

    With this configuration the aspect will be treated as any other Spring bean and the autowiring will work as normal.