Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

spring - How to conditionally declare Bean when multiple profiles are not active?

In my Spring-Boot-App I want to conditionally declare a Bean, depending on (un)loaded spring-profiles.

The conditon:

Profile "a" NOT loaded  
AND  
Profile "b" NOT loaded 

My solution so far (which works):

@Bean
@ConditionalOnExpression("#{!environment.getProperty('spring.profiles.active').contains('a') && !environment.getProperty('spring.profiles.active').contains('b')}")
    public MyBean myBean(){/*...*/}

Is there a more elegant (and shorter) way to explain this condition?
Especially I want to get rid of the usage of Spring Expression Language here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since Spring 5.1.4 (incorporated in Spring Boot 2.1.2) it is possible to use a profile expression inside profile string annotation. So:

In Spring 5.1.4 (Spring Boot 2.1.2) and above it is as easy as:

@Component
@Profile("!a & !b")
public class MyComponent {}

In Spring 4.x and 5.0.x:

There are many approaches for this Spring versions, each one of them has its pro's and con's. When there aren't many combinations to cover I personally like @Stanislav answer with the @Conditional annotation.

Other approaches can be found in this similar questions:

Spring Profile - How to include AND condition for adding 2 profiles?

Spring: How to do AND in Profiles?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...