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 com.gszh.wmcp.project.distribution.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gszh.wmcp.project.distribution.service.TestQueryService;

@Component("InitParamServlet")
public class InitParamServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Tomcat服务器启动时马上执行ServerMain.start(),启动相关线程
	 */
	@Autowired
	private TestQueryService queryAction;

	@Override  
    public void init() throws ServletException {  
        super.init();
        Start();
        
    } 
	//开始启动
	public void Start(){
		queryAction.query();
	}
	
}

3:配置Web。
  <servlet-mapping>
    <servlet-name>wap</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>InitParamServlet</servlet-name>
    <servlet-class>com.gszh.wmcp.project.distribution.unit.DelegatingServletProxy</servlet-class>
    <load-on-startup>5</load-on-startup>
  </servlet>
//<servlet-name>InitParamServlet</servlet-name>这一行的名字在执行的servlet的头部@Component("InitParamServlet")定义

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页