當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
@value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件...
生活随笔
收集整理的這篇文章主要介紹了
@value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件...
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本文包含以下內(nèi)容:
建立新的配置類
建立新的測試方法
通過@Value 進(jìn)行賦值
通過@PropertySource? 加載配置文件,并進(jìn)行注入
拓展@Value??、@PropertySource?
1.建立新的配置類
建立新的配置類,@Configuration指定為配置類?,@Bean加載Person類,為測試做準(zhǔn)備,代碼如下:@Configurationpublic class MainConfigOfPropertyValues { @Bean public Person person(){ return new Person(); }}2.建立新的測試方法
建立測試方法,獲取并打印Person 的Beanpublic class IOCTest_PropertyValue { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class); @Test public void test01(){ printBeans(applicationContext); System.out.println("============="); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); } private void printBeans(AnnotationConfigApplicationContext applicationContext){ String[] definitionNames = applicationContext.getBeanDefinitionNames(); for (String name : definitionNames) { System.out.println(name); } }}測試類運行結(jié)果如下,可以看到默認(rèn)情況下person 這個Bean 所有的字段都為空。下面將進(jìn)行賦值3.通過@Value?進(jìn)行賦值
在xml配置文件可以通過bean 標(biāo)簽中包含property進(jìn)行屬性賦值<bean id="person" class="com.atguigu.bean.Person" scope="prototype" > <property name="age" value="18">property> <property name="name" value="zhangsan">property> bean>在注解開發(fā)中可以使用@Value ?對屬性進(jìn)行賦值。其中可以賦值1.基本數(shù)據(jù)類型@Value("張三")private String name;2.可以寫SpEL;#{}?,即sping 的表達(dá)式@Value("#{20-2}")private Integer age;3.可以寫${};取出配置文件【properties】中的值(在運行環(huán)境變量里面的值)@Value("${person.nickName}")private String nickName;運行結(jié)果如下,成功賦值4.通過@PropertySource? 加載配置文件,并進(jìn)行注入
在xml 配置文件時,可以通過context:property-placeholder標(biāo)簽,引入配置文件。<context:property-placeholder location="classpath:person.properties"/>1.在注解開發(fā)中,可使用@PropertySource 加載外部配置文件@PropertySource(value={"classpath:/person.properties"})2.創(chuàng)建屬性文件person.propertiesperson.nickName=小李四即可通過@Value + ${}獲取到配置的文件的值,或使用容器的getEnvironment()方法進(jìn)行調(diào)用getProperty("person.nickName");獲取配置文件中的內(nèi)容。ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty("person.nickName");System.out.println(property);添加測試運行結(jié)果如下:5.拓展@Value? 、@PropertySource?
@Value?靜態(tài)變量賦值
在處理靜態(tài)變量時候,使用上面的@Value的用法是無法獲取到配置文件中的數(shù)據(jù)的,只能獲取到null,所以要進(jìn)行如下更改。
@PropertySource注解的地址可以是以下兩種:
?classpath路徑:"classpath:/com/myco/app.properties"
?文件對應(yīng)路徑:"file:/path/to/file"
-END-
可以關(guān)注我的公眾號,免費獲取價值1980元學(xué)習(xí)資料
點擊“在看”,學(xué)多少都不會忘~
總結(jié)
以上是生活随笔為你收集整理的@value 静态变量_Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html实时时间代码_价值十万代码之三-
- 下一篇: python 录制网易云登陆_图说Pyt