Spring Boot 项目配置文件

文章目录

  • 配置文件的作用
  • properties
    • 基本语法
    • 读取文件信息
    • 缺点
  • yml
    • 基本语法
    • 优点
    • 配置不同数据类型
      • 字符串类型的写法
    • 配置对象
    • 配置集合
  • 读取配置文件的几种方法
    • Environment
    • @PropertySource
    • 使用原生方式读取
  • 设置不同环境的配置文件

配置文件的作用

整个项目中重要的数据都是在配置文件中配置的,例如:

  1. 数据库的连接信息(包含连接主机、用户名和密码的设置);
  2. 项目的启动端⼝;
  3. 第三方系统的调用秘钥等信息;
  4. 发现和定位问题的普通日志和异常日志等

Spring Boot 配置文件主要分为以下两种格式:

  1. .properties
  2. .yml

配置文件都是放在:/src/main/resources中的,默认的 Spring Boot 项目生产的是 .properties 格式的配置文件,.yml 格式文件需要自己手动创建

image-20240127174835923

注意事项:

  1. properties 可以和 yml ⼀起存在于⼀个项目当中,但是如果两个配置文件中出现了同样的配置那么会以 properties 中的配置为主,但加载完 .properties 文件之后,也会加载 .yml 文件的配置信息。
  2. properties 配置文件是 Spring Boot 项目的默认配置文件

properties

基本语法

properties 是以键值的形式配置的,key 和 value 之间以 “=” 连接。

# 注释
server.port=8088
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding= utf8 
spring.datasource.username=root 
spring.datasource.password=root

读取文件信息

在项目中想要主动的读取配置文件中的内容,可以使用 @Value 注解来实现

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/* @Component 在 Spring Boot 启动时候会注入到框架中注⼊到框架中时会执⾏ @PostConstruct初始化⽅法读取配置文件信息
*/@Component
public class UserComponent {@Value("${server.port}")private String port;@PostConstructpublic void postConstruct() {System.out.println("Read properties: port: " + port);}
}

image-20240127175626724

缺点

例如下面的配置信息中:

# 注释
server.port=8088
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding= utf8 
spring.datasource.username=root 
spring.datasource.password=root

从上述配置key看出,properties 配置文件中会有很多的冗余的信息,出现了很多次的 spring.datasource.

这样写起来就很麻烦,代码也不好看,这时候旧的考虑 yml 配置文件了

yml

基本语法

yml 是树形结构的配置文件,基础语法是“key: value”,注意:key 和 value 之间使用英文冒汗加空格的方式组成的,空格不可省略

# 注释
spring:datasource:url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8username: rootpassword: root

这样写出来了代码就简约明了

优点

  1. yml 是⼀个可读性高,写法简单、易于理解,它的语法和 JSON 语⾔类似。
  2. yml 更多的数据类型,它可以简单表达清单(数组)、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件等。
  3. yml 支持更多的编程语言,它不止是 Java 中可以使用在 Golang、PHP、Python、Ruby、 JavaScript、Perl 中同样可以

配置不同数据类型

# 注释
string: helloboolean: trueint: 22float: 22.22

那么对于 yml 的获取文件信息,和 properties是一样的,同样使用 @Value zhujie

@Controller
public class UserController {@Value("${string}")private String hello;@Value("${boolean}")private String bool;@Value("${int}")private String Int;@Value("${float}")private String Flo;@PostConstructpublic void doPostConstruct(){System.out.println("string: " + hello);System.out.println("boolean: " + bool);System.out.println("int: " + Int);System.out.println("float: " + Flo);}
}

字符串类型的写法

  1. 字符串默认不要加上单引号或者双引号
  2. 加英文的单双引号就会表示特殊的含义
# 注释
str1: hel\nlo
str2: 'hel\nlo'
str3: "hel\nlo"

\n 是有着换行的特殊含义的,那么对于加或不加的字符串会有什么效果

image-20240127183418995

可以看到,不加和加了单引号就会得到 原所写的字符串

加了双引号就会变成原义输出

配置对象

yml 可以直接配置对象

student:id: 1name: 张三age: 22

或者可以使用行内式

student: {id: 1, name: 张三, age: 22}

配置好了之后就可以直接通过 @ConfigurationProperties 注解去获取配置对象了

@Getter
@Setter
@ConfigurationProperties(prefix = "student")
@Component
public class StudentComponent {private String name;private int id;private int age;@Overridepublic String toString() {return "StudentComponent{" + "id= " + id + ", " +"name= '" + name + '\'' +", age= " + age + '}';}
}

注意:使用 @ConfigurationProperties 注解的类一定要有 Get和Set 方法。可以跟上述代码一样使用 LomBok 也可以直接写出来

通过控制类去获取该 Bean 打印查看结果

@Component
public class StudentController {@Autowiredprivate StudentComponent studentComponent;@PostConstructpublic void print(){System.out.println(studentComponent);}
}

image-20240127204849860

配置集合

yml 也可以配置集合

dbtypes:name:- mysql- sqlserver- test

或者使用行内式

dbtypes: {name: [mysql, sqlserver, test]}

然后通过list 去接收

@Getter
@Setter
@ConfigurationProperties(prefix = "dbtypes")
@Component
public class NameComponent {private List<String> name;
}

通过控制类去获取该 Bean 打印查看结果

@Component
public class NameController {@Autowiredprivate NameComponent nameComponent;@PostConstructpublic void print(){System.out.println(nameComponent.getName());}
}

image-20240127205513882

读取配置文件的几种方法

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

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

@Value 和 @ConfigurationProperties 在上文已经讲过了

Environment

首先 Environment 是一个类,这个类可以直接使用 @Autowired 去注入,注入完成后就可以调用其 getProperty 方法去获取指定配置信息了

@SpringBootApplication
public class SpringbootDemoApplication implements InitializingBean {@Autowiredprivate Environment environment;public static void main(String[] args) {SpringApplication.run(SpringbootDemoApplication.class, args);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("str1:" + environment.getProperty("str1"));}
}

image-20240127211403086

@PropertySource

使用 @PropertySource 注解可以用来指定读取某个配置文件,但是只是指定,还是得用到 @Value注解去获取

@SpringBootApplication
@PropertySource("classpath:application.yml")
public class SpringbootDemoApplication implements InitializingBean {@Value("${str1}")private String str1;public static void main(String[] args) {SpringApplication.run(SpringbootDemoApplication.class, args);}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("str1:" + str1);}
}

使用原生方式读取

最原始的方式就是通过 Properties 对象来读取配置文件

@SpringBootApplication
public class SpringbootDemoApplication implements InitializingBean {public static void main(String[] args) {SpringApplication.run(SpringbootDemoApplication.class, args);}@Overridepublic void afterPropertiesSet() throws Exception {Properties props = new Properties();try {// 指定配置文件InputStreamReader inputStreamReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("application.yml"),StandardCharsets.UTF_8);props.load(inputStreamReader);} catch (IOException e1) {System.out.println(e1);}// 调用方法获取指定信息System.out.println("str1:" + props.getProperty("str1"));}
}

设置不同环境的配置文件

可能一个项目中不同阶段时所用的配置是不一样的,例如测试时使用的数据库是本地的,发布后使用的数据库是云端的,那这样就需要一个个修改。

在Spring Boot 项目中可以为不同的环境设置不同的配置文件,然后只需要修改主配置文件就可以指定使用哪一套配置文件,并且只需要将不同的配置分开,公共的配置还是可以放在主配置文件中。

主配置文件名必须为:

application.properties / application.yml

其他的配置文件前面部分必须统一,横杠后的任取

application-XXX.properties / application-XXX.yml

需要指定用某一个配置文件,只需要在主配置文件中加入

spring.profiles.active=XXX // 注意XXX是横杠后任取的名称

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

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

相关文章

springboot整合mqtt实现消息订阅和推送

前言 mica-mqtt-client-spring-boot-starter是一个基于Spring Boot的MQTT客户端启动器&#xff0c;它集成了mica-mqtt客户端&#xff0c;提供了在Spring Boot应用程序中使用MQTT协议进行消息通信的能力。以下是关于mica-mqtt-client-spring-boot-starter的简介&#xff1a; 特…

安装 vant-ui 实现底部导航栏 Tabbar

本例子使用vue3 介绍 vant-ui 地址&#xff1a;介绍 - Vant 4 (vant-ui.github.io) Vant 是一个轻量、可定制的移动端组件库 安装 通过 npm 安装&#xff1a; # Vue 3 项目&#xff0c;安装最新版 Vant npm i vant # Vue 2 项目&#xff0c;安装 Vant 2 npm i vantlatest-v…

Vue3下载WEBAPI导出的Excel文件

webApi查询数据保存为Excel /// <summary>/// 获取LMI3D相机涂胶测量数据/// </summary>/// <returns></returns>[HttpPost(Name "GetLMI3DGlueDataToExcel")]public async Task<IActionResult> GetLMI3DGlueDataToExcel(QueryGlueM…

一站式在线协作办公软件ONLYOFFICE,协作更便捷

1、ONLYOFFICE是什么&#xff1f; ONLYOFFICE是一款功能强大的在线协作办公软件&#xff0c;可以创建编辑Word文档、Excel电子表格&#xff0c;PowerPoint&#xff08;PPT&#xff09;演示文稿、Forms表单等多种文件。ONLYOFFICE支持多个平台&#xff0c;无论使用的是 Windows、…

河南省考后天网上确认,请提前准备证件照哦

✔报名时间&#xff1a;2024年1月18号一1月24号 ✔报名确认和缴费&#xff1a;2024年1月 31号一2月4号 ✔准考证打印&#xff1a;2024年3月12号一3月17号 ✔笔试时间&#xff1a;2024年3月16日-2024年3月17日。 ✔面试时间&#xff1a;面试时间拟安排在2024年5月中旬 报名网址&…

微信投票小程序源码系统:无限多开,吸粉利器, 礼物道具,功能强大 带完整的安装代码包以及搭建教程

随着互联网的不断发展&#xff0c;社交媒体已成为人们生活中不可或缺的一部分。而微信作为中国最大的社交软件之一&#xff0c;拥有着庞大的用户群体和广泛的影响力。在这样的背景下&#xff0c;微信投票小程序应运而生。今天小编要向大家介绍的是一个功能强大的微信投票小程序…

SpringBoot 结合 liteflow 规则引擎使用

1、前言 在日常的开发过程中&#xff0c;经常会遇到一些串行或者并行的业务流程问题&#xff0c;而业务之间不必存在相关性。 在这样的场景下&#xff0c;使用策略和模板模式的结合可以很好的解决这个问题&#xff0c;但是使用编码的方式会使得文件太多,在业务的部分环节可以…

5G智慧钢铁厂数字孪生三维可视化,推进钢铁新型工业化数字化转型

5G智慧钢铁厂数字孪生三维可视化&#xff0c;推进钢铁新型工业化数字化转型。随着科技的不断发展&#xff0c;数字化转型已经成为钢铁企业转型升级的必经之路。而5G技术的广泛应用&#xff0c;为钢铁企业数字化转型提供了新的机遇。其中&#xff0c;5G智慧钢铁厂数字孪生三维可…

Leetcode—2396. 严格回文的数字【中等】

2024每日刷题&#xff08;一零六&#xff09; Leetcode—2396. 严格回文的数字 算法思想 实现代码 class Solution { public:bool isStrictlyPalindromic(int n) {return false;} };运行结果 之后我会持续更新&#xff0c;如果喜欢我的文章&#xff0c;请记得一键三连哦&…

在centos 7 中 安装 配置 并 远程连接 MySQL5.7

目录 安装MySQL 1.卸载CentOS7系统自带的mariadb 2.安装依赖库 3.上传MySQL并解压 4.安装MySQL 配置MySQL 1.修改登录密码 2.修改字符集 3.配置远程连接 前言&#xff1a; 安装MySQL版本&#xff1a;mysql-5.7.30-1.el7.x86_64.rpm-bundle 文件需求后台私信 以下7条为…

云纱网签约百望云,联手打造数字化产业闭环

近日&#xff0c;百望云签约广东云纱数字科技有限公司&#xff0c;共建数字化发票管理系统&#xff0c;赋能产业链上下游供应商的协同交易与运营&#xff0c;助力企业实现数字化四流合一交易&#xff0c;打造数字化产业闭环。 云纱网是广东云纱数字科技有限公司依托于深厚的产业…

动态分析C语言代码生成函数调用关系的利器——perf

大纲 环境准备安装开启监控 分析采集解析 可视化处理环境准备转换成dot转换为图片 参考资料 perf是一套linux操作系统上分析工具集&#xff0c;分析函数调用关系只是其一个子集功能。它并不像《动态分析C语言代码生成函数调用关系的利器——gprof》中介绍的需要在被分析程序的编…