import
com.alibaba.dubbo.common.utils.ConfigUtils;
import
com.ctrip.framework.apollo.Config;
import
com.ctrip.framework.apollo.ConfigService;
import
org.springframework.beans.BeansException;
import
org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import
java.util.Properties;
import
java.util.Set;
/**
* 处理apollo配置
*/
public
class
ApolloConfigurer
extends
PropertyPlaceholderConfigurer {
static
final
String[] NAMESPACES = {
"PUBLIC"
,
"REDIS"
,
"ZOOKEEPER"
,
"application"
};
@Override
protected
void
processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws
BeansException {
try
{
this
.reloadProperties(props);
}
catch
(Exception e) {
e.printStackTrace();
logger.info(
"获取apollo配置失败"
);
}
ConfigUtils.addProperties(props);
super
.processProperties(beanFactoryToProcess, props);
}
private
void
reloadProperties(Properties props) {
for
(String namespace : NAMESPACES) {
Config config = ConfigService.getConfig(namespace);
Set<String> fieldNames = config.getPropertyNames();
for
(String attributeName : fieldNames) {
props.put(attributeName, config.getProperty(attributeName,
""
));
System.setProperty(attributeName, config.getProperty(attributeName,
""
));
}
}
}
@Override
protected
String resolvePlaceholder(String placeholder, Properties props) {
this
.reloadProperties(props);
return
props.getProperty(placeholder);
}
}