自定义(继承自 Javax.servlet.http.HttpServlet)的 Servlet 如何像 Struts1/2 中那样调用 Spring 容器的 service 呢?
如同 Struts1/2 的配置一样,Spring 在 web.xml 中的配置及其 application*.xml 配置不变:
web.xml 中:
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext*.xml</param-value>
- </context-param>
applicationContext-service.xml 中:
- <bean id="operationService"
- class="com.defonds.cds.service.operation.impl.OperationServiceImpl" scope="singleton">
- </bean>
如同一般的 Servlet 的配置一样,Servlet 在 web.xml 中的配置不变:
- <servlet>
- <servlet-name>downloadServlet</servlet-name>
- <servlet-class>com.defonds.cds.common.ArcSyncDownloadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>downloadServlet</servlet-name>
- <url-pattern>/file</url-pattern>
- </servlet-mapping>
如同一般的 Struts1/2 的 action 一样注入 service:
- private OperationService operationService = null;
- public OperationService getOperationService() {
- return operationService;
- }
- public void setOperationService(OperationService operationService) {
- this.operationService = operationService;
- }
在 Servlet 中如同一般的 Struts1/2 的 action 一样调用 service:
- FileInfo fileInfo = this.getOperationService().getFileByFidAndSecret(Long.parseLong(fileId), secret);
唯一需要修改的是 Servlet 的 init 方法:
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- ServletContext servletContext = this.getServletContext();
- WebApplicationContext wac = null;
- wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
- this.setOperationService((OperationService) wac.getBean("operationService"));//Spring 配置 中的 bean id
- }
这是一种办法。还有一种办法就是使用 Spring 将 Servlet 及其业务对象的依赖关系都管理起来,详细说明请参阅作者另一篇《使用 Spring 容器管理 Servlet》 见 http://www.linuxidc.com/Linux/2012-06/63008.htm。