Dynamic Bean configuration & loading in spring boot


I am following this link for understanding hexagonal architecture with spring boot. The infrastructure section contains the configuration for the service bean and the repository is passed as a parameter as a below method.


@ComponentScan(basePackageClasses = HexagonalApplication.class)
public class BeanConfiguration {

      BankAccountService bankAccountService(BankAccountRepository repository) {
          return new BankAccountService(repository, repository);

I am not using JPA instead using Spring JDBC for interacting to DB. Linked tutorial is using JPA.

Lets say I have different database implementations i.e.. postgresql(BankAccountRepository) and db2(BankAccountDB2Rep) . I want to change the beans without touching the code. something like with yml configuration or something which I can maintain separately instead of touching the code.


public class BankAccountRepository implements LoadAccountPort, SaveAccountPort {

      private SpringDataBankAccountRepository repository;

      // Constructor

      public Optional<BankAccount> load(Long id) {
          return repository.findById(id);

      public void save(BankAccount bankAccount) {

How can I achieve the same in spring boot? Any help is appreciated..


As mentioned by @M.Deinum in comments, the issue can be resolved by using the spring conditional beans, as below

    havingValue = "true", 
    matchIfMissing = true)
class CrossCuttingConcernModule {

More information can be found here

Answered By – Hard Coder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published