public class MyServlet extends HttpServlet { @Autowired private MyService myService; public void init(ServletConfig config) { super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } }
这样,就不会出现时而成功,时而失败了。 当然也许有人会说,还有其他方法,的确,至少还可以通过 webapplication 让后用 getBean 的方式来拿到 bean , 然后在使用.比如:
public void init(ServletConfig config) throws ServletException { super.init(config); ServletContext servletContext = this.getServletContext(); WebApplicationContext wac = null; wac = WebApplicationContextUtils .getRequiredWebApplicationContext(servletContext); this.setUserServiceService((UserServiceService) wac .getBean("userServiceService"));// Spring 配置 中的 bean id }
这种方式也是一样的,但没有第一种方法优雅.