在servlet中用spring @Autowire 注入.

摘要: 今天在改版以前老应用程序的时候,发现很多系统是直接用servlet做的,当初也用到了 spring, 所以自然想到也用 spring 的 @autowire 注入 来引入 service 层, 但发现如果直接用,有时候成功,有时候报错,失败。貌似就是不稳定,一直搞不清楚原因, 后来在网上找到了一个简单的方法. 这个简单的方法也是  spring 提供的,解决方法如下

今天在改版以前老应用程序的时候,发现很多系统是直接用servlet做的,当初也用到了 spring, 所以自然想到也用 spring 的 @autowire 注入 来引入 service 层, 但发现如果直接用,有时候成功,有时候报错,失败。貌似就是不稳定,一直搞不清楚原因, 后来在网上找到了一个简单的方法. 这个简单的方法也是 spring 提供的,解决方法如下:

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
	}


这种方式也是一样的,但没有第一种方法优雅.

上一篇: Java里各种路径的区别:getPath(), getCanonicalPath()
下一篇: jsp不支持${pageContext.request.contextPath} jstl表达式
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号