读取资源文件方法有很多种,这里只说最简单、最实用、最方便的用法,通过spring注解@Value
读取属性值,如果是SpringBoot且为.yml
文件时不建议用@Value
,建议使用@PropertySource
。
新建一个conf.properties文件
在项目resources文件下新建一个conf.properties文件
文件内容为:
testName=读取资源文件
SpringMVC
Spring配置文件(第一种)
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:conf.properties 文件路径 </value>
</list>
</property>
<property name="fileEncoding" value="utf-8" />
</bean>
Spring配置文件(第二种)
<!--加载配置文件-->
<context:property-placeholder location="classpath:conf.properties" file-encoding="UTF-8"/>
以上是两种加载资源配置,用哪种都可以
Java中获取属性
@Value("${testName}")
private String myProperty;
Spring配置文件中获取属性
<property name="driverClassName" value="${testName}"></property>
SpringBoot
SpringBoot默认加载bootstrap/application.properties/yml文件,如果配置在这个文件里面的值可以直接读取。
文件内容为:
testName=读取资源文件(properties文件)
或
testName: 读取资源文件(yml文件)
Java中获取属性
@Value("${testName}")
private String myProperty;
如果新建一个conf.properties文件,那么需要在类上和类中属性上加注释
@PropertySource(value = "classpath:conf.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
public class TestResource{
@Value("${testName}")
private String testName;
}
如果项目启动时读取不到相应值会抛异常,项目无法启动!!!
如果读取不到设置默认值:@Value("${testName}:默认值")
@PropertySource获取属性(properties文件)
在SpringBoot中如果读取资源为@Value()
形式,启动时读取不到会抛异常,项目无法启动!!!
@PropertySource
方式读取不到值为null,不会抛异常,项目正常启动
@Component
@ConfigurationProperties(prefix = "前缀")
//资源文件中内容:hello.word=helloWord
//前缀为hello
@PropertySource(value = "classpath:conf.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
public class TestResource{
private String word;
//省略get/set方法
}
@PropertySource获取属性(推荐使用)
如果用上面@PropertySource
方法获取属性,细心的小伙伴会发现,.yml
文件无法读取(除系统bootstrap.yml和application.yml文件)。感兴趣的小伙伴阅读一下源码:SpringBoot默认加载配置文件类为Properties
而加载.yml
文件类为YamlPropertiesFactoryBean
,所以通过@PropertySource
注解属性factory实现加载类。
- ignoreInvalidFields :忽略无效的属性,默认为 false;
- ignoreUnknownFields :忽略未知的属性,默认为 true;
@Component
@ConfigurationProperties(prefix = "前缀")
//资源文件中内容:
//hello:
// word: helloWord
//前缀为hello
@PropertySource(value = "classpath:conf.yml", ignoreResourceNotFound = true, encoding = "UTF-8", factory = YmlConfigurationFactory.class )
//根据环境读配置文件
//local:conf-local.yml
//dev:conf-dev.yml
@PropertySource(value = "classpath:conf-${spring.profiles.active}.yml", ignoreResourceNotFound = true, encoding = "UTF-8", factory = YmlConfigurationFactory.class )
public class TestResource{
private String wrod;
//省略get/set方法
}
public class YmlConfigurationFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = name != null ? name : resource.getResource().getFilename();
boolean existed = sourceName != null && (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml"));
if (sourceName != null &&
!resource.getResource().exists()) {
return new PropertiesPropertySource(sourceName, new Properties());
} else if (existed) {
Properties propertiesFromYaml = loadYml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}
private Properties loadYml(EncodedResource resource) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
用代码加载配置文件
用代码加载其实就是用流加载配置文件,同上步骤新建一个conf.properties文件内容不变
代码:
//用流读入properties配置文件
InputStream resourceAsStream = 所在类名.class.getClassLoader().getResourceAsStream("conf.properties");
Properties properties = new Properties();
//从输入字节流读取属性列表(键和元素对)
properties.load(resourceAsStream);
//用此属性列表中指定的键搜索属性
String testName= properties.getProperty("testName");
//假设代码所有类名为的TestProperty,需要改为:TestProperty.class.getClassLoader().getResourceAsStream("conf.properties");
这种方法可用在工具类项目加载所依赖的项目配置。
properties/yml读取实例
# 测试test.yml
user:
userName: root
isAdmin: true
regTime: 2019/11/01
isOnline: 1
maps: {k1 : v1,k2: v2}
lists:
- list1
- list2
address:
tel: 15899988899
name: 上海市
@Component
@ConfigurationProperties(prefix = "user")
@PropertySource(value = "classpath:test.yml", ignoreResourceNotFound = true, encoding = "UTF-8", factory = YmlConfigurationFactory.class )
public class TestResource {
private String userName;
private boolean isAdmin;
private Date regTime;
private Long isOnline;
private Map<String, Object> maps;
private List<Object> lists;
private Address address;
//省略get/set方法
public static Class Address {
private String tel;
private String name;
//省略get/set方法
}
}