1.6 配置檔案屬性值的注入
使用Spring Boot全局配置檔案設定屬性時:
如果配置屬性是Spring Boot已有屬性,例如服務端口server.port,那麼Spring Boot内部會自動掃描并讀取這些配置檔案中的屬性值并覆寫預設屬性。
如果配置的屬性是使用者自定義屬性,例如剛剛自定義的Person實體類屬性,還必須在程式中注入這些配置屬性方可生效。
Spring Boot支援多種注入配置檔案屬性的方式,下面來介紹如何使用注解@ConfigurationProperties和@Value注入屬性
1.6.1
使用@ConfigurationProperties注入屬性
Spring Boot提供的@ConfigurationProperties注解用來快速、友善地将配置檔案中的自定義屬性值批量注入到某個Bean對象的多個對應屬性中。假設現在有一個配置檔案,如果使用@ConfigurationProperties注入配置檔案的屬性,示例代碼如下:
@Component
@ConfigurationProperties(prefix =
"person")
public class Person {
private int id;
// 屬性的setXX()方法
public void setId(int id) {
this.id = id;
}
}
上述代碼使用@Component和@ConfigurationProperties(prefix
= “person”)将配置檔案中的每個屬性映射到person類元件中。
需要注意的是,使用@ConfigurationProperties
1.6.2 使用@Value注入屬性
@Value注解是Spring架構提供的,用來讀取配置檔案中的屬性值并逐個注入到Bean對象的對應屬性中,Spring Boot架構從Spring架構中對@Value注解進行了預設繼承,是以在Spring Boot架構中還可以使用該注解讀取和注入配置檔案屬性值。使用@Value注入屬性的示例代碼如下
@Component
public class Person {
@Value("${person.id}")
private int id;
}
上述代碼中,使用@Component和@Value注入Person實體類的id屬性。其中,@Value不僅可以将配置檔案的屬性注入Person的id屬性,還可以直接給id屬性指派,這點是@ConfigurationProperties不支援的
示範@Value注解讀取并注入配置檔案屬性的使用:
(1)在com.lagou.pojo包下新建立一個實體類Student,并使用@Value注解注入屬性
@Component
public class Student {
@Value("${person.id}")
private int id;
@Value("${person.name}")
private String name; //名稱
//省略toString
}
Student類使用@Value注解将配置檔案的屬性值讀取和注入。
從上述示例代碼可以看出,使用@Value注解方式需要對每一個屬性注入設定,同時又免去了屬性的setXX()方法
(2)再次打開測試類進行測試
@Autowired
private Student student;
@Test
public void studentTest() {
System.out.println(student);
}
列印結果:
可以看出,測試方法studentTest()運作成功,同時正确列印出了Student實體類對象。需要說明的是,本示例中隻是使用@Value注解對執行個體中Student對象的普通類型屬性進行了指派示範,而@Value注解對于包含Map集合、對象以及YAML檔案格式的行内式寫法的配置檔案的屬性注入都不支援,如果指派會出現錯誤 。
這些内容,是從拉勾教育的《Java工程師高薪訓練營》裡學到的,課程内容非常全面,還有拉勾的内推大廠服務,推薦你也看看。