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

Spring读取配置文件,获取bean的几种方式的更多相关文章

  1. Spring获取ApplicationContext方式,和读取配置文件获取bean的几种方式

    转自:http://chinazhaokeke.blog.163.com/blog/static/109409055201092811354236  Spring获取ApplicationContex ...

  2. Spring获取bean的几种方式

    工作中需要对一个原本加载属性文件的工具类修改成对数据库的操作当然,ado层已经写好,但是需要从Spring中获取bean,然而,工具类并没有交给Spring来管理,所以需要通过方法获取所需要的bean ...

  3. Spring学习之实例化bean的三种方式

    实例化bean的三种方式 构造器实例化bean Person.java public class Person { private String name; private Integer age; ...

  4. Spring在代码中获取bean的几种方式

    方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...

  5. Spring在代码中获取bean的几种方式(转:http://www.dexcoder.com/selfly/article/326)

    方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...

  6. Spring在代码中获取bean的几种方式(转)

    获取spring中bean的方式总结: 方法一:在初始化时保存ApplicationContext对象 ApplicationContext ac = new FileSystemXmlApplica ...

  7. Spring获取bean的一种方式

    随便一百度,网上一大把,并且还不止一种.所以这里就只记录目前用的一种好了. 实现ApplicationContextAware接口 即可: import org.springframework.bea ...

  8. 001-Spring在代码中获取bean的几种方式

    一.概述 方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类Applicati ...

  9. java中读取配置文件ResourceBundle和Properties两种方式比较

    今天在开发的时候,需要把一些信息放到配置文件中,方便后续的修改,注意到用的是ResourceBundle读取配置文件的方式,记得之前也见过使用Properties的方式,就比较好奇这两种方式的区别,网 ...

随机推荐

  1. Java环境搭建指南

    1.1 配置Java环境 1.  下载并安装Jdk1.7或Jdk1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.ht ...

  2. JavaScript高级程序设计-读书笔记(4)

    第11章 DOM扩展 1.选择符API Selector API Level 1 的核心是两个方法:querySelector()和querySelectorAll().在兼容的浏览器中,可以通过Do ...

  3. Lua学习笔记2. lua变量和 循环

    1. lua中变量的作用域有三种:全局,局部,表中的域 需要注意的是默认的变量都是全局变量,必须声明为local的变量才是局部变量,即使是在函数里面没有使用local修饰的变量依然是全局变量!!!! ...

  4. 十五 web爬虫讲解2—urllib库中使用xpath表达式—BeautifulSoup基础

    在urllib中,我们一样可以使用xpath表达式进行信息提取,此时,你需要首先安装lxml模块,然后将网页数据通过lxml下的etree转化为treedata的形式 urllib库中使用xpath表 ...

  5. echarts 折线图配置

    html内容: <div id="user_num_chart" style="width: 582px;height:250px;"></d ...

  6. 验证email是否合法

    https://buluo.qq.com/p/detail.html?bid=339910&pid=6675390-1514450689&from=grp_sub_obj 场景1:验证 ...

  7. 016——数组(十六)usort uasort uksort

    <?php /*数组 usort uasort uksort */ //usort()通过自定义函数对数组进行排序,原数组索引不保留 /*$arr = array(5, 3, 7, 6, 4, ...

  8. C#中Abstract和Virtua笔记,知识

    在C#的学习中,容易混淆virtual方法和abstract方法的使用,现在来讨论一下二者的区别.二者都牵涉到在派生类中与override的配合使用. 一.Virtual方法(虚方法) virtual ...

  9. ftp的本地用户搭建

    前期的准备跟虚拟用户一样,就是配置文件不一样 修改配置文件 就是共享的都是自己的账号的家目录,然后启动服务就可以了 本地登陆的都是自己的账号密码 ftp本地的黑名单,

  10. bzoj3600

    题解: 好像是什么替罪羊树 然后看了几个题解 然后就抄了一边 代码: #include<bits/stdc++.h> using namespace std; ; int n,m,rt,R ...