直接最簡單有效的方法,重寫Servlet的Init()方法。代碼以下:java
1)、 首先新建一個重寫Servlet的Init()方法的類繼承HttpServletweb
import javax.servlet.ServletException;spring
import javax.servlet.http.HttpServlet;this
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;.net
import org.springframework.web.context.WebApplicationContext;繼承
import org.springframework.web.context.support.WebApplicationContextUtils;接口
/**get
* 描述:Servlet重寫Init()方法servlet
* @author WangKunit
*/
public class ServletProxy extends HttpServlet {
/**
*/
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
super.init();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
AutowireCapableBeanFactory factory = wac.getAutowireCapableBeanFactory();
factory.autowireBean(this);
}
}
2)、新建本身須要的Servlet再繼承重寫Servlet的類 (ServletProxy)
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
public class ***Servlet extends ServletProxy {
@Autowired
private ***Service ***Service;
private static final long serialVersionUID = 2827297299439162553L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
***Service.本身的接口方法。
你本身的東西本身寫了。 } }