假设此时有properties文件:mytest.properties
testKey=testValue
1 利用PropertyPlaceholderConfigurer
1.1 注解
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:mytest.properties" />
</bean>
如果有多个文件的话:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>mytest1.properties</value>
<value>mytest2.properties</value>
</list>
</property>
</bean>
此时可以使用@Value直接使用:
@Value("${testKey}")
String configVal;
1.2 维护到容器中
或者继承PropertyPlaceholderConfigurer,将文件内容解析后放到一个容器中:
public class TestConfigurer extends PropertyPlaceholderConfigurer {
private Map<String,Object> testPropMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
if(null == testPropMap){
testPropMap= new HashMap<>();
}
for (Object key : props.keySet()){
String keyStr = key.toString();
Object value = props.get(key);
testPropMap.put(keyStr,value);
}
}
public List<String> getCtxProp(String name) {
return encryptPropMap.get(name);
}
}
<bean id="testConfigurer " class="com.test.TestConfigurer">
<property name="location">
<value>classpath:conf/mytest.properties</value>
</property>
</bean>
此时就可以通过注入testConfigurer来获取了。
2 PropertiesFactoryBean
PropertiesFactoryBean使用上和PropertyPlaceholderConfigurer类似,仅仅是注解使用身上有些差异
<bean id="testConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:mytest.properties" />
</bean>
然后用注解:
@Value("#{$testConfig['testKey']}")
int configVal;
3 Properties与InputStream
此种方式可以动态的读取Properties文件,比如定义一个读取文件的类:
public class TestConfigurer {
public static Properties getConfig(String configPath){
InputStream inputStream = TestConfigurer .class.getResourceAsStream(configPath);
if (inputStream == null) {
return null;
}
try {
Properties properties = new Properties();
properties.load(inputStream);
return properties;
} catch (Exception e) {
throw new RuntimeException("load config error", e);
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
logger.error("close stream error", ioe);
}
}
}
}
只要传入路径就能获取到Properties实例,也就获得了文件内容.
关于getResourceAsStream是用法,可以参考一下:Java中getResourceAsStream的用法这篇博文
4 PropertiesLoaderUtils与Resource
此种方式和类似,可以动态读取文件:
Resource resource = new ClassPathResource("/myTest.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
路径
关于文件路径,如果路径以‘/’开头,则表示classpath目录下。
参考资料:
Spring获取properties文件中的属性