如何将依赖项自动装入Spring @Configuration实例?

时间:2012-10-16 15:47:13

标签: spring spring-mvc configuration annotations

我需要将一个对象注入我的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。

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

1 个答案:

答案 0 :(得分:0)

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