spring学习笔记(3)——配置文件applicationContext.xml的加载

转载:
http://blog.csdn.net/mezheng/article/details/7322981

1、把applicationContext.xml直接放在WEB-INF下,spring会采用默认的加载方式
2、采用在web.xml中配置ContextLoaderListenera或ContextLoaderServlet指定加载路径方式。
它们两个有着同样的功能,都实现在了org.springframework.web.context.ContextLoader类,都要定义contextConfigLocation参数。
区别在于listener不能在Servlet 2.2兼容的容器中使用。
自从Servelt 2.4规范,listener被要求在web应用启动后初始化。web.xml初始化的时候,listerner会检查contextConfigLocation参数。
如果不存在的话,它将默认使用/WEB-INF/applicationContext.xml。
如果它存在,它就会用预先定义的分隔符(逗号,分号和空格)分开分割字符串(),并将这些值作为应用上下文将要搜索的位置。

<context-param>   
    <param-name>contextConfigLocation</param-name>      
    <param-value>   
      /WEB-INF/daoContext.xml,/WEB-INF/config/appContext1.xml,/WEB-INF/config/appContext2.xml    
    </param-value>   
</context-param>      
<listener>   
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   
</listener>     
<!-- 另一种是使用ContextLoaderServlet    


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

 -->    

3 通过ClassPathXmlApplicationContext或XmlWebApplicationContext代码动态加载
一:XmlBeanFactory 引用

Resource resource = new ClassPathResource("appcontext.xml");   
BeanFactory factory = new XmlBeanFactory(resource);



ApplicationContext factory=new 
ClassPathXmlApplicationContext("classpath:appcontext.xml");

ApplicationContext factory=new 
ClassPathXmlApplicationContext("appcontext.xml"); // src目录下的 

  ApplicationContext factory=new 
ClassPathXmlApplicationContext("conf/appcontext.xml"); // src/conf 目录下的 

  ApplicationContext factory=new 
ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml"); 

三 : 用文件系统的路径

 ApplicationContext factory=new 
FileSystemXmlApplicationContext("src/appcontext.xml"); 
  //使用了 classpath: 前缀,作为标志, 这
样,FileSystemXmlApplicationContext 也能够读入classpath下的相对路径 

  ApplicationContext factory=new 
FileSystemXmlApplicationContext("classpath:appcontext.xml"); 

  ApplicationContext factory=new 
FileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml"); 

  ApplicationContext factory=new 
FileSystemXmlApplicationContext("G:/Test/src/appcontext.xml"); 
  四: XmlWebApplicationContext 是专为Web工程定制的。  

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

方法一:在初始化时保存ApplicationContext对象
代码:
ApplicationContext ac = new FileSystemXmlApplicationContext(“applicationContext.xml”);
ac.getBean(“beanId”);
说明:
这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

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

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对象,然后在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

方法三:继承自抽象类ApplicationObjectSupport
说明:
抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport
说明:
类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

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

以上方法适合不同的情况,请根据具体情况选用相应的方法。

这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运行环境,尽量通过DI的方式获取需要的服务提供者。

本人认为,方法五比较可行,可以设计一个工具类,专门来获取Spring中的类。减少对业务代码的侵入性。

读取xml文件

/**
* 利用XmlBeanFactory(Resource resource)
* 这里Resource必须是xml格式
* Resource包括:AbstractResource, ClassPathResource, FileSystemResource,
* InputStreamResource, ServletContextResource, UrlResource
*/

/*
* 利用 InputStreamResource(InputStream inputStream)
* 要将applicationContext.xml放在项目根目录下
*/
InputStream is = null;
try {
is = new FileInputStream(“applicationContext.xml”);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Resource resource = new InputStreamResource(is);
BeanFactory factory = new XmlBeanFactory(resource);
UserDao userDao = (UserDao)factory.getBean(“userDao”);

/*
* 利用 Properties
* 要将bean.properties放在类路径--源文件夹(src)目录下
*/

这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件

构造如下config.properties文件properties代码

userDao.class=com.spring.dao.UserDao

属性文件中的”userDao”名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource(“config.properties”));
BeanFactory factory = (BeanFactory)reg;
UserDao userDao = (UserDao)factory.getBean(“userDao”);
(二)利用java.util.Properties读取属性文件
1. String str=File.separator;
InputStream path=this.getServletContext().getResourceAsStream(str+”WEB-INF”+str+”classes”+str+”password.properties”);
//InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(“password.properties”);

/*File filepath=new File(this.getServletContext().getRealPath(str+"WEB-INF"+str+"classes")+str+"password.properties");

    InputStream path=new FileInputStream(filepath);*/
    Properties pros = new Properties();
    try {
        pros.load(path);
    } catch (IOException ex) {
        //System.out.println("file is not exist");
        errorMessage="资源文件不存在";
    }
    System.out.println("username:"+p.getProperty("username")+",password:"+p.getProperty("password"));
  1. import org.springframework.core.io.ClassPathResource;

    ClassPathResource cr = new ClassPathResource("password.properties");//会重新加载spring框架
    Properties pros = new Properties();
    try {
        pros.load(cr.getInputStream());
    } catch (IOException ex) {
        //System.out.println("file is not exist");
        errorMessage="资源文件不存在";
    }
    

1.利用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;

UserDao userDao = (UserDao) factory.getBean(“userDao”);

  1. 利用ClassPathResource

可以从classpath中读取XML文件

Resource cr = new ClassPathResource(“applicationContext.xml”);

BeanFactory bf=new XmlBeanFactory(cr);

UserDao userDao = (UserDao)bf.getBean(“userDao”);

加载一个xml文件org.springframework.beans.factory.config.PropertyPlaceholderConfigurer不起作用

3.利用XmlWebApplicationContext读取

从Web应用程序的文件架构中,指定相对位置来读取定义文件。

XmlWebApplicationContext 的建構子無法帶參數,參考API文件會發現,預設的location會指向/WEB-INF/applicationContext.xml檔案。使用其 public static屬性DEFAULT_CONFIG_LOCATION可取得此預設檔名。由於我使用MyEclipse,預設會多一個”/WebRoot”的 目錄在WEB-INF之前,因此若在web project裡有一些與web無關的程式要使用context時(例如處理一些MVC架構中的”M”的部份),就無法使用 XmlWebApplicationContext來讀取bean定義檔,因為default location會差一個”WebRoot”的目錄。
即 使在web.xml裡面,在DispatcherServlet定義中重新定義contextConfigLocation也一樣(此定義可以 override掉XmlWebApplicationContext中的DEFAULT_CONFIG_LOCATION值),因為與web無關的程式 並不會經過web.xml的定義檔設定。目前我還沒試成功過XmlWebApplicationContext取得bean定義檔,使用 ClassPathXmlApplicationContext反而會快一些。

XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(new String[] {“/WEB-INF/ applicationContext.xml”);
ctx.setServletContext(pageContext.getServletContext());
ctx.refresh();
UserDao userDao = (UserDao ) ctx.getBean(“userDao “);

4.利用FileSystemResource读取

Resource rs = new FileSystemResource(“D:/tomcat/webapps/test/WEB-INF/classes/ applicationContext.xml”);
BeanFactory factory = new XmlBeanFactory(rs);
UserDao userDao = (UserDao )factory.getBean(“userDao”);

值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常

5.利用FileSystemXmlApplicationContext读取

可以指定XML定义文件的相对路径或者绝对路径来读取定义文件。

方法一:

String[] path={“WebRoot/WEB-INF/applicationContext.xml”,”WebRoot/WEB-INF/applicationContext_task.xml”};
ApplicationContext context = new FileSystemXmlApplicationContext(path);

方法二:

String path=”WebRoot/WEB-INF/applicationContext*.xml”;
ApplicationContext context = new FileSystemXmlApplicationContext(path);

方法三:
ApplicationContext ctx = new FileSystemXmlApplicationContext(“classpath:地址”);
没有classpath的话就是从当前的工作目录