互斥bean加载

时间:2015-03-18 00:48:40

标签: spring spring-boot

我正在使用spring-boot,并希望根据传递的配置文件有条件地加载两个bean。

@Configuration
@Profile("secure")
public class Secured ... //this should only load when "secure" is supplied

@Configuration
public class NotSecured ... //this should be the default

基本上是这样的:

如果用户通过--spring.profiles.active=secured,我希望加载安全bean但不加载NotSecured bean。默认情况下,它应该只加载NotSecured bean。

这可能吗?

2 个答案:

答案 0 :(得分:4)

你可以使用'!' not运算符,即使用@Profile("!secure")注释Bean / Configuration类,并且仅在'secure'配置文件未激活时才使用它。

答案 1 :(得分:0)

您还可以使用此注释明确指定默认配置文件设置:

  • @Profile("default")
  • 或具有类似@Profile({"insecure","default"}的值

值得注意的是,任何未指定配置文件的bean都属于默认配置文件

令我惊讶的是,如果您有一项服务的几种实现,并且用@Primary@Profile(...)进行了注释,则具有默认配置文件的bean将被注入配置文件 示例配置applications.properties spring.profiles.active=val1,val2,...)。

换句话说,在任何实现中使用@Profile时,似乎都不会考虑@Primary注释;如果未定义配置文件,则将使用 default (这可能是不带有@Profile注释的实现,因为该注释成为默认值!)。

<!-- Tested for -->
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
相关问题