【问题标题】:@Autowired doesn't work with interceptor@Autowired 不适用于拦截器
【发布时间】:2013-11-07 14:39:56
【问题描述】:

我正在开发使用 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;
    }
}

应用程序上下文:

.................
......
<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 上显示您对组件进行扫描的上下文?
  • @SotiriosDelimanolis 我已经用 applicationContext 更新了原始帖子
  • 这个问题通常发生在 Spring bean 的注解最终会生成 2 个代理(例如事务和方面)时。 Spring 能够生成其中一个代理,但随后它会“丢失”元数据以创建第二个代理。避免这种情况的一种方法是使用 aspectj 编译时编织器,因为某些方面将在编译时添加。

标签: java spring rest spring-aop spring-annotations


【解决方案1】:

我不是 Spring 的高手,但据我所知,我会尽量用语言表达出来。

我想你注意到了,但是@Aspect 不是基于弹簧的,所以为了扫描它你需要添加&lt;aop:aspectj-autoproxy/&gt;,此外我认为问题是正在创建同一个类的两个实例,一个对于每个容器(spring和AspectJ),为了避免我使用工厂方法将完全相同的实例检索到spring容器(如果我解释得当,我不确定100%), - 请记住一个方面是首先创建的 - 以这样的方式:

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

【讨论】:

    【解决方案2】:

    this blog找到解决方案

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 2015-02-23
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多