小编典典

如何在Spring Boot应用程序中记录活动配置?

spring-boot

我真的很想在Spring
Boot中使用YAML配置,因为我发现使用单个文件显示在我的不同配置文件中处于活动状态的属性非常可读且有用。不幸的是,我发现在其中设置属性application.yml可能非常脆弱。

使用制表符代替空格之类的事情将导致属性不存在(据我所知没有警告),并且由于YAML的一些未知问题,我经常发现我的活动配置文件未设置。

所以我想知道是否有任何挂钩可以让我掌握当前活动的配置文件和属性,以便我可以对其进行记录。

同样,如果application.yml包含错误,是否有办法导致启动失败?这或者是我自己验证YAML的一种方式,这样我就可以取消启动过程。


阅读 373

收藏
2020-05-30

共2个答案

小编典典

我遇到了同样的问题,并希望有一个调试标志来告诉配置文件处理系统吐出一些有用的日志记录。一种可行的方法是为您的应用程序上下文注册一个事件侦听器,并从环境中打印出配置文件。我自己没有尝试过这样做,所以您的行程可能会有所不同。我认为也许像这里概述的那样:

然后,您将在监听器中执行以下操作:

System.out.println("Active profiles: " + Arrays.toString(ctxt.getEnvironment().getActiveProfiles()));

也许值得尝试一下。您可能执行的另一种方法是在要打印配置文件的代码中声明要注入的环境。即:

@Component
public class SomeClass {
  @Autowired
  private Environment env;
  ...
  private void dumpProfiles() {
    // Print whatever needed from env here
  }
}
2020-05-30
小编典典

Actuator / env服务显示属性,但不显示哪个属性值实际上是活动的。很多时候,您可能想覆盖您的应用程序属性

  • 特定于配置文件的应用程序属性
  • 命令行参数
  • 操作系统环境变量

因此,您将在多个来源中具有相同的属性和不同的值。

下面的代码段在启动时显示活动的应用程序属性值:

@Configuration
public class PropertiesLogger {
    private static final Logger log = LoggerFactory.getLogger(PropertiesLogger.class);

    @Autowired
    private AbstractEnvironment environment;

    @PostConstruct
    public void printProperties() {

        log.info("**** APPLICATION PROPERTIES SOURCES ****");

        Set<String> properties = new TreeSet<>();
        for (PropertiesPropertySource p : findPropertiesPropertySources()) {
            log.info(p.toString());
            properties.addAll(Arrays.asList(p.getPropertyNames()));
        }

        log.info("**** APPLICATION PROPERTIES VALUES ****");
        print(properties);

    }

    private List<PropertiesPropertySource> findPropertiesPropertySources() {
        List<PropertiesPropertySource> propertiesPropertySources = new LinkedList<>();
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource instanceof PropertiesPropertySource) {
                propertiesPropertySources.add((PropertiesPropertySource) propertySource);
            }
        }
        return propertiesPropertySources;
    }

    private void print(Set<String> properties) {
        for (String propertyName : properties) {
            log.info("{}={}", propertyName, environment.getProperty(propertyName));
        }
    }

}
2020-10-14