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. Flink整合面向用户的数据流SDKs/API(Flink关于弃用Dataset API的论述)

    动机 Flink提供了三种主要的sdk/API来编写程序:Table API/SQL.DataStream API和DataSet API.我们认为这个API太多了,建议弃用DataSet API,而 ...

  2. MySQL - 分页问题

    MySQL中的分页 MySQL中通过LIMIT关键字可以实现分页,如:(其中0表示开始记录数,10表示返回数据的数量) SELETE * FROM table_name LIMIT 0, 10 MyB ...

  3. RPA应用场景-对公账户开户资质审查

    场景概述 对公账户开户资质审查 所涉系统名称 人民银行账户管理系统 人工操作(时间/次) 0.5小时 所涉人工数量 132 操作频率 不定时 场景流程 1.机器人自动登录人民银行账户管理系统 2.查询 ...

  4. Java判断字符串是否为金额

    public static void main(String[] args) { String aa = "5632.2"; //小数点前后是数字即可,无小数点后数据也ok Sys ...

  5. identityserver4 (ids4)中如何获取refresh_token刷新令牌token 使用offline_access作用域

    ids4默认自带的api接口/api/connect/token 调用这个接口的时候,需要在body里面的 x-www-form-urlencoded模式下写 {     grant_type: &q ...

  6. (一)Linux环境的学习环境的搭建

    我们使用VMWARE来安装Debian11系统来进行我们的LINUX学习 Debian虚拟机的安装 vmware-tools的安装 xShell的安装使用 samba的配置 gcc环境的配置 Debi ...

  7. antd vue 折叠面板 v-for 循环点击无效

    问题描述 实现一个折叠面板点击展开,但是必须点击两次才能展开,第一次无效 <a-collapse-panel v-for="(item, index) in dataMap" ...

  8. Linux串口编程进阶

    在<Linux串口编程>编程一文中介绍了串口应用中常用的基本操作,如:串口打开关闭.串口设置.数据收发等.本篇文章主要基于常规串口操作进行了扩充,主要介绍如下操作: Linux系统使用非标 ...

  9. python sphinx(文档生成器)入门

    简介 Sphinx 是一个 文档生成器 ,您也可以把它看成一种工具,它可以将一组纯文本源文件转换成各种输出格式,并且自动生成交叉引用.索引等.也就是说,如果您的目录包含一堆 reStructuredT ...

  10. 青山不遮,毕竟东流,集成Web3.0身份钱包MetaMask以太坊一键登录(Tornado6+Vue.js3)

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_213 上世纪九十年代,海湾战争的时候,一位美军军官担心他们的五角大楼会被敌人的一枚导弹干掉,从而导致在全球的美军基地处于瘫痪状态. ...