我使用的是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
,我希望加载Secured bean,但不希望加载NotSecured bean。默认情况下,它应该只加载NotSecured bean。
这可能吗?
您可以使用'!'而不是运算符,即用@Profile("!secure")
注释Bean/Configuration类,并且它仅在"安全"配置文件未处于活动状态时使用。
您也可以使用此注释显式指定默认配置文件设置:
@Profile("default")
- 或具有类似
@Profile({"insecure","default"}
的值
值得注意的是,任何不指定概要文件的bean都属于默认概要文件。
我惊讶地发现,如果一个服务有多个实现,其中一个用@Primary
和@Profile(...)
注释,那么如果配置文件未被配置,则带有默认配置文件的bean将被注入(示例配置applications.properties
:spring.profiles.active=val1,val2,...
)。
换句话说,当在任何实现中使用@Profile
时,似乎不考虑@Primary
注释;如果没有定义概要文件,则将使用默认(这可能是一个没有@Profile
注释的实现,因为该注释将成为默认注释!)。
<!-- Tested for -->
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>