Skip to content
Advertisement

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.

Configuration

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

      @Bean
      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.

BankAccountRepository.java

@Component
public class BankAccountRepository implements LoadAccountPort, SaveAccountPort {

      private SpringDataBankAccountRepository repository;

      // Constructor

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

      @Override
      public void save(BankAccount bankAccount) {
          repository.save(bankAccount);
      }
}

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

Advertisement

Answer

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

@Configuration
@ConditionalOnProperty(
    value="module.enabled", 
    havingValue = "true", 
    matchIfMissing = true)
class CrossCuttingConcernModule {
  ...
}

More information can be found here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement