【问题标题】:other bean is getting called before Profile bean in boot其他 bean 在启动中的 Profile bean 之前被调用
【发布时间】:2020-03-15 19:19:58
【问题描述】:

我有一个 Spring Boot 应用程序,我在主类中配置了多个 bean,并且我还为不同的环境设置了不同的配置文件。请看下面的代码:

private static String propertiesFilePath;

    public static void main(String[] args) {
        LOGGER.info("Starting app..!!");
        SpringApplication.run(Application.class, args);
    }


    @Bean
    @Profile("local")
    public  String localBean() {
        propertiesFilePath = "application-local.properties";
        return propertiesFilePath;
    }

    @Bean
    public static CommandLineRunner init() {
        return (args) -> {
            try {
                LOGGER.info("Starting ..");
                CommonUtil.initializeCacheManager(propertiesFilePath);
                } catch (Exception e) {
                LOGGER.info("CommonUtil.initializeCacheManager :" + e.getMessage());
            }
        };

    }

    @Bean
    public BroadcastHandler createBroadcastHandler() {
        return new BroadcastHandler();
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

在这段代码中,首先调用其他 bean,然后调用带有 @Profile 注释的 bean,我可以在下面的日志中看到:

以下个人资料是active: local

由于 Spring 容器正在尝试初始化其他 bean,因此在没有先初始化属性的情况下,应用程序无法启动。

带有@Profile 的bean 没有被调用有什么原因,我该如何解决?

【问题讨论】:

    标签: spring-boot properties-file


    【解决方案1】:

    Spring boot 不适用于您在问题中的代码 sn-p 中提供的配置文件。

    它自动解析所有配置文件并加载相应的bean(使用@Profle注解):

    在运行应用程序时,将--spring.profiles.active=local 添加到执行 java 应用程序的命令中。

    仅此一项将指示 Spring Boot 查找 application-local.properties(或 yaml),并从那里解析所有属性,就像它在默认情况下处理通常的 application.properties 一样。

    默认情况下,如果您将属性文件放入src/main/resourcessrc/main/resources/config 文件夹,则会解析属性文件。

    还有一种方法可以从 java 代码(使用环境后处理器)自动启用配置文件,但这超出了问题的范围。

    【讨论】:

      【解决方案2】:

      尝试添加

      spring.profiles.active=local
      

      在您的 application.properties 文件中。

      【讨论】:

      • 我在 application.properties 文件中有这一行,这就是为什么我在日志“以下配置文件处于活动状态:本地”中得到这一行的原因
      • 您不必明确告诉您的 spring 应用程序加载 application-local.properties 文件。任何带有@Profile("local") 注释的东西肯定会从application-local.properties 中获取其配置。尝试删除 localBean 和 CommandLineRunner bean。
      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多