SpringBoot配置文件yml

SpringBoot配置文件(yml)

application.properties key = value

application.yml key: value (对空格要求严格)

heyuapplication.yml

heyuliang: waitting for me,i will find you
person:
name: 禾下凉
age: 20
happy: false
birthday: 2000/04/28
map: {k1: 长安故里,k2: 禾下凉}
list:
  - book
  - music
  - basketball
dog:
   #${person.mouse:hehe}-奶茶 表选择 person中没有mouse则默认后面的hehe
  name: ${person.mouse:hehe}-奶茶
  age: 2

cat:
C-name: 椰奶冰
age: 2

1、获取配置信息

(1)@value()(不推荐)

例: @value("${hexialiang}")

String liang;

(2)@ConfigurationProperties() 读取并绑定bean

@Component 将bean注入到类中

例: @Component //注入bean

@ConfigurationProperties(prefix="person")

class Person类{}

(3)@ConfigurationProperties() 读取并校验 (会自动进行校验,例如邮箱格式校验)

没有在类上使用@Component

要在使用该类的地方使用@EnableConfigurationProperties() 注册bean

例: @ConfigurationProperties("car")

class CarProperties{}

使用该类CarProperties的另外的一个类上(例如启动类上)

@EnableConfigurationProperties(CarProperties.class)

(4)@PropertySource() 读取指定的properties或yml文件

例:@Component //注入bean

@PropertySource("classpath:heyuapplication.yml")

class Heyu{}

 

2、SpringBoot 配置文件的优先级

 

 

 

 

3、多环境配置切换(激活配置文件)

(1)application.properties

  #springboot的多环境配置:可以选择激活哪一个配置文件
#激活application-properties
spring.profiles.active=test

(2)application-test.yml

server:
port: 8081
spring:
profiles:
  active: dev  
  #选择激活哪一个配置 此时选择的是dev
---    
server:
port: 8082
spring:
profiles:dev #版本名dev
---  
server:
port: 8083
spring:
profiles:test   #版本名test

 

 

 

posted @ 2022-04-15 21:35  与长安故里  阅读(694)  评论(0编辑  收藏  举报