【发布时间】:2016-03-29 19:13:58
【问题描述】:
无论如何我可以在我的程序中知道通过Spring的@PropertySource注解加载的文件的完整路径。 我需要它显示在日志中,以便知道应用程序中正在使用哪个属性文件
【问题讨论】:
标签: java spring properties
无论如何我可以在我的程序中知道通过Spring的@PropertySource注解加载的文件的完整路径。 我需要它显示在日志中,以便知道应用程序中正在使用哪个属性文件
【问题讨论】:
标签: java spring properties
在当前 ('21) 版本的 Spring Boot 中,上述两个关于日志记录级别的建议似乎都不起作用。此外 - 如果文件实际上没有加载,因为它没有找到或出于任何其他原因,无论如何都不会打印任何内容。
当我将 ROOT 记录器设置为 DEBUG(application.properties 中的 logging.level.root=DEBUG)时,我在日志文件中看到的唯一内容是正确加载文件并且 @Value 注释属性解析成功的是:
2021-07-23 11:06:10.299 调试 16776 --- [restartedMain] o.s.b.f.s.DefaultListableBeanFactory :创建共享实例 单例 bean 'bahblahService'
2021-07-23 11:06:10.302 调试 16776 --- [restartedMain] o.s.c.e.PropertySourcesPropertyResolver:找到密钥 PropertySource '类路径中的'blahblah.username' 具有字符串类型值的资源 [custom-local.properties]'
【讨论】:
以下似乎工作正常,但我不确定实例是否始终为ConfigurableEnvironment 类型
@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent>{
@Autowired
private Environment env;
private static final Logger log = LoggerFactory.getLogger(MyListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(env instanceof ConfigurableEnvironment){
MutablePropertySources propertySources = ((ConfigurableEnvironment)env).getPropertySources();
for(PropertySource ps : propertySources){
log.info(ps.getName()); //if only file based needed then check if instanceof ResourcePropertySource
}
}
}
}
编辑:真的不需要这一切。正如 Selim 已经回答的那样,启用正确的日志就可以了
log4j.logger.org.springframework.core.env.MutablePropertySources=DEBUG
【讨论】:
if声明写在哪里?
StandardServletEnvironment 已记录此信息。您可以将 org.springframework.web.context.support.StandardServletEnvironment 类的日志级别设置为 DEBUG 以在日志中显示详细信息。
如果您使用 spring-boot,您可以简单地将以下行添加到您的 application.properties 文件中。
logging.level.org.springframework.web.context.support.StandardServletEnvironment = DEBUG
【讨论】:
log4j.logger.org.springframework.core.env.MutablePropertySources=DEBUG