在servlet中用spring @Autowire注入

时间:2023-03-09 13:06:53
在servlet中用spring @Autowire注入

今天在改版以前应用程序的时候,发现很多系统是直接用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());
} }