Spring向Servlet中注入实例
开发Http接口的过程中,发现在Servlet中,无论是用spring 的什么注解,都无法正常的向Servlet中注入实例,但是在方法中通过
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Ctx.getBean("");
的方式,是可以得到实例的,说明实例已经被spring IOC容器管理。
后来发现,是spring注解不支持在Servlet中注入,如果需要在servlet中注入实例,需要重写servlet的init()方法。
public void init() throws ServletException {
super.init();
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
setServerRunDataService((ServerRunDataService)ctx.getBean(""));
}
其它的地方。可以按照普通的开发方式开发。
使用这种方式,在属性上是不需要再显示的写上@Resource, @Autowired等的。当然,写了,也不影响使用。
开发Http接口的过程中,发现在Servlet中,无论是用spring 的什么注解,都无法正常的向Servlet中注入实例,但是在方法中通过
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Ctx.getBean("");
的方式,是可以得到实例的,说明实例已经被spring IOC容器管理。
后来发现,是spring注解不支持在Servlet中注入,如果需要在servlet中注入实例,需要重写servlet的init()方法。
public void init() throws ServletException {
super.init();
ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
setServerRunDataService((ServerRunDataService)ctx.getBean(""));
}
其它的地方。可以按照普通的开发方式开发。
使用这种方式,在属性上是不需要再显示的写上@Resource, @Autowired等的。当然,写了,也不影响使用。