From what I understand, what you want to do is be capable of replacing some of your beans with some stub/mock beans for specific profiles. There are 2 ways to address this:
- Exclude the not needed beans for the corresponding profiles and include by default everything else
- Include only the required beans for each profile
The first option is feasible but difficult. This is because the default behaviour of Spring when providing multiple profiles in @Profile
annotation is an OR
condition (not an AND
as you would need in your case). This behaviour of Spring is the more intuitive, because ideally each profile should correspond to each configuration of your application (production, unit testing, integration testing etc.), so only one profile should be active at each time. This is the reason OR makes more sense than AND
between profiles. As a result of this, you can work around this limitation, probably by nesting profiles, but you would make your configuration very complex and less maintainable.
Thus, I suggest you go with the second approach. Have a single profile for each configuration of your application. All the beans that are the same for every configuration can reside in a class that will have no @Profile
specified. As a result, these beans will be instantiated by all the profiles. For the remaining beans that should be distinct for each different configuration, you should create a separate @Configuration
class (for each Spring profile), having all of them with the @Profile
set to the corresponding profile. This way, it will be really easy to tract what is injected in every case.
This should be like below:
@Profile("dev")
public class MockImp implements MyInterface {...}
@Profile("prof1")
public class MockImp implements MyInterface {...}
@Profile("prof2")
public class MockImp implements MyInterface {...}
@Profile("the-last-profile") //you should define an additional profile, not rely on excluding as described before
public class RealImp implements MyInterface {...}
Last, @Primary
annotation is used to override an existing beans. When there are 2 beans with the same type, if there is no @Primary
annotation, you will get an instantiation error from Spring. If you define a @Primary
annotation for one of the beans, there will be no error and this bean will be injected everywhere this type is required (the other one will be ignored). As you see, this is only useful if you have a single Profile. Otherwise, this will also become complicated as the first choice.
TL;DR: Yes you can. For each type, define one bean for each profile and add a @Profile
annotation with only this profile.
RealImp
with@Profile("Production")
simply ?