Is it possible to prevent the creation of a bean of type A
if it could be generated as a primary bean
Example:
I have two configuration classes and have two profiles.
AppConfig.java: (The generic configuration class having all beans)
@Configuration
public class AppConfig {
@Value("${host}")
private String host;
@Bean
public A getA() {
//uses the 'host' value to create an object of type A
// Involves database connections
}
@Bean
public B getB(A a) { //Others using bean A. This might come from either getA() or getOtherA()
...
}
}
SpecificConfig.java: (These beans will be created only if profile-a
is active)
@Configuration
@Profile("profile-a")
public class SpecificConfig{
@Bean
@Primary
public A getOtherA() {
//return a bean of type A
}
}
Here when profile-a
is chosen, the bean of type A
will come from SpecificConfig.java
. But the problem is when profile-a is active the parameter host
in AppConfig.java is not available and hence getA method in AppConfig throws an exception.
Since bean of type A is already there or will be there (I'm not sure of the order of bean creation), I don't want the getA() in AppConfig to be executed. (when profile-a is active)
Is there a way to achieve this?
Possible solutions:
Add
@Profile({"!profile-a"})
to the top of getA method in AppConfig.Add if checks to see if host param exists.
I don't want to do the above two as I would have to change in multiple places. (There are a bunch of other beans like
A
and other params likehost
)
Thanks
Let me know if any clarification is required.