前言
springboot常用的配置文件有yml和properties两种,当然有必要的时候也可以用xml。我个人更加喜欢用yml,所以我在这里使用yml作为例子。yml或properties配置文件可以为我们完成很多工作,我们只需要从配置文件中读取出相关的属性值用起来就行了。
读取配置文件+idea使用Slf4j记录日志
1、idea安装lombok插件(slf4j需要)
file -> settings -> plugins
查找lombok安装,然后重启idea。
2、创建一个springboot项目,引入相关依赖
<!-- 使用@ConfigurationProperties-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、修改application.yml
person:
name: Kobe Bryant
age: 18
salary: 1235478.22
car:
carName: 奔驰S3200
carBrand: 奔驰
hobbit:
- 篮球
- singing
- dancing
daughters:
k1: d1
k2: d2
birthDate: 1980/01/01
marriage: true
#时间戳统一转换
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
3、创建实体类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component //导入Spring IOC容器中管理
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
private String name;
private int age;
private double salary;
private Car car;
private List<String> hobbit;
private Map<String, Object> daughters;
private Date birthDate;
private Boolean marriage;
}
@ConfigurationProperties(prefix = "person")
将整个配置文件映射到对象中,转化为bean。
它可以和@PropertySource 标注一起使用,指定映射哪一个个配置文件。
如果我们没有指定属性文件的地址,Springboot 默认读取 application.properties/application.yml 中的属性文件名。
例如:
@PropertySource("classpath:xxx.yml")
@ConfigurationProperties(prefix = "person")
就会映射xxx.yml中以person为前缀的属性。
Car.java
import lombok.Data;
@Data
public class Car {
private String carName;
private String carBrand;
}
ps: @Data 是lombok的注解,使用该注解会在运行时自动为该实体类生成getter、setter、toString 方法。
3、创建控制类
@Slf4j
@RestController
@EnableConfigurationProperties(Person.class)
public class PropertiesController {
@Autowired
private Person person;
@RequestMapping(value="/getProperties")
public Person getProperties() {
log.info("/getProperties");
return person;
}
}
@EnableConfigurationProperties(Person.class)这句注解的作用是使ConfigurationProperties生效,把Person类注入到spring的IOC容器中。
关于EnableConfigurationProperties,在SpringBoot的注释中是这样说明的:为带有@ConfigurationProperties注解的Bean提供有效的支持。这个注解可以提供一种方便的方式来将带有@ConfigurationProperties注解的类注入为Spring容器的Bean。
4、测试
输出配置文件内容
INFO级别日志