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

在servlet中用spring @Autowire注入

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

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

public class MyServlet extends HttpServlet {

@Autowired
private MyService myService;

public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: