How to log the active configuration in a Spring Boot application?

前端 未结 5 1514
野性不改
野性不改 2020-12-14 15:51

I would really like to use YAML config for Spring Boot, as I find it quite readable and useful to have a single file showing what properties are active in my different profi

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 16:37

    In case you want to get the active profiles before initializing the beans/application, the only way I found is registering a custom Banner in your SpringBootServletInitializer/SpringApplication (i.e. ApplicationWebXml in a JHipster application).

    e.g.

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder)
    {
        // set a default to use when no profile is configured.
        DefaultProfileUtil.addDefaultProfile(builder.application());
        return builder.sources(MyApp.class).banner(this::printBanner);
    }
    
    /** Custom 'banner' to obtain early access to the Spring configuration to validate and debug it. */
    private void printBanner(Environment env, Class sourceClass, PrintStream out)
    {
        if (env.getProperty("spring.datasource.url") == null)
        {
            throw new RuntimeException(
                "'spring.datasource.url' is not configured! Check your configuration files and the value of 'spring.profiles.active' in your launcher.");
        }
        ...
    }
    

提交回复
热议问题