【转载】Spring初始化ApplicationContext为null

原文地址1, 原文地址2

ApplicationContext是Spring的核心,Context我们通常解释为上下文环境,

在Web应用中,WebApplicationContext继承自ApplicationContext;WebApplicationContext的初始化方式和BeanFactory.ApplicationContext有所区别,因为WebApplicationContext需要ServletContext实例,也就是说它必须拥有Web容器的前提下才能完成启动的工作.有过Web开发经验的读者都知道可以在web.xml中配置自启动的Servlet或定义Web容器监听器(ServletContextListener),借助着两者中的任何一个,我们就可以启动Spring Web应用上下文的工作.

//Spring分别提供了用于启动WebApplicationContext的Servlet和Web容器监听器:

org.springframework.web.context.ContextLoaderServlet;

org.springframework.web.context.ContextLoaderListener.

1. ApplicationContextAware初始化

通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

使用方法如下:

1.实现ApplicationContextAware接口:

package com.bis.majian.practice.module.spring.util; 
import org.springframework.beans.BeansException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 
public class SpringContextHelper implements ApplicationContextAware { 
    private static ApplicationContext context = null; 
   
    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) 
            throws BeansException { 
        context = applicationContext; 
    } 
    public static Object getBean(String name){ 
        return context.getBean(name); 
    } 
       
} 

 2.在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">    
    <bean id="springContextHelper" class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean> 
    <context:component-scan base-package="com.bis.majian.practice.module.*" /> 
</beans> 

 3.在web项目中的web.xml中配置加载Spring容器的Listener:

<!-- 初始化Spring容器,让Spring容器随Web应用的启动而自动启动 --> 
    <listener> 
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 

4.在项目中即可通过这个SpringContextHelper调用getBean()方法得到Spring容器中的对象了。

2. ApplicationContext加载机制

1.加载器目前有两种选择:ContextLoaderListener和ContextLoaderServlet  
这两者在功能上完全等同,只是一个是基于Servlet2.3版本中新引入的Listener接口实现 而另一个基于Servlet接口实现。开发中可根据目标Web容器的实际情况进行选择。  配置非常简单,在web.xml中增加: 

<listener>   

<listener-class>   

          org.springframework.web.context.ContextLoaderListener   

</listener-class>   

</listener> 

或者

<servlet>
  <servlet-name>context</servlet-name>
  <servlet-class> org.springframework.web.context.ContextLoaderServlet</servlet-class>
   <load-on-startup>1</load-on-startup> 
</servlet>
 
 

通过以上配置,Web容器会自动加载/WEB-INF/applicationContext.xml初始化  

ApplicationContext实例,如果需要指定配置文件位置,可通过context-param加以指定:  

1

2

3

4

<context-param>

  <param-name>contextConfigLocation</param-name>  

  <param-value>classpath:applicationContext-bean.xml,classpath:spring-jamon.xml </param-value>

</context-param>

2.Spring提供ApplicationContext多种实现机制

简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用:  

1

2

3

4

5

6

7

8

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

RegisterDAO registerDAO = (RegisterDAO)ac.getBean("RegisterDAO");

 

如果是两个以上:

ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","dao.xml"});

 

或者用通配符:

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/*.xml");

 spring为ApplicationContext提供的3种实现分别为:

   ClassPathXmlApplicationContext,FileSystemXmlApplicationContext和XmlWebApplicationContext,其中XmlWebApplicationContext是专为Web工程定制的。

其中XmlWebApplicationContext是专为Web工程定制的。使用举例如下:    

(1)FileSystemXmlApplicationContext  

1

2

3

4

5

//加载单个配置文件

ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");       

String[] locations = {"bean1.xml""bean2.xml""bean3.xml"};     //加载多个配置文件

ApplicationContext ctx = new FileSystemXmlApplicationContext(locations );  //根据具体路径加载文件

ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");

注: 这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。 

(2)ClassPathXmlApplicationContext  

//加载单个配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//配置完成之后,即可通过ContextLoader工具类获取WebApplicationContext
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
LoginAction action=(LoginAction) wac.getBean("action"); 

(3) XmlWebApplicationContext

ServletContext servletContext = request.getSession().getServletContext();    
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

注:这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

3.如何获取ApplicationContext 
(1)继承自抽象类ApplicationObjectSupport 
  说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。 
  Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。 
(2)继承自抽象类WebApplicationObjectSupport 
  说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext (3)实现接口ApplicationContextAware 
  说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存 ApplicationContext 对象。 
  Spring初始化时,会通过该方法将ApplicationContext对象注入。 

  实现方法: 

public void setApplicationContext(ApplicationContext arg0) throws BeansException {   <br>    applicationContext = arg0; 
 }
获取bean:
ITaskService bean = (ITaskService)applicationContext.getBean(taskServiceName);

3. Spring获取WebApplicationContext为null解决方案

在web.xml中配置Spring,配置如下

1

2

3

4

5

6

7

8

9

<servlet>

<servlet-name>springServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>         

<param-name>contextConfigLocation</param-name>        

<param-value>/WEB-INF/applicationContext.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

  </servlet>

在Servlet中通过WebApplicationContextUtils.getWebApplicationContext(getServletContext())获取WebApplicationContext对象为null。这是由于除了配置DispatcherServlet,还需要配置ContextLoaderServlet,否则无法获取WebApplicationContext。配置方法如下,在web.xml中加入

1

2

3

4

5

<servlet>

        <servlet-name>context</servlet-name>

        <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>

        <load-on-startup>2</load-on-startup>

 </servlet>

案例2:

查找原因:xml文件的加载顺序不正确,ServiceBeanUtils还没有加载, ApplicationContext还没有初始化,而服务启动时就有个类通过调用ApplicationContext去取bean进行初始化了

解决方案:先加载ServiceBeanUtils类,去初始化ApplicationContext,然后再加载要调用ApplicationContext的类去初始化此类

4.ApplicationContext初始化方式

1. 在独立应用程序中,获取ApplicationContext:
          AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         context.close();//释放资源

2. 在web环境中,获取ApplicationContext:

      A)ServletContext servletContext = request.getSession().getServletContext();               

         ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); 

      B)String contextpath = "org.springframework.web.context.WebApplicationContext.ROOT";

         WebApplicationContext context = request.getSession().getServletContext().getAttribute(contextpath);   

5.常用获取spring 中bean的方式总结

方法一:在初始化时保存ApplicationContext对象

1

2

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");

ac.getBean("beanId");

说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

方法二:通过Spring提供的工具类获取ApplicationContext对象

1

2

3

4

5

import org.springframework.web.context.support.WebApplicationContextUtils;

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);

ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);

ac1.getBean("beanId");

ac2.getBean("beanId");

说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。

方法五:实现接口ApplicationContextAware
说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入。

使用的时候一定要注意实现了这些类或接口的普通java类一定要在Spring 的配置文件application-context.xml文件中进行配置。否则获取的ApplicationContext对象将为null。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值