我正在开发一个spring引导项目,其中传递了许多VM参数,以便应用程序启动,例如cert位置、特定的配置文件类型(不是dev、qa、prod等)。
我正在移动default.yml文件中的所有配置。
问题陈述
default.yml中设置的属性仅可访问spring上下文的环境接口,即org.springframework.core.env.Environment,而属性不会自动/默认设置为。
我是通过一个listner ServletContextListener在contextInitialized.方法中设置系统中的属性
但我不想使用environment .getProperty(key)显式地调用所有属性的名称,而是希望将spring上下文中可用的所有属性循环/不循环设置到系统/环境变量中。
期望解
我正在寻找一种方法,在listner方法中,我可以将default.yml文件中定义的所有属性设置为系统属性,而不需要访问它们的名称。
下面是我目前所遵循的将从spring /default.yml提取的活动概要文件设置为system属性的方法。我不想从yml获取活动配置文件或任何属性,但希望.yml中可用的所有属性都自动设置到系统中。
Optional.ofNullable(springEnv.getActiveProfiles())
.ifPresent(activeProfiles -> Stream.of(activeProfiles).findFirst().ifPresent(activeProfile -> {
String currentProfile = System.getProperty("spring.profiles.active");
currentProfile = StringUtils.isBlank(currentProfile) ? activeProfile : currentProfile;
System.setProperty("spring.profiles.active", currentProfile);
}));发布于 2017-04-19 15:22:41
你可能会用到这样的东西:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Properties;
@Component
public class EnvTest {
final StandardEnvironment env;
@Autowired
public EnvTest(StandardEnvironment env) {
this.env = env;
}
@PostConstruct
public void setupProperties() {
for (PropertySource<?> propertySource : env.getPropertySources()) {
if (propertySource instanceof MapPropertySource) {
final String propertySourceName = propertySource.getName();
if (propertySourceName.startsWith("applicationConfig")) {
System.out.println("setting sysprops from " + propertySourceName);
final Properties sysProperties = System.getProperties();
MapPropertySource mapPropertySource = (MapPropertySource) propertySource;
for (String key : mapPropertySource.getPropertyNames()) {
Object value = mapPropertySource.getProperty(key);
System.out.println(key + " -> " + value);
sysProperties.put(key, value);
}
}
}
}
}
}当然,当它为您工作时,请删除stdout消息。
https://stackoverflow.com/questions/43360485
复制相似问题