您的位置:首页 > 编程语言 > Java开发

Spring向Servlet中注入实例

2016-03-29 09:30 369 查看
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等的。当然,写了,也不影响使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: