Servlet无法将service bean注入,一种方法是重写init()方法手动获取bean:
public void init() throws ServletException {
super.init();
ServletContext servletContext = this.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
wapProductDao = (IWapProductDao) ctx.getBean("IWapProductDaoImpl");
}
另外一种方法是用注解的方法进行注入:
public class DelegatingServletProxy extends GenericServlet {
private static final long serialVersionUID = -3249114289342226808L;
private String targetBean;
private Servlet proxy;
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
proxy.service(req, res);
}
@Override
public void init() throws ServletException {
this.targetBean = getServletName();
getServletBean();
proxy.init(getServletConfig());
}
private void getServletBean() {
WebApplicationContext wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
this.proxy = (Servlet) wac.getBean(targetBean);
}
}
Servlet片段:
@Component("wapServlet")
public class WapServlet extends HttpServlet {
@Resource
private IWapProductDao wapProductDao;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet method\t" + wapProductDao);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
web.xml Servlet配置:
<servlet>
<servlet-name>wapServlet</servlet-name>
<servlet-class>com.fee.servlet.DelegatingServletProxy</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wapServlet</servlet-name>
<url-pattern>/WapServlet</url-pattern>
</servlet-mapping>
通过url进行访问:http://127.0.0.1:8080/Fee/WapServlet