繁体   English   中英

@Autowired不适用于拦截器

[英]@Autowired doesn't work with interceptor

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

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

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

我不是Spring的高手,但据我所知,我将尽我最大的努力来表达。

我想您已经注意到了,但是@Aspect不是基于spring的,因此要对其进行扫描,您需要添加<aop:aspectj-autoproxy/> ,此外,我认为问题在于正在创建同一类的两个实例,每个容器一个(spring和AspectJ),以避免使用工厂方法来检索与spring容器完全相同的实例(如果我解释正确,我不确定100%),-请记住首先用以下方式创建方面的一个:

<bean id="id_of_your_bean" class="ApplicationMonitoring" factory-method="aspectOf">
     //other stuff
</bean>

此博客中找到了解决方案

方面是一个单例对象,在Spring容器外部创建。 使用XML配置的解决方案是使用Spring的factory方法检索方面。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM