前言
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級別日志

