转至:http://www.cnblogs.com/hafiz/p/5876243.html

方式1.通过context:property-placeholder加载配置文件jdbc.properties中的内容

<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

  上面的配置和下面配置等价,是对下面配置的简化

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

注意:这种方式下,如果你在spring-mvc.xml文件中有如下配置,则一定不能缺少下面的红色部分,关于它的作用以及原理,参见另一篇博客:context:component-scan标签的use-default-filters属性的作用以及原理分析

<!-- 配置组件扫描,springmvc容器中只扫描Controller注解 -->
<context:component-scan base-package="com.hafiz.www" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

  方式2.使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
<property name="locations">
<array>
<value>classpath:jdbc.properties</value>
</array>
</property>
</bean>

  方式3.使用util:properties标签进行暴露properties文件中的内容

<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>

注意:使用上面这行配置,需要在spring-dao.xml文件的头部声明以下红色的部分

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util.xsd">

  方式4.通过PropertyPlaceholderConfigurer在加载上下文的时候暴露properties到自定义子类的属性中以供程序中使用

<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

自定义类PropertyConfigurer的声明如下:

package com.hafiz.www.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.util.Properties; /**
* Desc:properties配置文件读取类
* Created by hafiz.zhang on 2016/9/14.
*/
public class PropertyConfigurer extends PropertyPlaceholderConfigurer { private Properties props; // 存取properties配置文件key-value结果 @Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException {
super.processProperties(beanFactoryToProcess, props);
this.props = props;
} public String getProperty(String key){
return this.props.getProperty(key);
} public String getProperty(String key, String defaultValue) {
return this.props.getProperty(key, defaultValue);
} public Object setProperty(String key, String value) {
return this.props.setProperty(key, value);
}
}

使用方式:在需要使用的类中使用@Autowired注解注入即可。

  方式5.自定义工具类PropertyUtil,并在该类的static静态代码块中读取properties文件内容保存在static属性中以供别的程序使用

package com.hafiz.www.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.*;
import java.util.Properties; /**
* Desc:properties文件获取工具类
* Created by hafiz.zhang on 2016/9/15.
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
static{
loadProps();
} synchronized static private void loadProps(){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
       <!--第一种,通过类加载器进行获取properties文件流-->
in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
       <!--第二种,通过类进行获取properties文件流-->
//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
props.load(in);
} catch (FileNotFoundException e) {
logger.error("jdbc.properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("jdbc.properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
} public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
} public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}

说明:这样的话,在该类被加载的时候,它就会自动读取指定位置的配置文件内容并保存到静态属性中,高效且方便,一次加载,可多次使用。

四、注意事项及建议

  以上五种方式,前三种方式比较死板,而且如果你想在带有@Controller注解的Bean中使用,你需要在SpringMVC的配置文件spring-mvc.xml中进行声明,如果你想在带有@Service、@Respository等非@Controller注解的Bean中进行使用,你需要在Spring的配置文件中spring.xml中进行声明。原因请参见另一篇博客:Spring和SpringMVC父子容器关系初窥

  我个人比较建议第四种和第五种配置方式,第五种为最好,它连工具类对象都不需要注入,直接调用静态方法进行获取,而且只一次加载,效率也高。而且前三种方式都不是很灵活,需要修改@Value的键值。

spring- properties 读取的五种方式的更多相关文章

  1. Spring事务配置的五种方式和spring里面事务的传播属性和事务隔离级别

    转: http://blog.csdn.net/it_man/article/details/5074371 Spring事务配置的五种方式 前段时间对Spring的事务配置做了比较深入的研究,在此之 ...

  2. Spring事务配置的五种方式(转发)

    Spring事务配置的五种方式(原博客地址是http://www.blogjava.net/robbie/archive/2009/04/05/264003.html)挺好的,收藏转发 前段时间对Sp ...

  3. 【开发笔记】- Java读取properties文件的五种方式

    原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...

  4. Spring事务配置的五种方式 巨全!不看后悔,一看必懂!

    前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...

  5. SSH深度历险(六) 深入浅出----- Spring事务配置的五种方式

    这对时间在学习SSH中Spring架构,Spring的事务配置做了详细总结,在此之间对Spring的事务配置只是停留在听说的阶段,总结一下,整体把控,通过这次的学习发觉Spring的事务配置只要把思路 ...

  6. Spring事务配置的五种方式(转载)

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分. DataSo ...

  7. Spring事务配置的五种方式

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分. DataSo ...

  8. Spring事务配置的五种方式 -- 越往后需要Spring版本越高

    第五种 基本零配置  个人感觉第四种也可以 Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式, ...

  9. Spring事务配置的五种方式(转)

    前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...

随机推荐

  1. 搭建PHP开发环境 apache+MySQL+PHP 安装phpMyAdmin模块

    该博文参考的资料来源于: http://wenku.baidu.com/view/0e4c569ddd3383c4bb4cd267.html http://www.cnblogs.com/pharen ...

  2. 记录IOS入门的过程

    先说点私话.再进入正题吧,顺便抒发下情绪.公司传统业务不景气,而互联网正如火如荼,无奈被逼上梁山.開始学起了IOS编程.后来想想闲着也是闲着就学习学习呗.无奈公司确实不希望投入了.不愿意提供苹果电脑. ...

  3. jquerymobile知识点三:弹出层popup

    弹出层popup很简单,主要就是弹出验证,登陆注册,提交信息之类的,下面是我写好的一个demo... <div data-role="popup" id="popu ...

  4. [Ionic] Ionic Quickstart for Windows

    1. Install ionic 2. Create ionic app ionic start myApp tabs //create a app cd myApp ionic serve // o ...

  5. [转]开源应用架构之asterisk

    作者:Russell Bryant 翻译:jiazhengfeng Asterisk[1]是一款GPLv2协议下的开源电话应用平台.简单来说,Asterisk是一个服务器应用,能够完成发起电话呼叫.接 ...

  6. Response乱码的解决方法

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletExcept ...

  7. MySQL查询

    DQL 操作 DQL 数据查询语言(重要)     数据库执行DQL语句不会对数据做出任何改变,而是让数据库发送结果集给客户端.  查询返回的结果是一张虚拟表.   查询关键字:SELECT     ...

  8. linux sed使用

    原文引用:http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856901.html [root@www ~]# sed [-nefr] [动作] ...

  9. System Operations on AWS - Lab 3W - Managing Storage (Windows)

    创建一个名叫Processor的EC2实例,登陆到CommandHost实例,通过AWS CLI对Processor实例的EBS卷做snapshot,设置周期性snapshot的计划任务, 登陆到Pr ...

  10. python 面向对象深入理解

    面向过程 函数式编程 面向对象编程:面向对象是由类和对象组成,只要用类和对象实现的,就是面向对象编程 def  Bar():     print  "This is  Bar " ...