springboot有几种读取配置的方式
时间: 2023-05-01 12:06:43 浏览: 69
SpringBoot有两种读取配置的方式。一种是使用properties文件,另一种是使用yml文件。其中,使用properties文件可以在项目中快速配置简单属性;而使用yml文件能够更加灵活地控制配置。
相关问题
springboot有哪几种读取配置的方式
Spring Boot 有两种读取配置的方式,分别是通过 application.properties 或 application.yml 文件来读取配置信息,或者通过 @ConfigurationProperties 注解将配置信息绑定到 Java 对象上。
springboot2读取yml配置文件的几种方式
在Spring Boot 2中,可以使用以下几种方式读取YAML配置文件:
1. 通过@ConfigurationProperties注解读取YAML配置文件
@Configuration
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
private String name;
private int age;
//省略getter/setter
}
在YAML配置文件中配置:
myconfig:
name: "Tom"
age: 20
2. 通过@Value注解读取YAML配置文件
@Value("${myconfig.name}")
private String name;
@Value("${myconfig.age}")
private int age;
在YAML配置文件中配置:
myconfig:
name: "Tom"
age: 20
3. 通过Environment读取YAML配置文件
@Autowired
private Environment env;
String name = env.getProperty("myconfig.name");
int age = Integer.parseInt(env.getProperty("myconfig.age"));
在YAML配置文件中配置:
myconfig:
name: "Tom"
age: 20
以上三种方式都可以读取YAML配置文件,选择哪种方式,要根据具体的业务场景和个人喜好来决定。