75

In my application I use several profiles to make certain beans eligible for autowiring. What I'm missing is the possibility to make a bean eligible for autowiring when a certain profile is NOT active.

The best way of doing it that I thought about is like this:

  1. Let's suppose we have a list of all possible profiles, e.g. {A, B, C, D}.
  2. Profiles active for particular execution are {A, C}.
  3. What I do is I create artificial profiles for all possible profiles which are not active. In the example case I would create {not_B, not_D} profiles.
  4. The beans I want to be active based on not active profile X I make active for profile not_X. In my case if I wanted a bean to be eligible for autowiring when profile B is not active, I would annotate them @Profile("not_B")

This solution however requires an up-front knowledge about all possible profiles.

Can you think of any better solution?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
ShyJ
  • 4,560
  • 1
  • 19
  • 19

1 Answers1

111

You can use a not (!) operator... but you have to use Spring 3.2 M1.

The following syntax is now supported

<beans profile="A,!B">

@Profile({"A", "!B"})

indicating that the element or annotated component should be processed only if profile 'A' is active or profile 'B' is not active.

See change announced here: Spring Framework 3.2 M1 Released
The commit is at GitHub: Support not (!) operator for profile selection
Issue in JIRA: SPR-8728

If upgrading to Spring 3.2 is not possible for your project, I would recommend not using the @Profile approach and ensuring that the bean is not created in your Spring configuration.

Stefan Haberl
  • 9,812
  • 7
  • 72
  • 81
aweigold
  • 6,532
  • 2
  • 32
  • 46
  • This would be great, but Spring 3.2 is in RC1 right now, so it's not an option for me. – ShyJ Nov 26 '12 at 23:58
  • See my change to the post. I would recommend not initialising with @Profile then and handle this in Spring configuration. – aweigold Nov 27 '12 at 00:01
  • @Shyj Thought about that too (like configuring the classpath scanner with exclusion), but that just doesn't seem as nice as profiles... – ShyJ Nov 27 '12 at 00:04
  • @Shyj I absolutely agree... but the exclusion on your classpath scan is likely your best option if you are pinned to 3.1. – aweigold Nov 27 '12 at 00:05
  • @MarcoFerrari OP ([ShyJ](https://stackoverflow.com/users/1815355/shyj)) last seen Dec 21 '12 at 22:19. No matter how good this answer is, it's never gonna be accepted. =( – naXa stands with Ukraine Mar 14 '18 at 15:33
  • 2
    I was wondering whether we can do a @Profile("!default", "!test") – ashfaq Feb 19 '20 at 18:15