转载

Spring容器启动后注入service到Servlet并自动执行

通常做法是定义一个Servlet,并在web.xml中配置Servlet的启动顺序<load-on-startup>的值在DispatcherServlet之后。但这样做的缺点是在Servlet中无法使用Spring的依赖注入功能,只能使用WebApplicationContext的getBean()方法获取bean。 找到的解决办法如下: 1、自定义一个用于代理启动Servlet的类DelegatingServletProxy:
package cn.edu.swu.oa.common.util;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class DelegatingServletProxy extends GenericServlet {

	private String targetBean;
	private Servlet proxy;

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1)
			throws ServletException, IOException {
		proxy.service(arg0, arg1);
	}

	@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);
	}

}
2、编写启动Servlet:
package cn.edu.swu.oa.common.util;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import cn.edu.swu.oa.agency.model.Department;
import cn.edu.swu.oa.agency.model.Group;
import cn.edu.swu.oa.agency.service.DepService;
import cn.edu.swu.oa.agency.service.GroService;
import cn.edu.swu.oa.common.model.SysCode;
import cn.edu.swu.oa.safe.model.User;
import cn.edu.swu.oa.safe.service.UserService;

/**
 * 
 * 工程:WebOA
 * 类型解释:Spring启动完成后执行初始化操作
 * 类型表述:预读某些实体的Key-Value,放入map,方便以后使用
 * @author ChenGuanwei
 * @version 创建时间:2010-3-25 下午10:55:44
 *
 */
@Component("initialServlet")
public class InitialServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Resource
	private UserService userService;

	@Resource
	private DepService depService;

	@Resource
	private GroService groService;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitialServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		//初始化eserMap
		List<User> users = userService.getUsers();
		for(int i = 0; i < users.size(); i++) {
			User user = users.get(i);
			Integer userId = user.getUserId();
			String userName = user.getUserName();
			SysCode.userMap.put(userId, userName);
		}
		//初始化depMap
		List<Department> deps = depService.getAllDeps();
		for(int i = 0; i < deps.size(); i++) {
			Department dep = deps.get(i);
			Integer depId = dep.getDepId();
			String depName = dep.getDepName();
			SysCode.depMap.put(depId, depName);
		}
		//初始化groMap
		List<Group> gros = groService.getAllGroups();
		for(int i = 0; i < gros.size(); i++) {
			Group gro = gros.get(i);
			Integer groId = gro.getGroId();
			String groName = gro.getGroName();
			SysCode.groMap.put(groId, groName);
		}
	}

}

在web.xml文件中配置InitialServlet :
<servlet>
    <description></description>
    <display-name>InitialServlet</display-name>
    <servlet-name>initialServlet</servlet-name>
    <servlet-class>cn.edu.swu.oa.common.util.
DelegatingServletProxy
</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>initialServlet</servlet-name>
    <url-pattern>/InitialServlet</url-pattern>
  </servlet-mapping>
完成这些操作后,就可以在Spring容器启动后执行自定义的Servlet,并且在自定义Servlet中可以使用Spring Annotation的自动注入功能。 备注:需要在xml里面配置compont扫描:示例
<context:component-scan base-package="com.et59.cus"/>
正文到此结束
Loading...