java – Making a defined spring bean primary

java – Making a defined spring bean primary

A straightforward approach is to use a bridge configuration, which will register the desired bean as a new primary bean. A simple example:

The interface:

public interface Greeter { String greet(); }

The configuration which you dont control:

@Configuration
public class Config1 {
    @Bean public Greeter british(){ return () -> Hi; }
    @Bean public Greeter obiWan(){ return () -> Hello there; }
    @Bean public Greeter american(){ return () -> Howdy; }
}

The bridge configuration:

@Configuration
public class Config2 {
    @Primary @Bean public Greeter primary(@Qualifier(obiWan) Greeter g) { 
        return g; 
    }
}

The client code:

@RestController
public class ControllerImpl {
    @Autowired
    Greeter greeter;

    @RequestMapping(path = /test, method = RequestMethod.GET)
    public String test() {
        return greeter.greet();
    }
}

Result of curl http://localhost:8080/test will be

Hello there

You can use @Qualifier(___beanName__) annotation to choose the correct one

java – Making a defined spring bean primary

I tried @jihor solutions but it doesnt work. I have a NullPointerException in defined configuration.

Then I find the next solution on Spring Boot

@Configuration
public class Config1 {
    @Bean
    @ConfigurationProperties(prefix = spring.datasource.ddbb)
    public JndiPropertyHolder ddbbProperties() {
        return new JndiPropertyHolder();
    }

    @ConditionalOnProperty(name = spring.datasource.ddbb.primary, matchIfMissing = false, havingValue = true)
    @Bean(ddbbDataSource)
    @Primary
    public DataSource ddbbDataSourcePrimary() {
        return new JndiDataSourceLookup().getDataSource(ddbbProperties().getJndiName());
    }

    @ConditionalOnProperty(name = spring.datasource.ddbb.primary, matchIfMissing = true, havingValue = false)
    @Bean(ddbbDataSource)
    public DataSource ddbbDataSource() {
        return new JndiDataSourceLookup().getDataSource(ddbbProperties().getJndiName());
    }
}

And my application.properties if I need this datasource as primary, otherwise dont set the property or set false.

spring.datasource.ddbb.primary=true

Leave a Reply

Your email address will not be published. Required fields are marked *