我需要注入對象到我沒有XML春@Configuration對象如下:如何在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。 – fonZ
@SeanPatrickFloyd是的,我已經在上面提到過了。 –