我们的运维人员希望在应用程序启动时将Spring启动配置(即所有属性)转储到日志文件中。我假设这可以通过用注解@ConfigurationProperties注入属性并打印它们来完成。
问题是,是否有更好的或内置的机制来实现这一点。
考虑到似乎没有内置的解决方案,除此之外,我正在尝试自己做饭。这是我想出来的:
@Component
public class ConfigurationDumper {
@Autowired
public void init(Environment env){
log.info("{}",env);
}
}这样做的挑战是它不会打印我的application.yml中的变量。相反,下面是我得到的结果:
StandardServletEnvironment
{
activeProfiles=[],
defaultProfiles=[default],
propertySources=[
servletConfigInitParams,
servletContextInitParams,
systemProperties,
systemEnvironment,
random,
applicationConfig: [classpath: /application.yml]
]
}如何修复此问题,以便加载并打印所有属性?
发布于 2015-11-20 02:39:38
如果您使用actuator,env endpoint将为您提供在ConfigurableEnvironment中设置的所有配置属性,而configprops将为您提供@ConfigurationProperties列表,但不在日志中。
看一下这个env端点的source code,它可能会让您了解如何获得您感兴趣的所有属性。
发布于 2015-11-20 18:20:11
没有内置机制,这实际上取决于你所说的“所有属性”是什么意思。你是只想要你写的实际密钥,还是想要所有属性(包括默认值)。
对于前者,您可以很容易地侦听ApplicationEnvironmentPreparedEvent并记录您感兴趣的属性来源。对于后者,/configprops确实是一个更好/更完整的输出。
发布于 2020-09-08 15:11:25
这只记录配置的属性*.properties文件。
/**
* maps given property names to its origin
* @return a map where key is property name and value the origin
*/
public Map<String, String> fromWhere() {
final Map<String, String> mapToLog = new HashMap<>();
final MutablePropertySources propertySources = env.getPropertySources();
final Iterator<?> it = propertySources.iterator();
while (it.hasNext()) {
final Object object = it.next();
if (object instanceof MapPropertySource) {
MapPropertySource propertySource = (MapPropertySource) object;
String propertySourceName = propertySource.getName();
if (propertySourceName.contains("properties")) {
Map<String, Object> sourceMap = propertySource.getSource();
for (String key : sourceMap.keySet()) {
final String envValue = env.getProperty(key);
String env2Val = System.getProperty(key);
String source = propertySource.getName().contains("file:") ? "FILE" : "JAR";
if (envValue.equals(env2Val)) {
source = "ENV";
}
mapToLog.putIfAbsent(key, source);
}
}
}
}
return mapToLog;
}我的示例输出描述了属性名称、值以及它的来源。我的属性值描述了它们的来源:
myprop: fooFromJar from JAR
aPropFromFile: fromExternalConfFile from FILE
mypropEnv: here from vm arg from ENVhttps://stackoverflow.com/questions/33811234
复制相似问题