Spring通過配置檔案和註解實現屬性賦值
阿新 • • 發佈:2020-04-16
前言
在實際開發當中,Spring中bean的屬性直接賦值用的不是太多,整理這方面的資料,做一個小結,以備後續更深入的學習。
通過配置檔案的方式
以配置檔案的方式啟動spring容器時,可以使用property標籤的value給bean的屬性賦值,賦值的形式有以下幾種:
<--通過context:property-placeholder將properties檔案中的值載入的環境變數中(properties中的屬性值最終是以環境變數的形式儲存的)> <context:property-placeholder location="classpath:person.properties"/> <bean id="person" class="com.atneusoft.bean.Person" > <--①通過基本數值直接賦值--> <property name="name" value="zhangsan"></property> <--②通過${}取出配置檔案中的值--> <property name="age" value="${person.age}"></property> <--③通過Spring的El表示式--> <--<property name="age" value="10*2"></property>--> </bean>
classpath下的properties檔案內容
person.age=\u5C0F\u674E\u56DB
通過註解的方式
使用properties的value對應的註解給屬性賦值
//使用@PropertySource讀取外部配置檔案中的k/v儲存到執行的環境變數中;載入完外部的配置檔案以後使用${}取出配置檔案的值 @PropertySource(value={"classpath:/person.properties"}) @Configuration public class MainConfigOfPropertyValues { @Bean public Person person(){ return new Person(); } }
public class Person { //使用@Value賦值; //1、基本數值 //2、可以寫SpEL; #{} //3、可以寫${};取出配置檔案【properties】中的值(在執行環境變數裡面的值) @Value("張三") private String name; @Value("#{20-2}") private Integer age; /* @Value("${person.age}") private Integer age;*/ }
注:
外部配置檔案中的k/v儲存到執行的環境變數中,可以直接在環境變數中取出對應的值
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.age");
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。