jax
jax

Reputation: 38593

Mutally exclusive bean loading

I am using spring-boot and would like to conditionally load two beans based of what profile is passed.

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

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

So basically:

If the user passed --spring.profiles.active=secured I want the Secured bean to load but not the NotSecured bean. By default it should just load the NotSecured bean.

Is this possible?

Upvotes: 2

Views: 514

Answers (2)

Richard Logwood
Richard Logwood

Reputation: 3273

You may also specify the default profile setting with this annotation explicitly:

  • @Profile("default")
  • or with a value like @Profile({"insecure","default"}

It's worth noting that any bean that does not specify a profile belongs to the default profile.

It surprised me to find that if you have several implementations for a service and one is annotated with @Primary and @Profile(...) the bean with the default profile will get injected if the profile is not configured (example configuration applications.properties: spring.profiles.active=val1,val2,...).

Said differently, when @Profile is used in any implementation, the @Primary annotation doesn't appear to be considered; and if no profile is defined, the default will be used (which could be an implementation without the @Profile annotation since that one becomes the default!).

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

Upvotes: 0

adam p
adam p

Reputation: 1224

You can use the '!' not operator, i.e. annotate the Bean/Configuration class with @Profile("!secure") and it will only be used when the 'secure' profile is not active.

Upvotes: 4

Related Questions