【发布时间】: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