3

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:

  1. Add @Profile({"!profile-a"}) to the top of getA method in AppConfig.

  2. 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 like host)

Thanks

Let me know if any clarification is required.

Community
  • 1
  • 1
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • 1
    why dont you create a custom annotation – bananas Nov 11 '16 at 05:00
  • Initially, I wanted the profile specific beans in a separate file. The profile will handle the events differently. (say, instead of writing to a database, it'll write to disk) – Thiyagu Nov 11 '16 at 05:06

1 Answers1

4

The Condition annotations of Spring Boot auto-configuration is a solution to constrain the bean creation.

  • @ConditionalOnBean : check specified bean classes and/or names are already contained in the BeanFactory.
  • @ConditionalOnProperty : check specified properties have a specific value

Example:

@Configuration
public class SpecificConfig{
   @Bean
   @ConditionalOnBean(A.class)
   @Primary
   public A getOtherA() {
    //return a bean of type A
   }
}
Beck Yang
  • 3,004
  • 2
  • 21
  • 26