SpringBoot 读取配置文件的 5 种方法!

a7c7984f488bc4b958bfe9489b124e83.jpeg

作者 | 磊哥

来源 | Java面试真题解析(ID:aimianshi666)

转载请联系授权(微信ID:GG_Stone)

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);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("My Profile Name:" + name);}
}

以上程序的执行结果如下图所示:29597ae46ae5a5392f515e2818b73bd1.png

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 {@Autowiredprivate Profile profile;public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("Profile Object:" + profile);}
}

以上程序的执行结果如下图所示:4d2c396e5c887c2d235dd9ae3a473d73.png

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 {@Autowiredprivate Environment environment;public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("Profile Name:" + environment.getProperty("profile.name"));}
}

以上程序的执行结果如下图所示:19c15e2278c5381343312141d5991ecc.png

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);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("Name:" + name);}
}

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

中文乱码

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

@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);}@Overridepublic 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"));}
}

以上程序的执行结果如下图所示:5ab162be50655552914045d32379429b.png

总结

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

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

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

  3. 使用 @PropertySource 读取配置文件。

  4. 使用 Environment 读取配置文件。

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

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

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

公众号:Java面试真题解析

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

9afe1c75b2d4148679ba8e17235ae817.gif

往期推荐

f7e067222bb6ff3ffebfdfa50e1a9158.jpeg

面试突击74:properties和yml有什么区别?


793ea448572d18911a49de0b45bda80b.jpeg

面试突击73:IoC 和 DI 有什么区别?


e1c66098ed63d0922a3ff466e24dfc4d.jpeg

面试突击72:输入URL之后会执行什么流程?


9e14f56f2c85e8e61701d36d6735cb7a.gif

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

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

相关文章

机器学习朴素贝叶斯算法_机器学习中的朴素贝叶斯算法

机器学习朴素贝叶斯算法朴素贝叶斯算法 (Naive Bayes Algorithm) Naive Bayes is basically used for text learning. Using this algorithm we trained machine from text. 朴素贝叶斯基本上用于文本学习。 使用此算法,我们从文本中训练了机器。 Let’s understan…

jQuery的ajaxFileUpload上传文件插件刷新一次才能再次调用触发change

关于用ajaxfileupload时,遇到一个要刷新一次页面才能再次上传,用live()方法来绑定 file表单 的change事件就能够解决,直接$("xxx").change()这样只能调用一次,再次调用change的时候不能触发;IE浏览器下 file表单 选择完…

使用阿里巴巴 Druid 轻松实现加密!

作者 | 磊哥来源 | Java中文社群(ID:javacn666)转载请联系授权(微信ID:GG_Stone)为什么要加密?现在的开发习惯,无论是公司的项目还是个人的项目,都会选择将源码上传到 Gi…

xml不显示css样式_如何使用CSS显示XML?

xml不显示css样式Introduction: 介绍: You must be aware of the term XML and must have dealt with these various XML files while developing a web page or website. This article focuses entirely on XML and how to display them using CSS. There are num…

Spring Boot 如何优雅的校验参数?

今天介绍一下 Spring Boot 如何优雅的整合JSR-303进行参数校验,说到参数校验可能都用过,但网上的教程大多是简单的介绍,所以我们今天详细看来一下 。什么是 JSR-303?JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Va…

ruby hash方法_Ruby中带有示例的Hash.keys方法

ruby hash方法哈希键方法 (Hash.keys Method) In this article, we will study about Hash.keys Method. The working of the method cant be assumed because of its quite a different name. Let us read its definition and understand its implementation with the help of…

c#组元(Tuple)的使用

组元(Tuple)是C# 4.0引入的一个新特性,可以在.NET Framework 4.0或更高版本中使用。组元使用泛型来简化类的定义,多用于方法的返回值。在函数需要返回多个类型的时候,就不必使用out , ref等关键字了,直接定义一个Tuple类型&#x…

浅谈一下 MyBatis 批量插入的 3 种方法!

作者 | 磊哥来源 | Java中文社群(ID:javacn666)转载请联系授权(微信ID:GG_Stone批量插入功能是我们日常工作中比较常见的业务功能之一,今天咱们来一个 MyBatis 批量插入的汇总篇,同时对 3 种实现…

VMware 11安装Mac OS X 10.10 及安装Mac Vmware Tools.

http://www.bubuko.com/infodetail-790015.html#title3 http://my.oschina.net/vigiles/blog/141689#OSC_h2_9 http://www.360doc.com/content/10/0316/11/750552_18965817.shtml转载于:https://www.cnblogs.com/yuyang2100/p/4938829.html

kotlin 查找id_Kotlin程序查找圆柱体区域

kotlin 查找idA cylinder is a three-dimensional structure which has circular bases parallel to each other. 圆柱是具有彼此平行的圆形底的三维结构。 Formula to find area of a cylinder: 2*PI*(radiusheight) 查找圆柱体面积的公式:2 * PI *(半径高度) Gi…

快速搭建 SpringCloud Alibaba Nacos 配置中心!

作者 | 磊哥来源 | Java中文社群(ID:javacn666)转载请联系授权(微信ID:GG_Stone)Spring Cloud Alibaba 是阿里巴巴提供的一站式微服务开发解决方案,目前已被 Spring Cloud 官方收录。而 Nacos 作…

c# datetime._C#| DateTime.TimeOfDay属性(带示例)

c# datetime.DateTime.TimeOfDay属性 (DateTime.TimeOfDay Property) DateTime.TimeOfDay Property is used to get the time of the day of this object. Its a GET property of DateTime class. DateTime.TimeOfDay属性用于获取该对象一天中的时间。 这是DateTime类的GET属性…

JSP 基础(一)

JavaServletPage(JSP) 一 JSP简介 Servlet的缺陷–Servlet的编码、部署和调试任务繁琐–生成动态网页繁琐,不利于项目分工为了弥补Servlet的这些缺陷,SUN公司在Servlet的基础上推出了JSP技术作为解决方案采用JSP技术编写动态页面 –由HTML语句和嵌套在其…

浅聊一下建表的15个小技巧

前言对于后端开发同学来说,访问数据库,是代码中必不可少的一个环节。系统中收集到用户的核心数据,为了安全性,我们一般会存储到数据库,比如:mysql,oracle等。后端开发的日常工作,需要…

c# datetime._C#| 带示例的DateTime.DayOfWeek属性

c# datetime.DateTime.DayOfWeek属性 (DateTime.DayOfWeek Property) DateTime.DayOfWeek Property is used to return the day of the week. DateTime.DayOfWeek属性用于返回星期几。 Syntax: 句法: DayOfWeek DateTime.DayOfWeek;Return value: 返回值&#xff…

JConsole的使用手册 JDK1.5(转)

一篇Sun项目主页上介绍JConsole使用的文章,前段时间性能测试的时候大概翻译了一下以便学习,今天整理一下发上来,有些地方也不知道怎么翻,就保留了原文,可能还好理解点,呵呵,水平有限&#xff0c…

一文快速上手 Nacos 注册中心+配置中心!

作者 | 磊哥来源 | Java中文社群(ID:javacn666)转载请联系授权(微信ID:GG_Stone)Spring Cloud Alibaba 是阿里巴巴提供的一站式微服务开发解决方案,目前已被 Spring Cloud 官方收录。而 Nacos 作…

所有子序列的逆序对总和_一个数字的所有子串的总和

所有子序列的逆序对总和Problem statement: 问题陈述: Given an integer, S represented as a string, get the sum of all possible substrings of this string. 给定一个以字符串形式表示的整数S ,得到该字符串所有可能的子字符串的和 。 Input: 输入…

synchronized:使用不规范,老板泪两行!

线程安全问题一直是系统亘古不变的痛点。这不,最近在项目中发了一个错误使用线程同步的案例。表面上看已经使用了同步机制,一切岁月静好,但实际上线程同步却毫无作用。关于线程安全的问题,基本上就是在挖坑与填坑之间博弈&#xf…

SQL --运算符

2019独角兽企业重金招聘Python工程师标准>>> 一、<> (安全等于运算符) mysql中的 、<>或!运算符&#xff0c;相信大家已经很清楚了。今天看到了<>这个运算符&#xff0c;记录下来。 1><>和号的相同点 他们都是两个值比较符&#xff0c;相…