在java中通常会有变量,但是如果想改变变量的值,老是在程序里面改很麻烦,最方便的就是在配置文件里面改。程序直接引用就可以了。下面我就来分享一下。。。。
先在常量类里面定义
SystemParams.java
public static String COLLECTION_MUSIC_HOUR="collection_music_hour";
配置文件
config.properties
collection_music_hour=14:40
下面就是如何把变量从配置文件里面取值
MyEncryptablePropertyPlaceholderConfigurer.java
package com.chinaGPS.song.util;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.jasypt.commons.CommonUtils;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.TextEncryptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import com.chinaGPS.song.util.constant.SystemParams;
public final class MyEncryptablePropertyPlaceholderConfigurer
private final StringEncryptor stringEncryptor;
private final TextEncryptor textEncryptor;
private Map resolvedProps;//将属性保存起来
public MyEncryptablePropertyPlaceholderConfigurer(
final StringEncryptor stringEncryptor) {
super();
CommonUtils.validateNotNull(stringEncryptor, "Encryptor cannot be null");
this.stringEncryptor = stringEncryptor;
this.textEncryptor = null;
}
public MyEncryptablePropertyPlaceholderConfigurer(final TextEncryptor textEncryptor) {
super();
CommonUtils.validateNotNull(textEncryptor, "Encryptor cannot be null");
this.stringEncryptor = null;
this.textEncryptor = textEncryptor;
}
@Override
protected String convertPropertyValue(final String originalValue) {
if (!PropertyValueEncryptionUtils.isEncryptedValue(originalValue)) {
return originalValue;
}
if (this.stringEncryptor != null) {
return PropertyValueEncryptionUtils.decrypt(originalValue,
this.stringEncryptor);
}
return PropertyValueEncryptionUtils.decrypt(originalValue, this.textEncryptor);
}
@Override
protected String resolveSystemProperty(final String key) {
return convertPropertyValue(super.resolveSystemProperty(key));
}
@Override
protected void processProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
tmp=resolvePlaceholder(SystemParams.COLLECTION_MUSIC_HOUR, props);
if(StringUtils.isBlank(tmp)) {
logger.error(SystemParams.COLLECTION_MUSIC_HOUR+"解析出错");
throw new BeanInitializationException(SystemParams.COLLECTION_MUSIC_HOUR+"属性为空");
}
SystemParams.COLLECTION_MUSIC_HOUR = tmp;
}
最后就是通过spring的注入
class="com.chinaGPS.song.util.MyEncryptablePropertyPlaceholderConfigurer">
///WEB-INF/jdbc/mysql.properties
/WEB-INF/jdbc/config.properties