基本特征
@ConfigurationProperties
- 與@Bean結合為屬性賦值
- 與@PropertySource(只能用於properties文件)結合讀取指定文件
- 與@Validation結合,支持JSR303進行配置文件值的校驗,如@NotNull@Email等
@Value
- 為單個屬性賦值
- 支持屬性上的SpEL表達式
兩者比較
@ConfigurationProperties | @Value | |
功能 | 批量注入配置文件中的屬性 | 一個個指定 |
松散綁定 | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
復雜類型封裝 | 支持 | 不支持 |
我們用簡單的例子來說明一下。
假設在application.properties文件中這樣寫道:
1 student.name=zhangsan 2 student.age=25 3 student.class=mba 4 student.squad-leader=false 5 student.mail=zhangsan@gmail.com 6 7 student.maps.k1=aaa 8 student.maps.k2=bbb 9 student.maps.k3=ccc 10 11 student.lists=a,b,c 12 13 student.score.english=95 14 student.score.math=90
分別用上面兩種綁定屬性的方式寫兩個bean:
StudentCP類使用@ConfigurationProperties的方式來綁定屬性,相關比較內容可以看代碼上面的注釋。
1 @Component 2 // @PropertySource表示加載指定文件 3 // @PropertySource(value = {"classpath:student.properties"}) 4 @ConfigurationProperties(prefix = "student") 5 // prefiex表示指定統一前綴,下面就不用再寫了 6 @Validated // ConfigurationProperties形式下支持JSR303校驗 7 public class StudentCP { 8 9 private String name; 10 11 private Integer age; 12 13 // 支持松散綁定,可以將連接符轉成駝峰命名 14 private Boolean squadLeader; 15 16 // 當前形式下支持JSR303數據校驗,表示此屬性值必須是email的格式 17 @Email 18 private String mail; 19 20 // 支持復雜類型封裝對應 21 private Map<String, Object> maps; 22 23 private List<Object> lists; 24 25 private Score score; 26 27 }
StudentV類使用@Value的方式來綁定屬性,注釋中給出了簡單的說明。
1 public class StudentV { 2 3 // 使用@Value的話只能給屬性一一指定映射 4 5 @Value("student.name") 6 private String name; 7 8 // @Value形式支持SpEL表達式 9 @Value("#{13*2}") 10 // @Value("student.age") 11 private Integer age; 12 13 // @Value("true") // 可直接賦值 14 // 不能支持松散語法的綁定 15 @Value("student.squad-leader") 16 private Boolean squadLeader; 17 18 @Value("student.mail") 19 private String mail; 20 21 // 之后的map、list和對象等復雜形式對象@Value無法支持 22 23 }
小結
配置文件格式是yml或者properties兩者都能夠獲取值;
如果說只想在某個業務邏輯中獲取一下配置文件中的某個值,使用@Value;
如果說專門編寫一個JavaBean來和配置文件進行映射,那么就使用@ConfigurationProperties.
其他
@ConfigurationProperties默認從全局配置文件中獲取值,如果要從指定配置文件中獲取值,那么需要通過@PropertySource來聲明指定。
@PropertySource(value = "classpath:student.properties")
@ImportResource:導入Spring的配置文件,讓配置文件里面的內容生效。
我們自定義的配置文件,默認是不能注入(加載)到Spring的IoC容器中的,如果想在項目中使用自定義的配置文件,則需要通過@ImportResource來指定注入才能夠最終使用。
@ImportResource(location = {"classpath:my-beans.xml"})
以前的項目中,我們都在xml中配置bean,但是實際當中(目前),我們不會使用這種方式來給項目添加組件,SpringBoot有推薦的方式,即使用注解。
@Configuration標注一個類,指明當前類是一個配置類,就是用來替代之前Spring使用xml配置的方式。(<bean id="" class=""></bean>)
1 @Configuration 2 public class MyConfig { 3 4 /** 5 * 將方法的返回值注入到容器中,容器中這個組件默認的id就是方法名 6 */ 7 @Bean 8 public HelloService helloService() { 9 return new HelloService(); 10 } 11 }
配置文件占位符
可以在***.properties中使用占位符使用一些函數,或者調用之前配置的一些內容:
1 ${ramdom.value} 2 ${random.int(10)} 3 ${student.name} 4 // 獲取student.hobit的值,沒有的話取冒號后面的缺省值 5 ${student.hobit:football}