Spring注解驱动开发之八——@Value属性赋值、@PropertySource 加载外部配置文件
本文包含以下内容:
建立新的配置类
建立新的测试方法
通过@Value 进行赋值
通过@PropertySource 加载配置文件,并进行注入
拓展@Value 、@PropertySource
1.建立新的配置类
public class MainConfigOfPropertyValues {public Person person(){return new Person();}}
2.建立新的测试方法
public class IOCTest_PropertyValue {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);@Testpublic 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);}}}
3.通过@Value 进行赋值
<bean id="person" class="com.atguigu.bean.Person" scope="prototype" ><property name="age" value="18"></property><property name="name" value="zhangsan"></property></bean>
("张三")private String name;
private Integer age;
private String nickName;
4.通过@PropertySource 加载配置文件,并进行注入
<context:property-placeholder location="classpath:person.properties"/>
person.nickName=小李四
ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty("person.nickName");System.out.println(property);
5.拓展@Value 、@PropertySource
@Value 静态变量赋值
在处理静态变量时候,使用上面的@Value的用法是无法获取到配置文件中的数据的,只能获取到null,所以要进行如下更改。
@PropertySource注解的地址可以是以下两种:
classpath路径:"classpath:/com/myco/app.properties"
文件对应路径:"file:/path/to/file"
-END-
可以关注我的公众号,免费获取价值1980元学习资料
点击“在看”,学多少都不会忘~
本文分享自微信公众号 - 阿聪的全栈之路(gh_ffab7c84fb0c)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。




