用servlet的时候遇到一个问题,想往servlet中直接注入Spring的bean,但是servlet是由web容器管理的,不能将其交给spring进行管理,但是用如下方法可以完成:
一、编写一个servlet代理,如下:
public class DelegatingServletProxy extends GenericServlet{
private static final long serialVersionUID = 1L;
private String targetBean;//目标bean
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);
}
}
二、在web.xml中配置Spring自动加载的监听,用以启动Spring容器,配置需要的servlet,并将servlet的类指向刚才的代理。
三、编写一个bean,继承自HttpServlet,它将是响应请求的servlet。然后在applicationContext.xml中为其注入,要注意注入bean的名字需和web.xml中写的servlet的servlet-name一致。然后可以随便为这个bean注入什么样的值。
另外还可以用filter的方式,使用如下两个filter:
org.springframework.security.util.FilterToBeanProxy,
org.springframework.web.filter.DelegatingFilterProxy