1. 程式人生 > >【Spring註解驅動開發】面試官:如何將Service注入到Servlet中?朋友又栽了!!

【Spring註解驅動開發】面試官:如何將Service注入到Servlet中?朋友又栽了!!

## 寫在前面 > 最近,一位讀者出去面試前準備了很久,信心滿滿的去面試。沒想到面試官的一個問題把他難住了。面試官的問題是這樣的:如何使用Spring將Service注入到Servlet中呢?這位讀者平時也是很努力的,看什麼原始碼啊、多執行緒啊、高併發啊、設計模式啊等等。沒想到卻在一個很簡單的問題上栽了跟頭,這就說明學習知識要系統化,要有條理,切忌東學一點,西記一點,否則,到頭來,啥也學不到。 > > 專案工程原始碼已經提交到GitHub:[https://github.com/sunshinelyz/spring-annotation](https://github.com/sunshinelyz/spring-annotation) ## 如何實現將Service注入到Servlet中?? 這裡,我們列舉兩種解決方法(推薦使用第二種) ### 方法一: 直接重寫Servlet的Init()方法,程式碼如下: ```java public void init(ServletConfig servletConfig) throws ServletException { ServletContext servletContext = servletConfig.getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils .getWebApplicationContext(servletContext); AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext .getAutowireCapableBeanFactory(); autowireCapableBeanFactory.configureBean(this, BEAN_NAME); } ``` 這裡的BEAN_NAME即為我們需要注入到Spring容器中的服務,但這並不是一個好的方法,因為我們需要在每一個Servlet中都進行這樣的操作。 ### 方法二: 我們可以寫一個類似於“org.springframework.web.struts.DelegatingRequestProcessor”的委託的Bean,然後通過配置的方法把我們的服務注入到servlet中,具體方法如下, **Step 1:編寫委託類DelegatingServletProxy** ```java package com.telek.pba.base.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; /** * 以下是類似org.springframework.web.struts.DelegatingRequestProcessor的一個委託 * 用於通過配置的方法,在Servlet中注入Service * @author binghe * */ public class DelegatingServletProxy extends GenericServlet{ private static final long serialVersionUID = 1L; private String targetBean; private Servlet proxy; @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException{ proxy.service(req, res); } /** * 初始化 */ public void init() throws ServletException { this.targetBean = getServletName(); getServletBean(); proxy.init(getServletConfig()); } /** * 獲取Bean */ private void getServletBean() { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); this.proxy = (Servlet) wac.getBean(targetBean); } } ``` **Step 2:修改Web.xml配置** 在純Servlet模式下,我們的配置方式如下(以下由於程式碼高亮外掛的問題,請將程式碼中的#替換成尖括號)