Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件。
  2. 使用 @ConfigurationProperties 读取配置文件。
  3. 使用 Environment 读取配置文件。
  4. 使用 @PropertySource 读取配置文件。
  5. 使用原生方式读取配置文件。

它们的具体使用方法如下,为了方便测试,我们在 Spring Boot 配置文件 application.properties 添加以下内容:

profile.name=Spring Boot Profile
profile.desc=Spring Boot Profile Desc.

1.使用 @Value 读取配置文件

使用 @Value 可以读取单个配置项,如下代码所示:

@SpringBootApplication
public class DemoApplication implements InitializingBean {
@Value("${profile.name}")
private String name; public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("My Profile Name:" + name);
}
}

以上程序的执行结果如下图所示:

2.使用 @ConfigurationProperties 读取配置文件

@ConfigurationProperties 和 @Value 的使用略微不同,@Value 是读取单个配置项的,而 @ConfigurationProperties 是读取一组配置项的,我们可以使用 @ConfigurationProperties 加实体类读取一组配置项,如下代码所示:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "profile")
@Data
public class Profile {
private String name;
private String desc;
}

其中 prefix 表示读取一组配置项的根 name,相当于 Java 中的类名,最后再把此配置类,注入到某一个类中就可以使用了,如下代码所示:

@SpringBootApplication
public class DemoApplication implements InitializingBean {
@Autowired
private Profile profile; public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("Profile Object:" + profile);
}
}

以上程序的执行结果如下图所示:

3.使用 Environment 读取配置文件

Environment 是 Spring Core 中的一个用于读取配置文件的类,将此类使用 @Autowired 注入到类中就可以使用它的 getProperty 方法来获取某个配置项的值了,如下代码所示:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment; @SpringBootApplication
public class DemoApplication implements InitializingBean { @Autowired
private Environment environment; public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("Profile Name:" + environment.getProperty("profile.name"));
}
}

以上程序的执行结果如下图所示:

4.使用 @PropertySource 读取配置文件

使用 @PropertySource 注解可以用来指定读取某个配置文件,比如指定读取 application.properties 配置文件的配置内容,具体实现代码如下:

@SpringBootApplication
@PropertySource("classpath:application.properties")
public class DemoApplication implements InitializingBean {
@Value("${profile.name}")
private String name; public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("Name:" + name);
}
}

以上程序的执行结果如下图所示:

中文乱码

如果配置文件中出现中文乱码的情况,可通过指定编码格式的方式来解决中文乱码的问题,具体实现如下:

@PropertySource(value = "dev.properties", encoding = "utf-8")

注意事项

@PropertySource 注解默认是只支持 properties 格式配置文件的读取的。

5.使用原生方式读取配置文件

我们还可以使用最原始的方式 Properties 对象来读取配置文件,如下代码所示:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties; @SpringBootApplication
public class DemoApplication implements InitializingBean { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @Override
public void afterPropertiesSet() throws Exception {
Properties props = new Properties();
try {
InputStreamReader inputStreamReader = new InputStreamReader(
this.getClass().getClassLoader().getResourceAsStream("application.properties"),
StandardCharsets.UTF_8);
props.load(inputStreamReader);
} catch (IOException e1) {
System.out.println(e1);
}
System.out.println("Properties Name:" + props.getProperty("profile.name"));
}
}

以上程序的执行结果如下图所示:

总结

在 Spring Boot 中读取配置文件有以下 5 种方法:

  1. 使用 @Value 读取配置文件。
  2. 使用 @ConfigurationProperties 读取配置文件。
  3. 使用 @PropertySource 读取配置文件。
  4. 使用 Environment 读取配置文件。
  5. 使用原生方式读取配置文件。

其中最常用的是前 3 种,如果读取某一个配置项可使用 @Value,如果读取一组配置项可使用 @ConfigurationProperties,如果要指定读取某一个具体的配置文件可使用 @PropertySource 来指定。

是非审之于己,毁誉听之于人,得失安之于数。

公众号:Java面试真题解析

面试合集:https://gitee.com/mydb/interview

面试突击75:SpringBoot 有几种读取配置文件的方法?的更多相关文章

  1. SpringBoot学习笔记:读取配置文件

    SpringBoot学习笔记:读取配置文件 配置文件 在以往的项目中,我们主要通过XML文件进行框架配置,业务的相关配置会放在属性文件中,然后通过一个属性读取的工具类来读取配置信息.在SpringBo ...

  2. SpringBoot:四种读取properties文件的方式

    前言 在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作.今天就分享四种在Springboot中获取配置文件的方式. 注:前三种测试配置文件为springboot默认的applic ...

  3. springboot中使用@Value读取配置文件

    一.配置文件配置 直接配置 在src/main/resources下添加配置文件application.properties 例如修改端口号 #端口号 server.port=8089 分环境配置 在 ...

  4. Shell读取配置文件的方法

    参考:http://www.cnblogs.com/binbinjx/p/5680214.html 做批量软件安装自动化时,都喜欢用配置文件的方式改变参数,那怎么通过shell读取配置文件的配置呢?参 ...

  5. Log4j 2.0读取配置文件的方法

    log4j中配置日志文件存放的位置不一定在src下面,即根目录下.这个时候我们需要解决如何加载配置文件的问题.在log4j1.x中解决的方法就比较多了.如:PropertyConfigurator.c ...

  6. 【面试突击】-SpringBoot面试题(一)

    Spring Boot 是微服务中最好的 Java 框架. 我们建议你能够成为一名 Spring Boot 的专家. 问题一 Spring Boot.Spring MVC 和 Spring 有什么区别 ...

  7. SpringBoot两种读取配置文件的方式

    方式一 @Value("${custom.group}") private String customGroup; 方式二 @Autowired private Environme ...

  8. springboot @Value 类中读取配置文件 .properties null 原因和解决方案

    问题:在一个工具类中,通过@Value来映射配置文件的值,得到的总是null 原因:不能用new工具类的方式,应该是用容器注册(@Autowried)的方式使用此工具类,就能得到配置文件里的值 上代码 ...

  9. java中读取配置文件的方法

    转自:http://blog.csdn.net/stypace/article/details/38414871 一.使用org.apache.commons.configuration 需要使用的是 ...

随机推荐

  1. [KDTree]数列

    NKOJ传送门 describtion 给你一个序列,每个序列有编号(它本身的位置),标识符,数值. 有4种操作 op=0:l,r,x,y将编号在[l,r]的数值x+y op=1:l,r,x,y将标识 ...

  2. 解惑unittest框架中导入HTMLTestRunner模块后正常运行却无法生成HTML报告问题

    1.HTMLTestRunner介绍 HTMLTestRunner是一个第三方的unittest HTML报告库,用于python单元测试框架的TestRunner.它是生成一个HTML报告,以一目了 ...

  3. torch.ones_like(),expand_as(),expend()等torch.repeat

    https://blog.csdn.net/Arthur_Holmes/article/details/104267662 https://blog.csdn.net/weixin_39568781/ ...

  4. 写Selenium代码时一些技巧

    本文地址: https://www.cnblogs.com/hchengmx/p/10880002.html 1. Chrome插件之"CSS Selector Helper for Chr ...

  5. DevStream 成为 CNCF Sandbox 项目啦!- 锣鼓喧天、鞭炮齐鸣、红旗招展、忘词了。

    开局两张图,内容全靠"编" 来,有图有真相! DevStream ️ CNCF DevStream joins CNCF Sandbox CNCF Cloud Native Int ...

  6. JS:in语法

    1.应用于判断对象中是否有某一个成员 var obj = { name: "lili", age:10, gender:"girl" } console.log ...

  7. 记一次ms17-010复现过程

    最近碰到业务需要使用msf,以前了解过,后面都忘记了.这次干脆写下来,省的每次去找别人写的. 首先是使用nmap探测端口 nmap -O -sV 192.168.153.130 --script=vu ...

  8. Python基础学习笔记_02

    Python中的运算符 标准算术运算符 加(+) 减(-) 乘(*) 除(/) 整除(//) print(1+1) #加法运算 print(1-1) #减法运算 print(2*4) #乘法运算 pr ...

  9. SAP MM- BAPI_PO_CHANGE 更新PO version 信息(version management)

    目的 Version 信息的Complated 字段,自动打勾 实例程序 *&--------------------------------------------------------- ...

  10. SAP Tree editor(树形结构)

    SAP List Tree 效果 源代码 *&---------------------------------------------------------------------* *& ...