詳解Spring注解驅(qū)動開發(fā)之屬性賦值
一、@Value注解
在Person的屬性上使用@Value注解指定注入值
public class Person {
@Value("#{20-2}") //SpEL表達(dá)式 #{}
private Integer id;
@Value("張三") //基本數(shù)據(jù)類型
private String name;
}
配置類
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
測試
@Test
public void testValues(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames){
System.out.println(beanName);
}
Person person = (Person) context.getBean("person");
System.out.println(person);
}
輸出結(jié)果:

二、@PropertySource加載外部配置文件
配置類加上@PropertySource注解,引入外部配置文件
@PropertySource({"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
使用${屬性值}注入屬性值
public class Person {
@Value("#{20-2}") //SpEL表達(dá)式 #{}
private Integer id;
@Value("張三") //基本數(shù)據(jù)類型
private String name;
@Value("${person.age}") //使用外部配置文件注入屬性值
private Integer age;
}
輸出結(jié)果:

因?yàn)榕渲梦募械闹的J(rèn)都加載到環(huán)境變量中,所有還可以通過環(huán)境變量來獲取配置文件中的值
@Test
public void testValues(){
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames){
System.out.println(beanName);
}
Person person = (Person) context.getBean("person");
System.out.println(person);
Environment environment = context.getEnvironment();
String age = environment.getProperty("person.age");
System.out.println("age = " + age);
}
輸出結(jié)果:

到此這篇關(guān)于詳解Spring注解驅(qū)動開發(fā)實(shí)現(xiàn)屬性賦值的文章就介紹到這了,更多相關(guān)Spring注解驅(qū)動開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis自定義typeHandler的完整實(shí)例
這篇文章主要給大家介紹了關(guān)于MyBatis自定義typeHandler的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用MyBatis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
MyBatis使用resultMap如何解決列名和屬性名不一致
這篇文章主要介紹了MyBatis使用resultMap如何解決列名和屬性名不一致的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
java中char對應(yīng)的ASCII碼的轉(zhuǎn)化操作
這篇文章主要介紹了java中char對應(yīng)的ASCII碼的轉(zhuǎn)化操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Spring中@RabbitHandler和@RabbitListener的區(qū)別詳析
@RabbitHandler是用于處理消息的方法注解,它與@RabbitListener注解一起使用,這篇文章主要給大家介紹了關(guān)于Spring中@RabbitHandler和@RabbitListener區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-02-02
Mybatis-Plus中使用@DS注解動態(tài)選擇數(shù)據(jù)源的源碼解讀
這篇文章主要介紹了Mybatis-Plus中使用@DS注解動態(tài)選擇數(shù)據(jù)源的源碼解讀,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
SpringBoot實(shí)現(xiàn)Tomcat集群的會話管理功能
在使用 Tomcat 集群時(shí),由于每個 Tomcat 實(shí)例的 Session 存儲是獨(dú)立的,導(dǎo)致無法實(shí)現(xiàn) Session 的共享,這可能影響到用戶跨節(jié)點(diǎn)的訪問,為了實(shí)現(xiàn)跨 Tomcat 實(shí)例共享 Session,可以使用 Spring Session 配合 Redis 進(jìn)行集中式會話管理,需要的朋友可以參考下2024-12-12

