詳解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)文章
SpringBoot使用@Cacheable出現(xiàn)預(yù)覽工具亂碼的解決方法
直接使用注解進(jìn)行緩存數(shù)據(jù),我們再使用工具去預(yù)覽存儲的數(shù)據(jù)時發(fā)現(xiàn)是亂碼,這是由于默認(rèn)序列化的問題,所以接下來將給大家介紹一下SpringBoot使用@Cacheable出現(xiàn)預(yù)覽工具亂碼的解決方法,需要的朋友可以參考下2023-10-10IDEA安裝阿里巴巴編碼規(guī)范插件的兩種方式詳解(在線安裝和離線安裝)
這篇文章主要介紹了IDEA安裝阿里巴巴編碼規(guī)范插件的兩種方式詳解(在線安裝和離線安裝),本文通過截圖給大家展示的非常詳細(xì),需要的朋友可以參考下2021-09-09Spring多線程通過@Scheduled實(shí)現(xiàn)定時任務(wù)
這篇文章主要介紹了Spring多線程通過@Scheduled實(shí)現(xiàn)定時任務(wù),@Scheduled?定時任務(wù)調(diào)度注解,是spring定時任務(wù)中最重要的,下文關(guān)于其具體介紹,需要的小伙伴可以參考一下2022-05-05Java將字符串轉(zhuǎn)化為數(shù)組的兩種方法
Java中的String類是一種特殊的字符串,它可以被用于處理字符串,Java中的String類也可以將字符串轉(zhuǎn)換為數(shù)組,下面這篇文章主要給大家介紹了關(guān)于Java將字符串轉(zhuǎn)化為數(shù)組的兩種方法,需要的朋友可以參考下2023-05-05mybatis-plus指定字段模糊查詢的實(shí)現(xiàn)方法
最近項(xiàng)目中使用springboot+mybatis-plus來實(shí)現(xiàn),所以下面這篇文章主要給大家介紹了關(guān)于mybatis-plus實(shí)現(xiàn)指定字段模糊查詢的相關(guān)資料,需要的朋友可以參考下2022-04-04Springboot項(xiàng)目啟動成功后可通過五種方式繼續(xù)執(zhí)行
本文主要介紹了Springboot項(xiàng)目啟動成功后可通過五種方式繼續(xù)執(zhí)行,主要包括CommandLineRunner接口,ApplicationRunner接口,ApplicationListener接口,@PostConstruct注解,InitalizingBean接口,感興趣的可以了解一下2023-12-12