Reputation: 1545
I have to create a bean depending of whether one of 2 possible profiles is active, or a different bean if none of that profiles is active. I have the following:
@Profile("!A & !B")
@Bean(name = "myBean")
@Autowired
public Object myBean() {
...
}
@Profile({"A", "B"})
@Bean(name = "myBean")
@Autowired
public Object myBean() {
...
}
This code is working only if no profile A or B is active. To make it work when either A or B are active, I have to switch the order of the bean declaration.
I've tried declaring the beans in different files and it seems t obe working, but I do not understand why this not.
Also I don't understand why "!A & !B"
notation seems to be working but "A | B"
doest not work so I have to use {"A", "B"}
in that case.
Could you explain why having them in the same files only works for the first bean declared and the notations concern?
Thanks
Upvotes: 0
Views: 785
Reputation: 935
you can simply test your profile expression with org.springframework.core.env.Profiles
. For example:
Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
activeProfiles.add("B");
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); //false
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true
Now to your code
1.
This code is working only if no profile A or B is active
Set<String> activeProfiles = Collections.emptySet();
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); // true
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // false
So the first bean is active.
2.
To make it work when either A or B are active, I have to switch the order of the bean declaration
no, you don't need to switch anything:
Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
System.out.println(Profiles.of("!A & !B").matches(activeProfiles::contains)); //false
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true
So the second bean will always be active.
3.
"A | B"
also works without any problem similarly to "A", "B"
:
Set<String> activeProfiles = new HashSet<>();
activeProfiles.add("A");
System.out.println(Profiles.of("A | B").matches(activeProfiles::contains)); // true
System.out.println(Profiles.of("A", "B").matches(activeProfiles::contains)); // true
Upvotes: 1