Luke
Luke

Reputation: 1306

Defining beans per multiple spring profiles

I have 3 profiles in my app called: dev, test, prod. I want to use spring profiles to customize bean injection so that for profile dev and test I will have one bean implementation and for profile prod I will have another. The question is how to achieve that. How I can setup one bean to be active within two different profiles. I tried something like this:

@Component
@Profile("dev, test")
class DevTestBean{}

but unfortunatelly spring sees it as a single profile called dev comma space test.

Upvotes: 7

Views: 12826

Answers (2)

Łukasz Kotyński
Łukasz Kotyński

Reputation: 1147

XML solution has not been placed in official documentation:

https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/#beans-definition-profiles

so for the record I will put it here:

<beans profile="dev,foo,bar">
  <!-- (...) -->
</beans>

Upvotes: 3

Jens
Jens

Reputation: 69440

You have to change to @Profile({"dev", "test"})

The value must be declared as Set. See the documentation

If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is analogous to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., , the beans element will not be parsed unless at least profile 'p1' or 'p2' has been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered or processed unless at least profile 'p1' or 'p2' has been activated.

Upvotes: 13

Related Questions