Spring读取配置文件,获取bean的几种方式

BeanFactory有很多实现类,通常使用 org.springframework.beans.factory.xml.XmlBeanFactory类。但对于大部分J2EE应用而言,推荐使 用ApplicationContext. ApplicationContext是

BeanFactory的子接口,其常用实现类是 org.springframework.context.support.FileSystemXmlApplicationContext和 org.springframework.context.support.ClassXmlAplicationContext。
Springr的配置信息通常采用XML配置文件来设置,因此,创建BeanFactory实例时,应该提供XML配置文件作为参数。

方法一:使用FileSystemXmlApplicationContext
代码:

ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:beans.xml");
ac.getBean("beanId"); 

beans.xml所在位置:如图

 1.默认为项目工作路径 即项目的根目录
ApplicationContext appCt2 = new FileSystemXmlApplicationContext("src/main/resources/beans.xml");

2.前缀classpath:表示的是项目的classpath下相对路径
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:beans.xml");

3.使用前缀file 表示的是文件的绝对路径
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("file:E:/workspace/java-maven/src/main/resources/beans.xml");
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("E:/workspace/java-maven/src/main/resources/beans.xml");

4.可以同时加载多个文件
  String[] xmlCfg = new String[] { "src/main/resources/base.spring.xml","classpath:app.spring.xml"};
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext(xmlCfg);

5.使用通配符加载所有符合要求的文件
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:*.spring.xml");


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

方法二:使用ClassPathXmlApplicationContext

     可以从classpath中读取XML文件

(1)没有前缀:默认为项目的classpath下相对路径

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

(2).前缀classpath:表示的是项目的classpath下相对路径
   ApplicationContext appCt = new ClassPathXmlApplicationContext("classpath:app.spring.xml");

(3)使用前缀file 表示的是文件的绝对路径

ApplicationContext appCt = new ClassPathXmlApplicationContext("file:E:/workspace/java-maven/src/main/resources/beans.xml"); 

 (4)可以同时加载多个文件

String[] xmlCfg = new String[] { "classpath:beans.xml","spring-context.xml"};
ApplicationContext appCt = new ClassPathXmlApplicationContext(xmlCfg);

(5).使用通配符加载所有符合要求的文件

  ApplicationContext appCt = new ClassPathXmlApplicationContext("*.spring.xml");


方法三:通过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"));

2.  

 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="资源文件不存在";
        }

2. 利用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直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常

原文地址:https://www.cnblogs.com/jsStudyjj/p/4917184.html