有时在Spring(3.2.5)项目中,如果使用到Servlet,可能希望Servlet实例作为bean受Spring容器管理,这样也能自动注入其他需要的bean,查了下,发现只针对过滤器提供了代理类org.springframework.web.filter.DelegatingFilterProxy,并没有提供针对Servlet的代理类,于是模仿着写了下面的代理类:
  
package org.springframework.web.servlet;
 
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
 
 
/**
 *  Servlet代理类,将Servlet托管于Spring容器,以便直接在Servlet内部自动注入其他bean<br>
 *  参考 {@code org.springframework.web.filter.DelegatingFilterProxy}<br>
 */
@SuppressWarnings("serial")
public class DelegatingServletProxy extends HttpServletBean {
 
 private String contextAttribute;
 private WebApplicationContext webApplicationContext;
 private String targetBeanName;
 private boolean targetServletLifecycle = true;
 private volatile Servlet delegate;
 private final Object delegateMonitor = new Object();
 
 public DelegatingServletProxy() {
 }
 
 public DelegatingServletProxy(Servlet delegate) {
  Assert.notNull(delegate, "delegate Servlet object must not be null");
  this.delegate = delegate;
 }
 
 public DelegatingServletProxy(String targetBeanName) {
  this(targetBeanName, null);
 }
 
 public DelegatingServletProxy(String targetBeanName, WebApplicationContext wac) {
  Assert.hasText(targetBeanName, "target Servlet bean name must not be null or empty");
  this.setTargetBeanName(targetBeanName);
  this.webApplicationContext = wac;
  if (wac != null) {
   this.setEnvironment(wac.getEnvironment());
  }
 }
 
 public void setContextAttribute(String contextAttribute) {
  this.contextAttribute = contextAttribute;
 }
 
 public String getContextAttribute() {
  return this.contextAttribute;
 }
 
 public void setTargetBeanName(String targetBeanName) {
  this.targetBeanName = targetBeanName;
 }
 
 protected String getTargetBeanName() {
  return this.targetBeanName;
 }
 
 public void setTargetServletLifecycle(boolean targetServletLifecycle) {
  this.targetServletLifecycle = targetServletLifecycle;
 }
 
 protected boolean isTargetServletLifecycle() {
  return this.targetServletLifecycle;
 }
 
 @Override
 protected void initServletBean() throws ServletException {
  synchronized (this.delegateMonitor) {
   if (this.delegate == null) {
    if (this.targetBeanName == null) {
     this.targetBeanName = this.getServletName();
    }
    WebApplicationContext wac = this.findWebApplicationContext();
    if (wac != null) {
     this.delegate = this.initDelegate(wac);
    }
   }
  }
 }
 
 @Override
 public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
  Servlet delegateToUse = this.delegate;
  if (delegateToUse == null) {
   synchronized (this.delegateMonitor) {
    if (this.delegate == null) {
     WebApplicationContext wac = this.findWebApplicationContext();
     if (wac == null) {
      throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
     }
     this.delegate = this.initDelegate(wac);
    }
    delegateToUse = this.delegate;
   }
  }
  this.invokeDelegate(delegateToUse, req, resp);
 }
 
 @Override
 public void destroy() {
  Servlet delegateToUse = this.delegate;
  if (delegateToUse != null) {
   this.destroyDelegate(delegateToUse);
  }
 }
 
 protected WebApplicationContext findWebApplicationContext() {
  if (this.webApplicationContext != null) {
   if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
    if (!((ConfigurableApplicationContext) this.webApplicationContext).isActive()) {
     ((ConfigurableApplicationContext) this.webApplicationContext).refresh();
    }
   }
   return this.webApplicationContext;
  }
  String attrName = this.getContextAttribute();
  if (attrName != null) {
   return WebApplicationContextUtils.getWebApplicationContext(super.getServletContext(), attrName);
  }
  else {
   return WebApplicationContextUtils.getWebApplicationContext(super.getServletContext());
  }
 }
 
 protected Servlet initDelegate(WebApplicationContext wac) throws ServletException {
  Servlet delegate = wac.getBean(this.getTargetBeanName(), Servlet.class);
  if (this.isTargetServletLifecycle()) {
   delegate.init(super.getServletConfig());
  }
  return delegate;
 }
 
 protected void invokeDelegate(Servlet delegate, ServletRequest req, ServletResponse resp) throws ServletException, IOException {
  delegate.service(req, resp);
 }
 
 protected void destroyDelegate(Servlet delegate) {
  if (this.isTargetServletLifecycle()) {
   delegate.destroy();
  }
 }
 
}
 
//======================================================//
用法:
1、比如存在test.TestServlet,配置到spring对应xml中:
 <bean id="testServlet" class="test.TestServlet" />
 
2、在web.xml配置如下:
<servlet>
  <servlet-name>testServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DelegatingServletProxy</servlet-class>
  <init-param>
   <param-name>targetBeanName</param-name>
   <param-value>testServlet</param-value>
  </init-param>
  <load-on-startup>10</load-on-startup>
 </servlet>
 
然后在TestServlet中可自动注入需要的bean。

整合Servlet到Spring容器的更多相关文章

  1. spring boot整合servlet、filter、Listener等组件方式

    创建一个maven项目,然后此项目继承一个父项目:org.springframework.boot 1.创建一个maven项目: 2.点击next后配置父项目及版本号 3.点击finish后就可查看p ...

  2. spring boot 2.x 系列 —— spring boot 整合 servlet 3.0

    文章目录 一.说明 1.1 项目结构说明 1.2 项目依赖 二.采用spring 注册方式整合 servlet 2.1 新建过滤器.监听器和servlet 2.2 注册过滤器.监听器和servlet ...

  3. spring 整合 servlet

    目的:记录spring整合 servlet过程demo.(企业实际开发中可能很少用到),融会贯通. 前言:在学习spring 过程(核心 ioc,aop,插一句 学了spring 才对这个有深刻概念, ...

  4. Servlet自动注入Spring容器中的Bean解决方法

    很多情况在进行Web开发的时候需要自己手写Servlet来完成某些功能,而servlet有需要注入Spring容器中的某些bean,这是每次都要手动获取比较麻烦,这里有一个解决方案,只需要写一个ser ...

  5. 如何在servlet的监听器中使用spring容器的bean

    另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对 ...

  6. Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)

    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...

  7. servlet容器,web容器,spring容器,springmvc容器的区别(转)

    web容器中有servlet容器,spring项目部署后存在spring容器和springmvc容器.其中spring控制service层和dao层的bean对象.springmvc容器控制contr ...

  8. Web容器、Servlet容器、Spring容器、SpringMVC容器之间的关系

    以下内容为个人理解,如有误还请留言指出,不胜感激! Web容器 web容器(web服务器)主要有:Apache.IIS.Tomcat.Jetty.JBoss.webLogic等,而Tomcat.Jet ...

  9. Spring Boot整合Servlet,Filter,Listener,访问静态资源

    目录 Spring Boot整合Servlet(两种方式) 第一种方式(通过注解扫描方式完成Servlet组件的注册): 第二种方式(通过方法完成Servlet组件的注册) Springboot整合F ...

随机推荐

  1. struts2 异常处理3板斧

    板斧1:找不到action的错误 在struts.xml中参考如下配置 <struts> ... <package name="default" namespac ...

  2. [MetaHook] GameUI hook

    Hook GameUI function. #include <metahook.h> #include <IGameUI.h> IGameUI *g_pGameUI = ; ...

  3. 用Map-Reduce的思维处理数据

    在很多人的眼里,Map-Reduce等于Hadoop,没有Hadoop谈Map-Reduce犹如自上谈兵,实则不然,Map-Reduce是一种计算模型,只是非常适合在并行的环境下运行,Hadoop是M ...

  4. EMV内核使用中的常见问题

    EMV内核在使用上会由于调用不当引起的许多问题,本文旨在基于内核LOG(也就是与IC卡交互的指令LOG)的基础上,对一些常见问题作初步的分析与解答,方便不熟悉EMV规范的同学参考. 本文的前提是你已经 ...

  5. QT 智能提示设置

    qt5.0的智能提示设置 qt默认的是Ctrl+空格 但这个是切换输入法,用着也不习惯 修改的地方是 工具->选项->环境 键盘选项把CompleteThis修改成自己习惯的快捷键

  6. 关于mvc5+EF里面的db.Entry(model).State = EntityState.Modified报错问题

    最近在使用mvc5+EF的的时候用到了这句话 db.Entry(model).State = EntityState.Modified 看上去很简单的修改数据,但是一直报错,说是key已经存在,不能修 ...

  7. ASP.NET的编译原理

    http://www.cnblogs.com/mdy2001212/archive/2008/01/31/1060345.html

  8. Node进阶:核心模块http简介

    本文摘录自<Nodejs学习笔记>,更多章节及更新,请访问 github主页地址.欢迎加群交流,群号 197339705. http模块概览 大多数nodejs开发者都是冲着开发web s ...

  9. 利用manifest文件对程序目录下的dll进行分类

    1 背景 对于大部分的券商和机构投资者,只能通过有交易所交易系统接入资质的券商提供的柜台系统来进行现货交易.相对于期货市场,现货市场的柜台系统千差万别,接入协议有明文字符串.二进制数据和FIX协议等, ...

  10. ModernUI教程:目录 (完结)

    入门 My first Modern UI app (manually)                         第一个ModernUI应用(手动编写)(已完成) My first Moder ...