SpringBoot 配置文件

目录

一、配置文件快速入手

二、配置文件的格式

三、properties 配置文件说明

基本语法

读取配置文件

properties 缺点分析

四、yml 配置文件说明

基本语法

使用 yml 连接数据库

yml 使用进阶

配置不同数据类型及 null

yml 配置读取

注意事项: value 值加单双引号

配置对象

配置集合

配置 Map


一、配置文件快速入手

我们在前面讲了Tocmat 默认端口号是8080, 所以我们程序访问时的端口号也是8080。但是如果8080端口号已经被其他进程使用了呢? 我们可以通过配置文件来修改服务的端口号, SpringBoot 在创建项目时, 就已经帮我们创建了配置文件

spring.application.name=spring-book
server.port=9090

重新运行程序, 观察日志

此时8080就不能再访问了

解决方案有:把端口号的进程停掉或修改自己端口号

二、配置文件的格式

Spring Boot配置文件有以下三种:
🔹application.properties
🔹application.yml
🔹application.yaml

yml 为 yaml 的简写, 实际开发中出现频率最高. yaml 和yml 的使用方式⼀样, 这里只讲 yml 文件的使用

当应用程序启动时, Spring Boot 会自动从 classpath 路径找到并加载 application.properties 和 application.yaml 或者 application.yml 文件.

也可以通过 spring.config.name 指定文件路径和名称,参考https://docs.spring.io/spring-boot/reference/features/external-config.html#features.external-config.files

类似商品的包装一样,有新老两款包装 .properties 类型的配置文件就属于老款包装,也是创建
Spring Boot项目时默认的文件格式(主要是因为仓库里还有库存),而 yml 属于新版包装,如果用户了解情况直接指定要新款包装,那么就直接发给他 

📢特殊说明
1️⃣理论上讲 .properties 和 .yml 可以并存在于一个项目中,当 .properties 和 .yml 并存时,两个配置都会加载.如果配置文件内容有冲突,则以 .properties 为主,也就是 .properties 优先级更高.
2️⃣虽然理论上来讲 .properties 可以和 .yml 共存,但实际的业务当中,我们通常会采取一种统一的配置文件格式,这样可以更好的维护(降低故障率).

三、properties 配置文件说明

properties 配置文件是最早期的配置⽂件格式,也是创建 SpringBoot 项目默认的配置文件

基本语法

properties 是以键值的形式配置的,key 和 value 之间是以 "=" 连接的,如:

# 配置数据库连接信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

PS:小技巧:配置文件中使用 “#” 来添加注释信息

读取配置文件

如果在项目中,想要主动的读取配置文件中的内容,可以使用 @Value 注解来实现。@Value 注解使用 " ${} " 的格式读取,如下代码所示:

properties 配置如下:

my.key=test
package com.example.demo;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/prop")
@RestController
public class PropertiesController {
    @Value("${my.key}")
    private String myKey;

    @RequestMapping("/readValue1")
    public String readValue1() {
        return "从配置文件中读取配置信息:" + myKey;
    }

    @PostConstruct
    public void readValue2() {
        System.out.println(("从配置文件中读取配置信息:" + myKey));
    }
}

properties 缺点分析

properties 配置是以 key-value 的形式配置的,所以properties 配置文件中会有很多的冗余的信息,比如这些:

想要解决这个问题,就可以使用 yml 配置文件的格式化了

四、yml 配置文件说明

基本语法

yml 是树形结构的配置文件,它的基础语法是"key: value".

key 和 value 之间使用英文冒号加空格的方式组成,空格不可省略 基础语法如下:

第⼀项的配置为正确的,key 也是高亮显示的. 第⼆项没有空格是错误的使用方式,同时第⼆项的 key 没有高亮显示

使用 yml 连接数据库

spring:
  datasource:
    url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8&useSSL=false
    username: root
    password: root

yml 使用进阶

配置不同数据类型及 null

# 字符串
string:
  value: Hello
# 布尔值,true或false
boolean:
  value: true
  value1: false
# 整数
int:
  value: 10
# 浮点数
float:
  value: 3.14159
# Null,~代表null
null:
  value: ~
# "" 空字符串
#, 直接后⾯什么都不加就可以了, 但这种⽅式不直观, 更多的表⽰是使⽤引号括起来
empty:
  value: ''  

创建数据库时,密码如果设置为纯数字,比如1234,密码需要用单引号或双引号括起来 

yml 配置读取

yml 读取配置的方式和 properties 相同,使用 @Value 注解即可

yml:
  value: java
package com.example.demo;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YmlController {
    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    public String username;

    @Value("${yml.value}")
    public String ymlValue;

    @PostConstruct
    public void readValue() {
        System.out.println(url);
        System.out.println(username);
        System.out.println(ymlValue);
    }
}

properties 转 yml,把 . 改成 \n ;yml 转 properties 把 :\n 改成 .

注意事项: value 值加单双引号

字符串默认不用加上单引号或者双引号,如果加英文的单双引号可以表示特殊的含义

# 单双引号的区别
string:
  str1: Hello \n Spring Boot.
  str2: 'Hello \n Spring Boot.'
  str3: "Hello \n Spring Boot."
package com.example.demo;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YmlController {
    @Value("${string.str1}")
    private String str1;

    @Value("${string.str2}")
    public String str2;

    @Value("${string.str3}")
    public String str3;

    @PostConstruct
    public void readValue() {
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}

• 字符串默认不用加上单引号或者双引号。

• 单引号会转义特殊字符,使其失去特殊功能,始终是⼀个普通的字符串.

• 双引号不会转义字符串里面的特殊字符,特殊字符会表示本身的含义.

配置对象

student:
  id: 1
  name: Java
  age: 18

这个时候就不能用 @Value 来读取配置中的对象了,此时要使用另⼀个注解@ConfigurationProperties 来读取

package com.example.demo.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Data
@Configuration
@ConfigurationProperties(prefix = "student")
public class StudentConfig {
    private Integer id;
    private String name;
    private Integer age;
}
package com.example.demo;

import com.example.demo.config.StudentConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class YmlController {
    @Autowired
    public StudentConfig studentConfig;

    @RequestMapping("/readObject")
    public String readObject() {
        return studentConfig.toString();
    }
}

配置集合

配置文件也可以配置 list 集合

student:
  id: 1
  name: Java
  age: 18
  dbtypes:
    - mysql
    - sqlserver
    - oracle
package com.example.demo.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Data
@Configuration
@ConfigurationProperties(prefix = "student")
public class StudentConfig {
    private Integer id;
    private String name;
    private Integer age;
    private List<String> dbtype;
}

集合的读取和对象⼀样,也是使用 @ConfigurationProperties 来读取的

配置 Map

student:
  id: 1
  name: Java
  age: 18
  dbtypes:
    - mysql
    - sqlserver
    - oracle
  maptypes:
  map:
    k1: kk1
    k2: kk2
    k3: kk3

Map的读取和对象⼀样,也是使用 @ConfigurationProperties 来读取的

package com.example.demo.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;

@Data
@Configuration
@ConfigurationProperties(prefix = "student")
public class StudentConfig {
    private Integer id;
    private String name;
    private Integer age;
    private List<String> dbtypes;
    private Map<String, String> map;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值