【问题标题】:get name of the file loaded by @PropertySource获取@PropertySource 加载的文件名
【发布时间】:2016-03-29 19:13:58
【问题描述】:

无论如何我可以在我的程序中知道通过Spring的@PropertySource注解加载的文件的完整路径。 我需要它显示在日志中,以便知道应用程序中正在使用哪个属性文件

【问题讨论】:

    标签: java spring properties


    【解决方案1】:

    在当前 ('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]'

    【讨论】:

      【解决方案2】:

      以下似乎工作正常,但我不确定实例是否始终为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声明写在哪里?
      • 这可以在ApplicationListener的实现类中,所以在上下文初始化后会被记录
      • 酷。很高兴知道。感谢您的解决方案。 +1
      【解决方案3】:

      StandardServletEnvironment 已记录此信息。您可以将 org.springframework.web.context.support.StandardServletEnvironment 类的日志级别设置为 DEBUG 以在日志中显示详细信息。

      如果您使用 spring-boot,您可以简单地将以下行添加到您的 application.properties 文件中。

      logging.level.org.springframework.web.context.support.StandardServletEnvironment = DEBUG
      

      【讨论】:

      • 我们真的需要spring-boot吗?我们可以有log4j.logger.org.springframework.core.env.MutablePropertySources=DEBUG
      • 该类自带spring-web,所以如果你在项目中至少使用了spring-web,并适当设置了你的logger配置,让这个类的DEBUG日志推送到log appender中,你理论上不需要spring-boot。
      • 我的通知只是作为一个例子,如果你使用 spring-boot,你可以如何配置你的记录器。但解决方案不依赖于spring-boot
      猜你喜欢
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2011-01-20
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多