問題:Spring初始化HttpServlet不是用@Comonent的方式,所以用@Autowired無法注入bean。
解決:可以實現init方法,在裏面綁定bean,方式如下(假設要注入的bean類爲A):
......
private A a;
@Override
public void init() throws ServletException {
super.init();
ServletContext servletContext = this.getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
this.a = (A) context.getBean("a");
}
......