@Autowired 不适用于拦截器 [英] @Autowired doesn't work with interceptor

查看:56
本文介绍了@Autowired 不适用于拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用 Apache-CXF 开发的 REST 服务.我正在使用 Spring 3.1 注释来连接 bean.我编写了一个拦截器,它拦截我的 REST 方法以进行监控.为此,我必须自动装配我的 Monitor 类,该类作为库添加到我的项目中.@Autowired 在这种情况下似乎不起作用,并导致 NPE.我在这里做错了什么吗?

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

应用程序上下文:

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

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

推荐答案

这个博客

aspect 是一个单例对象,是在 Spring 容器之外创建的.XML 配置的一个解决方案是使用 Spring 的工厂方法来检索方面.

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

使用此配置,方面将被视为任何其他 Spring bean,并且自动装配将正常工作.

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

这篇关于@Autowired 不适用于拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆