目录
@PropertySource 加载配置文件,这个是很常用的,比如在实际开发中往往把数据库配置或其它配置写在外部文件中。
一、知识点
使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
- 多个配置文件可以适用多个@PropertySource或者适用@PropertySources
ps:现代YAML格式很流行,现在一般使用YAML,如上面的配置可以改为
@PropertySource(value={"classpath:/person.yml"})
二、例子
2.1 例1:读取外部配置文件
我在上一章《hualinux spring 4.11:@Value 属性注入》中已经讲了,这里不重复。
2.2 例2:读取配置环境中的值
在例1基础上,直接修改 com.hualinux.beans.PersonMain.java
package com.hualinux.beans;
import conf.MainConfPerson;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class PersonMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(MainConfPerson.class);
Person person= (Person) ctx.getBean("person");
System.out.println(person);
ConfigurableEnvironment environment=ctx.getEnvironment();
String property = environment.getProperty("nickName");
System.out.println(property);
ctx.close();
}
}
然后运行它,结果如下:
Person{name='阿华', age=26, nickName='hualinux'}
hualinux

本文详细介绍了如何在Spring框架中使用@PropertySource注解来读取外部配置文件,并通过实例展示了从配置环境中获取值的方法。

被折叠的 条评论
为什么被折叠?



