Java 开发中,需要将一些易变的配置参数放置 properties 配置文件中。我们在使用中需要 读取参数使用,在properties 文件中存放也是key/value格式
image_host=http://192.168.22.122/
方式一:在spring的配置文件spring.xml中先找到资源文件
<!-- 使用spring自带的占位符替换功能 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 允许JVM参数覆盖
java -Djdbc.url=123 -jar xxx.jar -->
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<!-- 忽略没有找到的资源文件 -->
<property name="ignoreResourceNotFound" value="true"/>
<!-- 配置资源文件 -->
<property name="locations">
<list>
<!--<value>classpath:disconf.properties</value>-->
</list>
</property>
</bean>
在这里需要注意的一点是,我们在项目启动后,加载完这个xml后,需要添加扫描的包,这些包里面的类才能通过@Value("$()")去获取配置文件的值
@Value("${image_host}")
private String image_host;
方式二:使用托管方式的disconf配置(无代码侵入, 配置更改会自动reload)
在pom加入
<!-- disconf 2.6.31 -->
<dependency>
<groupId>com.baidu.disconf</groupId>
<artifactId>disconf-client</artifactId>
<version>2.6.31</version>
<exclusions>
<exclusion>
<artifactId>javassist</artifactId>
<groupId>org.javassist</groupId>
</exclusion>
<exclusion>
<artifactId>com.101tec</artifactId>
<groupId>zkclient</groupId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
在spring的配置文件中加入
<bean id="configproperties_disconf" class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/disconf.properties</value>
</list>
</property>
</bean>
<bean class="com.lf.utils.PropertyUtil">
<property name="ignoreResourceNotFound" value="true"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="propertiesArray">
<list>
<ref bean="configproperties_disconf"/>
</list>
</property>
</bean>
准备工具类
/**
* @program: lfmyFirst
* @description:获取配置文件
* @author: LingFeng
* @create: 2019-09-29 11:01
*/
public class PropertyUtil extends ReloadingPropertyPlaceholderConfigurer {
/**
* 配置属性对象
*/
private static Properties properties;
public synchronized static void newProperties() {
properties = new Properties();
}
//初始化配置
@Override
public void setPropertiesArray(Properties[] propertiesArray) {
super.setPropertiesArray(propertiesArray);
newProperties();
for (Properties propertiesTemp : propertiesArray) {
properties.putAll(propertiesTemp);
}
}
private static String getValueByKey(String propertiesKey, String defaultValue) {
return properties.getProperty(propertiesKey, defaultValue);
}
public static String getString(String propertiesKey) {
String value = "";
try {
value = new String(getValueByKey(propertiesKey, "").getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("getString(" + propertiesKey + ")", e);
}
return value;
}
}
读取的话可以直接调用我们的工具类获取
PropertyUtil.getString("image_host")
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
这些代码在我新的项目将使用,欢迎大家纠正改进