`

Web开发中获取Spring的ApplicationContext的几种方式

 
阅读更多

在 WEB 开发中,获取到由 Spring 进行管理的某些 Bean,通常采用下面方式来获取

1、通过set注入方式

private ProjectStageHandler projectStageHandler;

public void setProjectStageHandler(ProjectStageHandler projectStageHandler) {
  this.projectStageHandler = projectStageHandler;
 }

2、通过注解方式

@Resource

private ProjectStageHandler projectStageHandler;

今天遇到 需要显示的获得 ApplicationContext 来得到由 Spring 进行管理的某些 Bean,在这里和大家分享一下,WEB 开发中,怎么获取 ApplicationContext ( 如有不正确之处还请指点)

查找工程有没有这种实现,功夫没有白费还真找到了大致实现方式如下:

3、首先web.xml配置

<listener>
    	<listener-class>org.common.xxxServletContextListener</listener-class>
    </listener>

接着xxxServletContextListener.java

public class xxxServletContextListener implements ServletContextListener {    
    //ServletContext创建时调用该方法 
	public void contextInitialized(ServletContextEvent arg0){
		ServletContext context= arg0.getServletContext();   
		System.out.println("监听器启动。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
		ApplicationCtx.init(context);
	}  
    //ServletContext销毁时调用该方法    
    public void contextDestroyed(ServletContextEvent sce){    
         System.out.println("ServletContext销毁");    
     }
	  
}   

ApplicationCtx .java

public class ApplicationCtx {

	public static ApplicationContext ctx;
	
	public static ApplicationContext getCtx(){
		return ctx;
	}
	public static void init(ServletContext sc){
		if(ctx==null){
			ctx =  WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		}
	}
}

通过 ApplicationCtx.getCtx().getBean("xxx"); 就可以获到想要的bean啦

想想这种方式有点太罗嗦和麻烦,还有没有更简单的方式哪?有当然有。

4、首先要在spring.xml中加上

<bean id="applicationContext" class="org.wy.util.AppliactionContextHelper"/>

当对AppliactionContextHelper实例时就自动设置applicationContext,以便后来可直接用applicationContext

 
public class AppliactionContextHelper implements ApplicationContextAware {
  private static ApplicationContext applicationContext;     //Spring应用上下文环境
 
  /**
  * 实现ApplicationContextAware接口的回调方法,设置上下文环境  
  * @param applicationContext
  * @throws BeansException
  */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    AppliactionContextHelper.applicationContext = applicationContext;
  }
 
  /**
  * @return ApplicationContext
  */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
 
  /**
  * 获取对象  
  * @param name
  * @return Object 一个以所给名字注册的bean的实例
  * @throws BeansException
  */
  public static Object getBean(String name) throws BeansException {
    return applicationContext.getBean(name);
  }
 
  /**
  * 获取类型为requiredType的对象
  * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
  * @param name       bean注册名
  * @param requiredType 返回对象类型
  * @return Object 返回requiredType类型对象
  * @throws BeansException
  */
  public static Object getBean(String name, Class requiredType) throws BeansException {
    return applicationContext.getBean(name, requiredType);
  }
 
  /**
  * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
  * @param name
  * @return boolean
  */
  public static boolean containsBean(String name) {
    return applicationContext.containsBean(name);
  }
 
  /**
  * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
  * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)  
  * @param name
  * @return boolean
  * @throws NoSuchBeanDefinitionException
  */
  public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.isSingleton(name);
  }
 
  /**
  * @param name
  * @return Class 注册对象的类型
  * @throws NoSuchBeanDefinitionException
  */
  public static Class getType(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getType(name);
  }
 
  /**
  * 如果给定的bean名字在bean定义中有别名,则返回这些别名  
  * @param name
  * @return
  * @throws NoSuchBeanDefinitionException
  */
  public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getAliases(name);
  }
}

通过AppliactionContextHelper.getBean("xxx");就可以获到想要的bean啦

5、

利用ClassPathXmlApplicationContext

可以从classpath中读取XML文件

(1) ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)context.getBean("userDao");

(2) ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new String[]{"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"});

BeanFactory factory = resource;

factory.getBean("xxx");

这种方式只适合非web中的应用程序中。

--------------------------------------------------------------------------------------------------------------------------------

转载:

获得spring里注册Bean的四种方法,特别是第三种方法,简单:


一:方法一(多在struts框架中)继承BaseDispatchAction

Java代码 复制代码 收藏代码
 
import com.mas.wawacommunity.wap.service.UserManager;
 
public class BaseDispatchAction extends DispatchAction {
    /**
    * web应用上下文环境变量
    */
    protected WebApplicationContext ctx;
 
    protected UserManager userMgr;
 
    /**
    * 获得注册Bean    
    * @param beanName String 注册Bean的名称
    * @return
    */
    protected final Object getBean(String beanName) {
        return ctx.getBean(beanName);
    }
 
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
              javax.servlet.http.HttpServletRequest request,
              javax.servlet.http.HttpServletResponse response) {    
        return mapping.findForward("index");
    }
 
    public void setServlet(ActionServlet servlet) {
        this.servlet = servlet;
        this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
        this.userMgr = (UserManager) getBean("userManager");
    }        
}


二:方法二实现BeanFactoryAware
一定要在spring.xml中加上:
Xml代码 复制代码 收藏代码

<bean id="serviceLocator" class="com.am.oa.commons.service.ServiceLocator" singleton="true" />

当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用 beanFactory
Java代码 复制代码 收藏代码
public class UserAction extends BaseAction implements Action,ModelDriven{
   
    private Users user = new Users();
    protected ServiceLocator service = ServiceLocator.getInstance();
    UserService userService = (UserService)service.getService("userService");
 
    public String execute() throws Exception {        
        return SUCCESS;
    }
 
  public Object getModel() {
        return user;
    }    
   
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();        
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);    
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}



三:方法三实现ApplicationContextAware,一定要在spring.xml中加上:
Xml代码 复制代码 收藏代码
<bean id="SpringContextUtil " class="com.am.oa.commons.service.SpringContextUtil " singleton="true" />

当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
Java代码 复制代码 收藏代码
 
public class SpringContextUtil implements ApplicationContextAware {
  private static ApplicationContext applicationContext;     //Spring应用上下文环境
 
  /**
  * 实现ApplicationContextAware接口的回调方法,设置上下文环境  
  * @param applicationContext
  * @throws BeansException
  */
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
  }
 
  /**
  * @return ApplicationContext
  */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
 
  /**
  * 获取对象  
  * @param name
  * @return Object 一个以所给名字注册的bean的实例
  * @throws BeansException
  */
  public static Object getBean(String name) throws BeansException {
    return applicationContext.getBean(name);
  }
 
  /**
  * 获取类型为requiredType的对象
  * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
  * @param name       bean注册名
  * @param requiredType 返回对象类型
  * @return Object 返回requiredType类型对象
  * @throws BeansException
  */
  public static Object getBean(String name, Class requiredType) throws BeansException {
    return applicationContext.getBean(name, requiredType);
  }
 
  /**
  * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
  * @param name
  * @return boolean
  */
  public static boolean containsBean(String name) {
    return applicationContext.containsBean(name);
  }
 
  /**
  * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
  * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)  
  * @param name
  * @return boolean
  * @throws NoSuchBeanDefinitionException
  */
  public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.isSingleton(name);
  }
 
  /**
  * @param name
  * @return Class 注册对象的类型
  * @throws NoSuchBeanDefinitionException
  */
  public static Class getType(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getType(name);
  }
 
  /**
  * 如果给定的bean名字在bean定义中有别名,则返回这些别名  
  * @param name
  * @return
  * @throws NoSuchBeanDefinitionException
  */
  public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    return applicationContext.getAliases(name);
  }
}


action调用:
Java代码 复制代码 收藏代码
package com.anymusic.oa.webwork;
 
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;
 
public class UserAction extends BaseAction implements Action,ModelDriven{
   
    private Users user = new Users();
 //不用再加载springContext.xml 文件,因为在web.xml中配置了,在程序中启动是就有了.   
    UserService userService = (UserService) SpringContextUtil.getBean("userService");
   
    public String execute() throws Exception {        
        return SUCCESS;
    }
 
  public Object getModel() {
        return user;
    }    
   
    public String getAllUser(){
        HttpServletRequest request = ServletActionContext.getRequest();        
        List ls=userService.LoadAllObject( Users.class );
        request.setAttribute("user",ls);    
        this.setUrl("/yonghu.jsp");
        return SUCCESS;
    }
}

四.通过servlet 或listener设置spring的 ApplicationContext,以便后来引用.
注意分别extends ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext 来getBean.
覆盖原来在web.xml中配置的listener或servlet.
public class SpringContext  {   
  private static ApplicationContext applicationContext;     //Spring应用上下文环境   
    
  
  */   
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {   
    SpringContextUtil.applicationContext = applicationContext;   
  }   
    
  /**  
  * @return ApplicationContext  
  */  
  public static ApplicationContext getApplicationContext() {   
    return applicationContext;   
  }   
    
  
  */   
  public static Object getBean(String name) throws BeansException {   
    return applicationContext.getBean(name);   
  }   
  
}   
  
public class SpringContextLoaderListener extends ContextLoaderListener{  //   
 public void contextInitialized(ServletContextEvent event) {     
  super.contextInitialized(event);   
  SpringContext.setApplicationContext(   
    WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())   
    );   
 }   
}   
  
public class SpringContextLoaderServlet extends ContextLoaderServlet {   
 private ContextLoader contextLoader;   
    public void init() throws ServletException {   
        this.contextLoader = createContextLoader();   
        SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));   
    }   
}  
分享到:
评论

相关推荐

    Spring开发指南

    依赖注入的几种实现类型 Type1 接口注入 Type2 设值注入 Type3 构造子注入 几种依赖注入模式的对比总结 Spring Bean封装机制 Bean Wrapper Bean Factory ApplicationContext Web Context Spring 高级...

    Spring面试题含答案.pdf

    25. 解释 Spring 支持的几种 bean 的作用域 26. Spring 框架中的单例 bean 是线程安全的吗? 27. 解释 Spring 框架中 bean 的生命周期 28. 哪些是重要的 bean 生命周期方法? 你能重载它们吗? 29. 什么是 Spring ...

    开源框架 Spring Gossip

    从代理机制初探 AOP 动态代理 &lt;br&gt;AOP 观念与术语 Spring AOP Advices Advices 包括了Aspect 的真正逻辑,由于缝合至Targets的时机不同,Spring 提供了几种不同的 Advices。 Before ...

    ssh(structs,spring,hibernate)框架中的上传下载

    WEB-INF下的applicationContext.xml为Spring的配置文件,struts-config.xml为Struts的配置文件,file-upload.jsp为文件上传页面,file-list.jsp为文件列表页面。  本文后面的章节将从数据持久层->业务层->Web层的...

    2011 经典 下载 spring中文教程(spring开发指南).pdf

    依赖注入的几种实现类型........................................................................................14 Type1 接口注入...........................................................................

    springmybatis

    1. 现阶段,你可以直接建立java 工程,但一般都是开发web项目,这个系列教程最后也是web的,所以一开始就建立web工程。 2. 将 mybatis-3.2.0-SNAPSHOT.jar,mysql-connector-java-5.1.22-bin.jar 拷贝到 web工程的...

    java面试宝典

    68、java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类? 17 69、文件读写的基本类 17 70、多线程有几种实现方法,都是什么?同步有几种实现方法,都是什么? 17 71、启动一个...

    千方百计笔试题大全

    68、java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类? 17 69、文件读写的基本类 17 70、多线程有几种实现方法,都是什么?同步有几种实现方法,都是什么? 17 71、启动一个...

    avaliacao-s2it

    3-在Web服务器上运行的组件只有几种类型: C 4-分析有关JEE和EJB的以下各项。 这 5-Spring Framework是一个完整的Java平台,为Java应用程序的开发提供基础结构支持。 关于Spring 3.0框架的功能,请检查正确的选项...

Global site tag (gtag.js) - Google Analytics