一.Java读取properties文件

1、基于ClassLoder读取配置文件

注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便。

 Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
// 使用properties对象加载输入流
properties.load(in);
//获取key对应的value值
properties.getProperty(String key);

2、基于 InputStream 读取配置文件

注意:该方式的优点在于可以读取任意路径下的配置文件

 Properties properties = new Properties();

 // 使用InPutStream流读取properties文件

 BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));

 properties.load(bufferedReader);

 // 获取key对应的value值properties.getProperty(String key);

3、通过 java.util.ResourceBundle 类来读取,这种方式比使用 Properties 要方便一些

  1>通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可

 properties.getProperty(String key);
//config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
String key = resource.getString("keyWord");

  2>从 InputStream 中读取,获取 InputStream 的方法和上面一样,不再赘述

 ResourceBundle resource = new PropertyResourceBundle(inStream);

注意:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,那么需要使用包名限定,如:config.properties入在com.test.config包下,则要使用com/test/config/config.properties(通过Properties来获取)或com/test/config/config(通过ResourceBundle来获取);属性文件在src根目录下,则直接使用config.properties或config即可。

以下是几种方式的代码参考:

 package com.test.properties;

 import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties; import org.springframework.core.io.support.PropertiesLoaderUtils; /**
*
* @ClassName: TestProperties
* @Description: 获取配置文件信息
* @date: 2017年11月25日 上午10:56:00
* @version: 1.0.0
*/
public class TestProperties { /**
*
* @Title: printAllProperty
* @Description: 输出所有配置信息
* @param props
* @return void
* @throws
*/
private static void printAllProperty(Properties props)
{
@SuppressWarnings("rawtypes")
Enumeration en = props.propertyNames();
while (en.hasMoreElements())
{
String key = (String) en.nextElement();
String value = props.getProperty(key);
System.out.println(key + " : " + value);
}
} /**
* 根据key读取value
*
* @Title: getProperties_1
* @Description: 第一种方式:根据文件名使用spring中的工具类进行解析
* filePath是相对路劲,文件需在classpath目录下
* 比如:config.properties在包com.test.config下,
* 路径就是com/test/config/config.properties
*
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
public static String getProperties_1(String filePath, String keyWord){
Properties prop = null;
String value = null;
try {
// 通过Spring中的PropertiesLoaderUtils工具类进行获取
prop = PropertiesLoaderUtils.loadAllProperties(filePath);
// 根据关键字查询相应的值
value = prop.getProperty(keyWord);
} catch (IOException e) {
e.printStackTrace();
}
return value;
} /**
* 读取配置文件所有信息
*
* @Title: getProperties_1
* @Description: 第一种方式:根据文件名使用Spring中的工具类进行解析
* filePath是相对路劲,文件需在classpath目录下
* 比如:config.properties在包com.test.config下,
* 路径就是com/test/config/config.properties
*
* @param filePath
* @return void
* @throws
*/
public static void getProperties_1(String filePath){
Properties prop = null;
try {
// 通过Spring中的PropertiesLoaderUtils工具类进行获取
prop = PropertiesLoaderUtils.loadAllProperties(filePath);
printAllProperty(prop);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 根据key读取value
*
* @Title: getProperties_2
* @Description: 第二种方式:使用缓冲输入流读取配置文件,然后将其加载,再按需操作
* 绝对路径或相对路径, 如果是相对路径,则从当前项目下的目录开始计算,
* 如:当前项目路径/config/config.properties,
* 相对路径就是config/config.properties
*
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
public static String getProperties_2(String filePath, String keyWord){
Properties prop = new Properties();
String value = null;
try {
// 通过输入缓冲流进行读取配置文件
InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
// 加载输入流
prop.load(InputStream);
// 根据关键字获取value值
value = prop.getProperty(keyWord);
} catch (Exception e) {
e.printStackTrace();
}
return value;
} /**
* 读取配置文件所有信息
*
* @Title: getProperties_2
* @Description: 第二种方式:使用缓冲输入流读取配置文件,然后将其加载,再按需操作
* 绝对路径或相对路径, 如果是相对路径,则从当前项目下的目录开始计算,
* 如:当前项目路径/config/config.properties,
* 相对路径就是config/config.properties
*
* @param filePath
* @return void
* @throws
*/
public static void getProperties_2(String filePath){
Properties prop = new Properties();
try {
// 通过输入缓冲流进行读取配置文件
InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
// 加载输入流
prop.load(InputStream);
printAllProperty(prop);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 根据key读取value
*
* @Title: getProperties_3
* @Description: 第三种方式:
* 相对路径, properties文件需在classpath目录下,
* 比如:config.properties在包com.test.config下,
* 路径就是/com/test/config/config.properties
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
public static String getProperties_3(String filePath, String keyWord){
Properties prop = new Properties();
String value = null;
try {
InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
prop.load(inputStream);
value = prop.getProperty(keyWord);
} catch (IOException e) {
e.printStackTrace();
}
return value;
} /**
* 读取配置文件所有信息
*
* @Title: getProperties_3
* @Description: 第三种方式:
* 相对路径, properties文件需在classpath目录下,
* 比如:config.properties在包com.test.config下,
* 路径就是/com/test/config/config.properties
* @param filePath
* @return
* @throws
*/
public static void getProperties_3(String filePath){
Properties prop = new Properties();
try {
InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
prop.load(inputStream);
printAllProperty(prop);
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) {
// 注意路径问题
String properties_1 = getProperties_1("com/test/config/config.properties", "wechat_appid");
System.out.println("wechat_appid = " + properties_1);
getProperties_1("com/test/config/config.properties");
System.out.println("*********************************************");
// 注意路径问题
String properties_2 = getProperties_2("configure/configure.properties", "jdbc.url");
System.out.println("jdbc.url = " + properties_2);
getProperties_2("configure/configure.properties");
System.out.println("*********************************************");
// 注意路径问题
String properties_3 = getProperties_3("/com/test/config/config.properties", "wechat_appid");
System.out.println("wechat_appid = " + properties_3);
getProperties_3("/com/test/config/config.properties");
}
}

参考链接:https://www.cnblogs.com/sebastian-tyd/p/7895182.html

二.SpringMVC读取properties文件

<bean id="propertyPlaceHolderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<!-- 把需要配置的properties文件配置在这里,可以有多个 -->
<value>classpath:config.properties</value>
</list>
</property>
</bean>

2、config.properties文件

## 这里配置自己的值
config.attr1=123456
config.attr2=adjfl12313

3、java代码,使用@value注解

// config.attr1是properties文件配置的键值
@Value("${config.attr1}")
private String attr1; @Value("${config.attr2}")
private String attr2;

三.spring读取properties文件

1.通过PropertyPlaceholderConfigurer来加载

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>src/jdbc.properties</value>
</property>
</bean> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${driverClassName}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${username}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean> <bean id="dao" class="com.zh.model.DataDAO">
<property name="datasource">
<ref local="datasource"/>
</property>
</bean> </beans>

2.通过 context:property-placeholder 标签实现配置文件加载

(1)、在spring.xml配置文件中添加标签

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

(2)、在 spring.xml 中使用 配置文件属性:$

<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /

(3)、在java文件中使用:

@Value("${jdbc.url}")
private String jdbcUrl; // 注意:这里变量不能定义成static

*注意点:踩过的坑

在Spring中的xml中使用<context:property-placeholderlocation>标签导入配置文件时,想要导入多个properties配置文件,如下:

<context:property-placeholderlocation="classpath:db.properties " />

<context:property-placeholderlocation="classpath:zxg.properties " />

结果发现不行,第二个配置文件始终读取不到,Spring容器是采用反射扫描的发现机制,通过标签的命名空间实例化实例,当Spring探测到容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描,即只能存在一个实例

如果有多个配置文件可以使用 “,” 分隔

<context:property-placeholderlocation="classpath:db.properties,classpath:monitor.properties" />

可以使用通配符 *

<context:property-placeholderlocation="classpath:*.properties" />

属性用法

ignore-resource-not-found //如果属性文件找不到,是否忽略,默认false,即不忽略,找不到文件并不会抛出异常。
ignore-unresolvable //是否忽略解析不到的属性,如果不忽略,找不到将抛出异常。但它设置为true的主要原因是:

3.通过 util:properties 标签实现配置文件加载

(1)、用法示例: 在spring.xml配置文件中添加标签

<?xml version="1.0" encoding="UTF-8"?>
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 加载配置文件 -->
<util:properties id="jdbc" local-override="true" location="classpath:properties/jdbc.properties"/>

(2)、在spring.xml 中使用配置文件属性:#

<!-- dataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="#{jdbc.driverClass}" />
<property name="jdbcUrl" value="#{jdbc.jdbcUrl}" />
<property name="user" value="#{jdbc.user}" />
<property name="password" value="#{jdbc.password}" />
</bean>

(3)、java文件,让Spring注入从资源文件中读取到的属性的值,,为了简便,把几种注入的方式直接写入到一个文件中进行展示:

@Component
public class SysConf { @Value("#{jdbc.url}")
private String url;
    @Value("#{jdbc}")
public void setJdbcConf(Properties jdbc){
url= sys.getProperty("url");
}
}

 注意:这里的#{jdbc} 是与第1步的id="jdbc" 相对应的

4、通过 @PropertySource 注解实现配置文件加载

使用和  context:property-placeholder 差不多

(1)、用法示例:在java类文件中使用 PropertySource 注解

@PropertySource(value={"classpath:mail.properties"})
public class ReadProperties {
  @Value(value="${mail.username}")
  private String USER_NAME;
}

四、springboot读取properties文件

1.默认读取application.properties文件

   @Value("${demo.name}")
            private String name;
            @Value("${demo.age}")
            private String age;

或者

需要一个spring-boot启动类

@SpringBootApplication
@EnableConfigurationProperties({PropsConfig.class,YmlConfig.class}) 
public class ReadApplication {
    public static void main(String[] args) {
        SpringApplication.run(ReadApplication.class, args);
    }
}

没错,@EnableConfigurationProperties注解里指出的PropsConfig.class,YmlConfig.class分别就是读取props和yml配置文件的类。接下来,我们分别进行读取properties和yml配置文件的具体实现。

在类路径下放置一个application.properties文件。

读取props配置的类,很简单,基本就是一个pojo/vo类,在类上加载@ConfigurationProperties注解即可。

@ConfigurationProperties(prefix = "master.ds",locations = "classpath:application.properties")

2.通过PropertiesLoaderUtils

ClassPathResource resource = new ClassPathResource(APPLICATION_PROPERTIES);

Properties properties = PropertiesLoaderUtils.loadProperties(resource);

String property = properties.getProperty(SPRING_BOOT_HELLO, UNDEFINED);

System.out.println("4. 通过PropertiesLoaderUtils获取: " + property);

3.@ConfigurationProperties和@PropertySource

作用在类上用于注入Bean属性,

然后再通过当前Bean获取注入值:

@SpringBootApplication
public class AttributeApplication { private static final String APPLICATION_YML = "application.yml";
private static final String SPRING_BOOT_PREFIX = "spring-boot"; @Data
@Component
@PropertySource("classpath:" + APPLICATION_YML)
@ConfigurationProperties(prefix = SPRING_BOOT_PREFIX)
class Attribute { private String hello;
private String world; }

1.8版本及以上,若引入多个properties文件:

@Configuration

@PropertySource("classpath:1.properties")

@PropertySource("classpath:2.properties")

@PropertySource("...")

public class XConfiguration{}

1.8版本以下,若引入多个properties文件:

@Configuration

@PropertySources({

  @PropertySource("classpath:1.properties")

  @PropertySource("classpath:2.properties")

})

public class XConfiguration{}

关于properties文件的读取(Java/spring/springmvc/springboot)的更多相关文章

  1. Spring SpringMVC SpringBoot SpringCloud 注解整理大全

    Spring SpringMVC SpringBoot SpringCloud 注解整理 才开的博客所以放了一篇以前整理的文档,如果有需要添加修改的地方欢迎指正,我会修改的φ(๑˃∀˂๑)♪ Spri ...

  2. spring springMvc spring-boot spring-cloud分别是什么

    本文来源于:克己习礼成仁   的<spring springMvc spring-boot spring-cloud分别是什么> 什么是spring 关于spring的定义无论是从官方还是 ...

  3. Java Bean 获取properties文件的读取

    实际的开发过程中,将一些配置属性从java代码中提取到properties文件中是个很好的选择,降低了代码的耦合度.下面介绍两种通过spring读取properties文件的方法,以ip地址配置为例. ...

  4. Android 对.properties文件的读取

    /** * * @param filepath .properties文件的位置 */ public void checkFileExists(String filepath){ File file ...

  5. properties文件的读取

    Demo //声明资源器类 Properties pro=new Properties(); //获取路径 URL url= PropertiesTest.class.getClassLoader() ...

  6. [Java] Spring + SpringMVC + Maven + JUnit 搭建

    示例项目下载: https://github.com/yangyxd/SpringDemo 利用前面 SpringMVC 项目的配置方式,完成初步的项目创建.下面只讲一些不同之处. 传送门: [Jav ...

  7. Properties文件工具读取类

    import java.io.IOException;import java.io.InputStream;import java.util.Properties; public class Comm ...

  8. Spring SpringMVC SpringBoot SpringCloud概念、关系及区别

    一.正面解读: Spring主要是基于IOC反转Beans管理Bean类,主要依存于SSH框架(Struts+Spring+Hibernate)这个MVC框架,所以定位很明确,Struts主要负责表示 ...

  9. 【微服务系列】Spring SpringMVC SpringBoot SpringCloud概念、关系及区别

    一.正面解读 Spring主要是基于IOC反转Beans管理Bean类,主要依存于SSH框架(Struts+Spring+Hibernate)这个MVC框架,所以定位很明确,Struts主要负责表示层 ...

随机推荐

  1. bootstrap-table的一些配置参数例子

    $('#reportTable').bootstrapTable({ method: 'post', url: '/qStock/AjaxPage', dataType: "json&quo ...

  2. 【AI】【计算机】【中国人工智能学会通讯】【学会通讯2019年第01期】中国人工智能学会重磅发布 《2018 人工智能产业创新评估白皮书》

    封面: 中国人工智能学会重磅发布 <2018 人工智能产业创新评估白皮书> < 2018 人工智能产业创新评估白皮书>由中国人工智能学会.国家工信安全中心.华夏幸福产业研究院. ...

  3. Django 实现登录后跳转

    说明 实现网页登录后跳转应该分为两类:即登录成功后跳转和登录失败再次登录成功后跳转.参考网上内容,基本都只实现了第一类.而没有实现第二类. 实现 为了能让登录失败后再次登录成功后还能实现跳转.我这里采 ...

  4. ubuntu18上传代码到github

    其实在github上建仓库时候就提示你步骤了: 1.注册个github账号并登录 创建一个仓库 https://github.com/ 2.创建SSH Key ssh-keygen -t rsa -C ...

  5. Thinking In Java 4th Chap5 初始化和清理

    类的构造器名必须与类名一致,且无返回类型,通过参数类型的不同(即使顺序不同也行)可以重载构造器,也可以以此技巧重载方法 this关键字:表示对“调用方法的那个对象的引用”,也可将当前对象传递给其他方法 ...

  6. vue的 :class 与 :style 的讲解

    Vue样式: Vue中通过属性绑定为元素的class样式 第一种使用方式:直接传递一个数组 注意:这里的class需要使用v-bind做数据绑定 第二种使用方式:在数组中使用三元表达式 第三种使用方式 ...

  7. 用bisect来管理已排序的序列

    bisect 模块包含两个主要函数,bisect 和 insort,两个函数都利用二分查找算法来在有序序列中查找或插入元素. 2.8.1 用bisect来搜索 bisect(haystack, nee ...

  8. 牛客 P21336 和与或 (数位dp)

    大意: 给定数组$R$, 求有多少个数组$A$, 满足$0\le A_i \le R_i$且$A_0+...+A_{N-1}=A_0\space or ...\space or \space A_{N ...

  9. ideaIU-2019.2.exe-安装目录和设置目录结构的说明

    一.查看安装目录结构 bin: 容器,执行文件和启动参数等 help:快捷键文档和其他帮助文档 jbr: 含有java运行环境 lib:idea 依赖的类库 license:各个插件许可 plugin ...

  10. POJ 1860 汇率 SPFA

    题意 有多种汇币,汇币之间可以交换,这需要手续费,当你用100A币交换B币时,A到B的汇率是29.75,手续费是0.39,那么你可以得到(100 - 0.39) * 29.75 = 2963.3975 ...