另一个bean在启动Profilebean之前被调用



我有一个Spring启动应用程序,我在main类中配置了多个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引导无法像您在问题中的代码片段中介绍的那样使用概要文件。

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

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

这将单独指示spring-boot查找application-local.properties(或yaml(,并将从那里解析所有属性,就像默认处理的普通application.properties一样。

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

还有一种方法可以从java代码中自动启用概要文件(使用Environment Post Processors(,但这超出了问题的范围。

尝试添加

spring.profiles.active=local

在application.properties文件中。

最新更新