Spring通過(guò)配置文件和注解實(shí)現(xiàn)屬性賦值
前言
在實(shí)際開(kāi)發(fā)當(dāng)中,Spring中bean的屬性直接賦值用的不是太多,整理這方面的資料,做一個(gè)小結(jié),以備后續(xù)更深入的學(xué)習(xí)。
通過(guò)配置文件的方式
以配置文件的方式啟動(dòng)spring容器時(shí),可以使用property標(biāo)簽的value給bean的屬性賦值,賦值的形式有以下幾種:
<--通過(guò)context:property-placeholder將properties文件中的值加載的環(huán)境變量中(properties中的屬性值最終是以環(huán)境變量的形式存儲(chǔ)的)><context:property-placeholder location='classpath:person.properties'/> <bean > <--①通過(guò)基本數(shù)值直接賦值--> <property name='name' value='zhangsan'></property> <--②通過(guò)${}取出配置文件中的值--> <property name='age' value='${person.age}'></property> <--③通過(guò)Spring的El表達(dá)式--> <--<property name='age' value='10*2'></property>--></bean>
classpath下的properties文件內(nèi)容
person.age=u5C0Fu674Eu56DB
通過(guò)注解的方式
使用properties的value對(duì)應(yīng)的注解給屬性賦值
//使用@PropertySource讀取外部配置文件中的k/v保存到運(yùn)行的環(huán)境變量中;加載完外部的配置文件以后使用${}取出配置文件的值@PropertySource(value={'classpath:/person.properties'})@Configurationpublic class MainConfigOfPropertyValues { @Bean public Person person(){ return new Person(); }}
public class Person { //使用@Value賦值; //1、基本數(shù)值 //2、可以寫(xiě)SpEL; #{} //3、可以寫(xiě)${};取出配置文件【properties】中的值(在運(yùn)行環(huán)境變量里面的值) @Value('張三') private String name; @Value('#{20-2}') private Integer age; /* @Value('${person.age}') private Integer age;*/}
注:
外部配置文件中的k/v保存到運(yùn)行的環(huán)境變量中,可以直接在環(huán)境變量中取出對(duì)應(yīng)的值
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty('person.age');
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. xml中的空格之完全解說(shuō)4. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問(wèn)題……5. XML入門(mén)的常見(jiàn)問(wèn)題(四)6. php bugs代碼審計(jì)基礎(chǔ)詳解7. ASP使用MySQL數(shù)據(jù)庫(kù)的方法8. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享9. WMLScript的語(yǔ)法基礎(chǔ)10. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法
