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. SpringBoot+Mybatis-Plus整合Sharding-JDBC5.1.1实现单库分表【全网最新】

    一.前言 小编最近一直在研究关于分库分表的东西,前几天docker安装了mycat实现了分库分表,但是都在说mycat的bug很多.很多人还是倾向于shardingsphere,其实他是一个全家桶,有 ...

  2. MIT 6.824(Spring 2020) Lab1: MapReduce 文档翻译

    首发于公众号:努力学习的阿新 前言 大家好,这里是阿新. MIT 6.824 是麻省理工大学开设的一门关于分布式系统的明星课程,共包含四个配套实验,实验的含金量很高,十分适合作为校招生的项目经历,在文 ...

  3. React简单教程-4-事件和hook

    前言 在上一章 React 简单教程-3-样式 中我们建立了一个子组件,并稍微美化了一下.在另一篇文章 React 简单教程-3.1-样式之使用 tailwindcss 章我们使用了 tailwind ...

  4. Python if-else的简单表示

    常见写法 a = 1 b = 1 c = 2 if a == b: print("true") elif a == c: print("false") else ...

  5. Python中的类变量和成员变量

    类变量 定义 在类里面定义,且不位于构造或者成员函数里面,同时没有" self. " 的前缀:或者在类外定义,用 类名.类变量名 来新增加类变量. 使用 两种使用方法: (1)类名 ...

  6. JVM学习笔记-从底层了解程序运行(一)

    1:JVM基础知识 什么是JVM 1. java虚拟机,跨语言的平台,实现java跨平台 2. 可以实现多种语言跨平台,只要该语言可以编译成.class文件 3. 解释执行.class文件 java是 ...

  7. QT5 QSS QML界面美化视频课程系列 QT原理 项目实战 C++1X STL

    QT5 QSS QML界面美化视频课程系列 QT原理 项目实战 C++1X STL 课程1   C语言程序设计高级实用速成课程 基础+进阶+自学 课程2   C语言程序设计Windows GDI图形绘 ...

  8. JavaScript写倒计时

    在网页中,特别是电商网站中,倒计时的出现频率很高,接下来给大家介绍一下怎么用JavaScript写一个倒计时.代码如下: 首先我们通过Date构造函数的方法创建一个倒计时的结束的时间.并将其转换为毫秒 ...

  9. Linux的文件路径和访问文件相关命令

    Linux的绝对和相对路径 绝地路径 绝对路径:以根作为起来的路径 相对路径 相对路径:以当前位置作为起点 文件操作命令 显示当前工作目录: pwd命令 pwd:显示文件所在的路径 基名:basena ...

  10. Python程序入口 __name__ == ‘__main__‘ 有重要功能(多线程)而非编程习惯

    文章来源于互联网(https://jq.qq.com/?_wv=1027&k=rX9CWKg4) 在Python中,被称为「程序的入口」的 if name =='main': 总是出现在各种示 ...