在Spring项目中,一般会有多个properties文件,例如数据库连接信息等,那么在Spring的配置文件和Java代码中怎么灵活的使用这些key-value形式的配置呢?
1. 新建类PropertyConfigurer继承PropertyPlaceholderConfigurer,并复写mergeProperties()方法,在该方法中调用super.mergeProperties()方法,把返回值保存至成员变量
public class PropertyConfigurer extends PropertyPlaceholderConfigurer
{
private Properties properties;
@Override
protected Properties mergeProperties() throws IOException
{
properties = super.mergeProperties();
return properties;
}
public Properties getProperties()
{
return properties;
}
}
2. 新建Config类,并使用单例模式,有一个静态成员变量propertyConfigurer
public class Config
{
private static Config config = new Config();
private static PropertyConfigurer propertyConfigurer;
private Config()
{
}
public static Config getInstance(PropertyConfigurer propertyConfigurer)
{
Config.propertyConfigurer = propertyConfigurer;
return config;
}
public static String getString(String key)
{
return propertyConfigurer.getProperties().getProperty(key);
}
public static String getString(String key, String defaultValue)
{
return propertyConfigurer.getProperties().getProperty(key, defaultValue);
}
public static int getInt(String key)
{
return Integer.valueOf(propertyConfigurer.getProperties().getProperty(key));
}
public static int getInt(String key, int defaultValue)
{
return Integer.valueOf(propertyConfigurer.getProperties().getProperty(key, String.valueOf(defaultValue)));
}
}
3. config.spring.xml配置,其中locations属性为properties文件所在路径
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="propertyConfigurer" class="com.realjt.summer.config.PropertyConfigurer"
p:fileEncoding="utf-8" p:localOverride="true">
<property name="locations">
<list>
<value>/WEB-INF/config/*.properties</value>
<value>classpath:*.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"></property>
<property name="ignoreUnresolvablePlaceholders" value="true"></property>
</bean>
<bean id="config" class="com.realjt.summer.config.Config"
factory-method="getInstance">
<constructor-arg ref="propertyConfigurer"></constructor-arg>
</bean>
</beans>
4. 配置使用
4.1 在spring.xml中通过EL表达式引用properties文件中变量,例如
<property name="url" value="${url}" />
4.2 在Java代码中通过Spring注解形式引用properties文件中变量,例如
@Value("${url}")
private String url;
4.3 直接使用Config类静态方法,例如
Config.getString("url");