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

servlet 中使用Spring自动注入的bean

2010-04-22 16:53 447 查看
编写一个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注入什么样的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: