【问题标题】:How do I autowire dependencies into Spring @Configuration instances?如何将依赖项自动装配到 Spring @Configuration 实例中?
【发布时间】:2012-10-16 15:47:13
【问题描述】:

我需要将一个对象注入到我的 No XML Spring @Configuration 对象中,如下所示:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "web.client")
public class WebApplicationConfiguration extends WebMvcConfigurerAdapter {

private static final Logger log = LoggerFactory.getLogger(WebApplicationConfiguration.class);

@Inject
private MonitoringExceptionResolver resolver;  // always null

@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    log.debug("configuring exception resolvers");
    super.configureHandlerExceptionResolvers(exceptionResolvers);
    exceptionResolvers.add(new DefaultHandlerExceptionResolver());
    exceptionResolvers.add(new AnnotationMethodHandlerExceptionResolver());
    exceptionResolvers.add(new ResponseStatusExceptionResolver());
    exceptionResolvers.add(resolver);  // passing null ref here
}

}

其中MonitoringExceptionResolver定义如下:

@Service
public class MonitoringExceptionResolver implements HandlerExceptionResolver {

private final Counters counters;

@Inject
public MonitoringExceptionResolver(Counters counters) {
    super();
    this.counters = counters;
}

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    Counter counter = counters.getCounterFor(ex.getClass());
    if(counter != null) {
        counter.increment();
    }
    return null;
}

}

但是,我在执行链的后期得到 NPE,因为上面的“解析器”字段为空,即使我使用 @Autowired。

其他类正在使用组件扫描成功连接到其他地方。为什么上面总是为空?我做错了吗?

【问题讨论】:

  • 你试过用@Autowired 代替@Inject 吗?
  • 在哪里声明要自动装配或注入的对象?因为在使用这些注解之前,应该在上下文中声明 bean。
  • @SeanPatrickFloyd 是的,我已经在上面提到了这一点。
  • @JonathanCruz 我认为@Configuration 是在上下文中包含对象的声明。我是否还需要使用 @Service 之类的原型注解来注解 @Configuration 类?
  • @Ricardo Gladwell 我不确定,但我会尝试将它添加到您的 applicationContext.xml 或 webcontext。 @ 配置也应该可以工作,但我认为它是最近推出的,所以它可能并不总是正常工作。我相信它从春季 3.0 开始。如果你使用@service,你应该能够自动装配它。

标签: spring spring-mvc configuration annotations


【解决方案1】:

@Inject 和 @Autowired 在 Spring 中的工作方式应该非常相似。 确保使用中的*BeanPostProcessor 知道MonitoringExceptionResolver:将其标记为@Component 并使其成为某个@ComponentScan 的主题,或者使@Bean 工厂方法成为某个正在使用的@Configuration 类。

【讨论】:

  • 从上面的代码片段中,@ComponentScan 已启用,我确实提到了对象已成功连接。
猜你喜欢
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 2012-10-27
  • 2011-12-31
  • 1970-01-01
相关资源
最近更新 更多