我遇到組件自動裝配的問題。如何在避免使用null @Autowired的接口實現中自動裝配組件?
我的實現包含在Controller中,Controller使用的接口和實現thagt接口的Component。 我想在實現中自動裝配另一個組件。
這是控制器:
@Controller
public class MyController {
@RequestMapping(path = "/myPath/{subpath}", method = RequestMethod.GET)
public void myMethod(@PathVariable("subpath") String subpath, HttpServletResponse response){
try{
MyHandler handler = new MyHandlerImpl(response.getOutputStream());
handler.handle();
} catch (Exception e) {
}
}
}
這是接口:
public interface MyHandler {
public void handle();
}
這是實施:
// tried all: @Component, @Service, @Repository, @Configurable
public class MyHandlerImpl implements MyHandler {
@Autowired
MyComponentToAutowired myComponentToAutowired; // <= this is NULL
public MyHandlerImpl (ServletOutputStream output) {
this.output = output;
}
private OutputStream output;
public void handle() {
myComponentToAutowired.theMethod(); // <- NullPointerException at this point
// ...
}
/*
If I don't create a default constructor, Spring crash at the start because it not finds the default constructor with no-args.
*/
}
我能做些什麼,以正確自動裝配組件?
感謝。
創建一個單例MyHandlerImpl bean並將ServletOutputStream傳遞給它的handle句柄。或者在每個請求上創建自己的'MyHandlerImpl'實例,並將'MyComponentToAutowired' bean傳遞給它的'handle'方法。 –