如何读懂 SpringBoot 配置文件

一、配置文件类型

以前写配置五花八门,每个技术有自己的配置文件,现在SpringBoot的配置全写在一个配置文件中就行

配置文件主要有三种:

properties(默认)

server.port=8080

yml(主流)

server:

        port:8080

yaml

server:

        port:8080

* yaml和yml差不多是一回事,主要的区别在优先级

二、为什么要使用yaml数据格式

YAML 配置和传统的 properties 配置相比之下,有这些优势:

 - yaml的语法结构更加简洁明了

 - yaml 除了可以很好的配置基础数据类型之外,它还可以很方便的配置对象、集合等数据类型

三、配置文件的优先级

三种格式的配置文件是可以同时存在的

三种格式的配置文件的优先级如下:properties > yml > yaml

四、获取配置文件数据的方法

容器类获取

使用@Value注解

非容器类获取

非容器类使用@Value注入时会是NULL,此时可以采用在 启动类 中将环境注入到某个非容器类的静态属性中

非容器类如下

@Data
public class User {

    public static String name;
    public static Integer age;

}

启动类如下

import com.example.springbootdemo1.pojo.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

@SpringBootApplication
public class SpringBootDemo1Application {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(SpringBootDemo1Application.class, args);
        ConfigurableEnvironment environment = run.getEnvironment();
        String name = environment.getProperty("user.name01");
        int age = Integer.parseInt(environment.getProperty("user.age"));
        User.name=name;
        User.age=age;
        System.out.println("User.name="+User.name);
        System.out.println("User.age="+User.age);
    }

}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值