五种方式让你在java中读取properties文件内容不再是难题

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

方式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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://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结果
@Overrideprotected 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的键值。

五、测试验证是否可用

1.首先我们创建PropertiesService

package com.hafiz.www.service;/*** Desc:java程序获取properties文件内容的service* Created by hafiz.zhang on 2016/9/16.*/
public interface PropertiesService {/*** 第一种实现方式获取properties文件中指定key的value** @return*/String getProperyByFirstWay();/*** 第二种实现方式获取properties文件中指定key的value** @return*/String getProperyBySecondWay();/*** 第三种实现方式获取properties文件中指定key的value** @return*/String getProperyByThirdWay();/*** 第四种实现方式获取properties文件中指定key的value** @param key** @return*/String getProperyByFourthWay(String key);/*** 第四种实现方式获取properties文件中指定key的value** @param key** @param defaultValue** @return*/String getProperyByFourthWay(String key, String defaultValue);/*** 第五种实现方式获取properties文件中指定key的value** @param key** @return*/String getProperyByFifthWay(String key);/*** 第五种实现方式获取properties文件中指定key的value** @param key** @param defaultValue** @return*/String getProperyByFifthWay(String key, String defaultValue);
}

2.创建实现类PropertiesServiceImpl

package com.hafiz.www.service.impl;import com.hafiz.www.service.PropertiesService;
import com.hafiz.www.util.PropertyConfigurer;
import com.hafiz.www.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;/*** Desc:java程序获取properties文件内容的service的实现类* Created by hafiz.zhang on 2016/9/16.*/
@Service
public class PropertiesServiceImpl implements PropertiesService {@Value("${test}")private String testDataByFirst;@Value("#{prop.test}")private String testDataBySecond;@Value("#{propertiesReader[test]}")private String testDataByThird;@Autowiredprivate PropertyConfigurer pc;@Overridepublic String getProperyByFirstWay() {return testDataByFirst;}@Overridepublic String getProperyBySecondWay() {return testDataBySecond;}@Overridepublic String getProperyByThirdWay() {return testDataByThird;}@Overridepublic String getProperyByFourthWay(String key) {return pc.getProperty(key);}@Overridepublic String getProperyByFourthWay(String key, String defaultValue) {return pc.getProperty(key, defaultValue);}@Overridepublic String getProperyByFifthWay(String key) {return PropertyUtil.getPropery(key);}@Overridepublic String getProperyByFifthWay(String key, String defaultValue) {return PropertyUtil.getProperty(key, defaultValue);}
}

3.控制器类PropertyController

package com.hafiz.www.controller;import com.hafiz.www.service.PropertiesService;
import com.hafiz.www.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;/*** Desc:properties测试控制器* Created by hafiz.zhang on 2016/9/16.*/
@Controller
@RequestMapping("/prop")
public class PropertyController {@Autowiredprivate PropertiesService ps;@RequestMapping(value = "/way/first", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFirstWay(){return ps.getProperyByFirstWay();}@RequestMapping(value = "/way/second", method = RequestMethod.GET)@ResponseBodypublic String getPropertyBySecondWay(){return ps.getProperyBySecondWay();}@RequestMapping(value = "/way/third", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByThirdWay(){return ps.getProperyByThirdWay();}@RequestMapping(value = "/way/fourth/{key}", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFourthWay(@PathVariable("key") String key){return ps.getProperyByFourthWay(key, "defaultValue");}@RequestMapping(value = "/way/fifth/{key}", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFifthWay(@PathVariable("key") String key){return PropertyUtil.getProperty(key, "defaultValue");}
}

4.jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.196:3306/dev?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=200
jdbc.minIdle=5
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=select 1 from t_user
jdbc.testWhileIdle=true
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=true
jdbc.maxPoolPreparedStatementPerConnectionSize=20
jdbc.filters=stat
#test data
test=com.hafiz.www

5.项目结果图

  

6.项目GitHub地址

  https://github.com/hafizzhang/SSM/branches 页面下的propertiesConfigurer分支。

7.测试结果

  第一种方式

  

  第二种方式

  

  第三种方式

  

  第四种方式

  

  第五种方式

  

六、总结

  通过本次的梳理和测试,我们理解了Spring和SpringMVC的父子容器关系以及context:component-scan标签包扫描时最容易忽略的use-default-filters属性的作用以及原理。能够更好地定位和快速解决再遇到的问题。总之,棒棒哒~~~

转载于:https://my.oschina.net/zhangph89/blog/1579668

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/453667.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

hive metastore mysql_Hive MetaStore的结构

本篇主要是介绍Hive在MySQL中存储的源数据的表结构。Hive MetaStore 数据库表结构图test.pngTBLS记录数据表的信息字段解释TBL_ID在hive中创建表的时候自动生成的一个id&#xff0c;用来表示&#xff0c;主键CREATE_TIME创建的数据表的时间&#xff0c;使用的是时间戳DBS_ID这个…

修炼一名程序员的职业水准

程序就是一系列按步骤进行的操作序列&#xff0c;它有好多种级别&#xff0c;比如最低级的微程序、次低级的汇编程序、高级的各种编程语言程序、最高级的脚本语言程序&#xff0c;也许我列的不对&#xff0c;但没关系&#xff0c;我要说的是不管是那个级别的程序&#xff0c;其…

Rails开发细节《一》

常用命令 rails new new_app cd new_app rake db:create rails server rails generate controller Blog action1 action2 rails generate scaffold Product title:string description:textrails generate model Comment commenter:string body:text post:references rake db…

latex中怎样使公式居中_LaTeX_多行公式对齐居中的同时选择性的加编号

标签: 【转载请注明出处】http://www.cnblogs.com/mashiqi 2016/10/20 一年多没写博文了。今天写一个短的,记录一下使用LaTeX的一些经验。 如何居中多行的公式呢?我试过很多种方法后,觉得下面这个最好用: 1 \begin{flalign*}2 % In this way (this arrange of &), the…

[SDOI2008]Cave 洞穴勘测

题目描述 辉辉热衷于洞穴勘测。 某天&#xff0c;他按照地图来到了一片被标记为JSZX的洞穴群地区。经过初步勘测&#xff0c;辉辉发现这片区域由n个洞穴&#xff08;分别编号为1到n&#xff09;以及若干通道组成&#xff0c;并且每条通道连接了恰好两个洞穴。假如两个洞穴可以通…

Linux指令大全

名称&#xff1a;cat 使用权限&#xff1a;所有使用者 使用方式&#xff1a;cat [-AbeEnstTuv] [--help] [--version] fileName 说明&#xff1a;把档案串连接后传到基本输出&#xff08;萤幕或加 > fileName 到另一个档案&#xff09; 参数&#xff1a; -n 或 --number 由 …

mysql宏参数_C语言带参数的宏定义

C语言允许宏带有参数。在宏定义中的参数称为“形式参数”&#xff0c;在宏调用中的参数称为“实际参数”&#xff0c;这点和函数有些类似。对带参数的宏&#xff0c;在展开过程中不仅要进行字符串替换&#xff0c;还要用实参去替换形参。带参宏定义的一般形式为&#xff1a;#de…

自定义过滤器

首先在web.xml中对过滤器的监听 1 <!-- 自定义过滤器 -->2 <filter>3 <filter-name>AscFilter</filter-name>4 <filter-class>com.llh.filter.AscFilter</filter-class>5 </filter>6 <filter-mapping>7 …

[MS Sql Server术语解释]预读,逻辑读,物理读

在MSSQL中使用 SET STATISTICS IO ON 打开IO统计功能之后&#xff0c;每次执行完一个查询就会在下面的【消息】面板中显示本次查询IO的统计信息。 (0 行受影响) 表 demo。扫描计数 1&#xff0c;逻辑读取 622 次&#xff0c;物理读取 0 次&#xff0c;预读 0 次&#xff0c;lob…

mysql 数据库查询测试_MySQL查询测试经验

测试表geoinfo,整个表超过1100万行&#xff0c;表结构&#xff1a;CREATE TABLEgeoinfo (objectidint(11) NOT NULLAUTO_INCREMENT ,latitudedouble NOT NULL,longitudedouble NOT NULL,occupancybit(1) NOT NULL,timedatetime NOT NULL,cabidvarchar(16) NOT NULL,PRIMARY KEY…

更改阿里云域名解析台里某个域名绑定的IP之后不能解析到新IP

1.由于要撤销一组负载均衡&#xff0c;所以需要更改阿里云域名解析台里某个域名由原来绑定的负载均衡公网IP换到服务器公网IP 2.在服务器上nginx指定了域名访问&#xff0c;开启nginx服务 3.暂时关闭该组负载均衡服务 4.实现通过服务器IP可以访问项目&#xff0c;域名访问不了 …

秒懂数据类型的真谛—Python基础前传(4)

一切编程语言都是人设计的&#xff0c;既然是人设计的&#xff0c;那么设计各种功能的时候就一定会有它的道理&#xff0c;那么设计数据类型的用意是什么呢&#xff1f; (一) 基本数据类型 基本数据类型&#xff1a; 数字 int字符串 str布尔值 bool列表 list元组 tuple字典 dic…

Linux 系统命令及其使用详解(大全)

Linux 系统命令及其使用详解(大全) (来源: 中国系统分析员) cat cd   chmod chown   cp cut   名称&#xff1a;cat   使用权限&#xff1a;所有使用者   使用方式&#xff1a;cat[-AbeEnstTuv] [--help] [--version] fileName   说明&#xff1a;把档案串连…

wordpress配置SMTP服务发送邮件

使用SMTP服务发送邮件&#xff0c;需要使用一个插件&#xff1a;http://wordpress.org/extend/plugins/wp-mail-smtp/ 下载完成以后解压到plugin目录&#xff0c;然后在插件中启用这个插件。 配置SMTP服务 SMTP的选项 发送一封测试邮件吧 >>> 本文转自齐师傅博客园博客…

使用rpm包安装mysql_centos下利用rpm包安装mysql

安装mysql步骤&#xff1a;第一、 http://www.mysql.com/downloads/mysql-4.0.html下载MySQL-client-5.0.96-1.glibc23.x86_64.rpm和MySQL-server-5.0.96-1.glibc23.x86_64.rpm第二、安装服务端&#xff1a;[rootlfl01 mysql]# rpm -ivh MySQL-server-5.1.73-1.glibc23.i386.rp…

maxN - 返回数组中N个最大元素 minN - 返回数组中N个最小元素

从提供的数组中返回 n 个最小元素。如果 n 大于或等于提供的数组长度&#xff0c;则返回原数组&#xff08;按降序排列&#xff09;。 结合使用Array.sort() 与展开操作符(...) &#xff0c;创建一个数组的浅克隆&#xff0c;并按降序排列。 使用 Array.slice() 以获得指定的元…

Linux 常用命令

Linux之所以受到广大计算机爱好者的喜爱&#xff0c;主要原因有两个&#xff0c;首先它是自由软件&#xff0c;用户不用支付费用就可以使用它&#xff0c;并可根据自己的需要对它进行修改。另外&#xff0c;它具有Unix的全部功能&#xff0c;任何使用Unix系统或想要学习Unix系统…

使用Server 2008新GPO做驱动器映射

在Server 2003的时代&#xff0c;我们为用户做网络驱动器映射(以下就直接称为Map Network Drive&#xff09;, 通常可能有以下的做法. 方法一: 做一个登录脚本&#xff0c;放在DC的netlogon目录&#xff0c;接着在“Active Directory用户和计算机”控制台的用户属性的Logon S…

electron 打包后 __static_electron开发客户端注意事项(兼开源个人知识管理工具“想学吗”)...

窗口间通信的问题electron窗口通信比nwjs要麻烦的多electron分主进程和渲染进程&#xff0c;渲染进程又分主窗口的渲染进程和子窗口的渲染进程主窗口的渲染进程给子窗口的渲染进程发消息subWin.webContents.on(dom-ready, () > {subWin.webContents.send(message, {title: s…

180118 有趣的人工智能对话小程序

print(Hello world!) #输入 print(What is your name?) # ask for their name 询问名字 myName input()   #该你来回答名字了 print(It is good to meet you, myName)  #根据你的名字来给你打个招呼 print(The length of your name is:)  #然后看下一句 print(len(…