5

I have a Spring-boot app that writes to database using spring-data and jpa. It has a configuration class annotated with @EnableJpaRepositories and @EnabledTransactionManagement which wires up the data sources and other bits:

@Configuration
@EnableJpaRepositories( entityManagerFactoryRef=..., transactionManagerRef=..., ... )
@EnableTransactionManagement
public class DatasourceConfiguration {

  @Bean(destroyMethod = "close")
  @Primary
  @ConfigurationProperties("db.pooling")
  ComboPooledDataSource pooledDataSource() {
    return new ComboPooledDataSource();
  } 
  // etc
}

Now I want to update my app so that it will instead log its transactions using a different methodology (writing to Kafka, not important.) If this other methodology is disabled, however, I want it to fall back on the original direct-to-database logic.

I attempted using the @ConditionalOnProperty annotation, because the javadoc indicates that it can annotate a @Configuration class:

@ConditionalOnProperty(prefix="kafka.logging", name="enabled", havingValue = "false", matchIfMissing = true)
@Configuration
@EnableJpaRepositories( ... )
@EnableTransactionManagement
public class DatasourceConfiguration { 

However the @EnableJpaRepositories and @EnableTransactionManagement do not honor the conditional annotation. (Which is to say, it fails on startup because Spring can't find any configured data sources.)

How can I only enable Spring data and JPA iff this property is missing or set to false?

(Please don't suggest using profiles. I can't use profiles. It's a policy thing, not a choice thing.)

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
  • The syntax you are using is correct with Spring Boot. Besides, the configuration is Active even if the property kafka.logging.enabled is not set. To be sure, you can start your application with --debug option, so that Spring Boot displays all the Beans that were retained or rejected, including yours (dataSourceConfiguration) – HL'REB Feb 17 '18 at 03:40
  • `@ConditionalOnProperty` works with your configuration, it does disable `@EnableJpaRepositories`'s custom `entityManagerFactoryRef` & `transactionManagerRef` when `kafka.logging.enabled=true`, but be aware that when the `@Configuration` class is disabled with `@ConditionalOnProperty`, beans in that class will be ignored as well. Is this the reason of absent data source in your case? Do you always need `ComboPooledDataSource`? Regardless of the `kafka` config condition? If so try putting the bean in a separate config class than the conditional annotated one – buræquete Sep 30 '19 at 23:36

1 Answers1

2

If you want to tell JPA not to create the repository bean, you can put the @ Conditional on the Repository interface ranther than on the configuration class.

Then the RepositoryComponentProvider will obey your setting.