从网上找来的文章都是说通过@Value怎么注入属性值。
但是如果你有20多个属性值需要配置呢?写一串的@Value吗?
所以,就想先把属性注入到Map,再随用随取。代码如下,仅供测试
package com.xxxx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Configuration
public class Config {
@Autowired
private Environment environment;
public Properties setEnvironment() {
final Properties properties = new Properties();
((AbstractEnvironment) environment).getPropertySources().forEach(propertySource -> {
System.out.println(propertySource.getName()+", class: "+ propertySource.getClass().getName());
if(propertySource instanceof CompositePropertySource){
properties.putAll(getPropertiesInCompositePropertySource((CompositePropertySource) propertySource));
}
});
System.out.println("-----------------------------------------------------------");
properties.forEach((o, o2) -> {
System.out.println("key: "+o+", value: "+o2);
});
System.out.println("-----------------------------------------------------------");
return properties;
}
private Properties getPropertiesInCompositePropertySource(CompositePropertySource compositePropertySource){
final Properties properties = new Properties();
compositePropertySource.getPropertySources().forEach(propertySource -> {
if (propertySource instanceof MapPropertySource) {
properties.putAll(((MapPropertySource) propertySource).getSource());
}
if (propertySource instanceof CompositePropertySource)
properties.putAll(getPropertiesInCompositePropertySource((CompositePropertySource) propertySource));
});
return properties;
}
@Bean
@RefreshScope
public ConfigMap configMap(){
return new ConfigMap(setEnvironment());
}
public static class ConfigMap{
private Properties properties;
public ConfigMap(Properties properties) {
this.properties = properties;
}
public String getKey(String key){
return properties.getProperty(key);
}
public String getKeyOrDefault(String key, String defaultValue){
return properties.getOrDefault(key, defaultValue).toString();
}
public String getKeyOnRequire(String key){
if(!properties.containsKey(key)){
throw new RuntimeException("the key is not found.");
}
return getKey(key);
}
public Map<String, String> getAllConfigs(){
return new HashMap<>((Map) properties);
}
}
}
经过测试,可以动态刷新属性值。