一、配置文件类型
以前写配置五花八门,每个技术有自己的配置文件,现在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);
}
}
运行结果