我有一个Spring-boot应用程序,该应用程序使用spring-data和jpa写入数据库。它具有一个用@EnableJpaRepositories@EnabledTransactionManagement注释的配置类,用于连接数据源和其他位:

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

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


现在,我想更新我的应用程序,以便它改用其他方法记录事务(写入Kafka,并不重要。)但是,如果禁用了其他方法,我希望它退回到原始的数据库逻辑。

我尝试使用@ConditionalOnProperty注释,因为javadoc指示它可以注释@Configuration类:

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


但是,@EnableJpaRepositories@EnableTransactionManagement不遵守条件注释。 (这就是说,由于Spring找不到任何已配置的数据源,因此启动失败。)

如果缺少此属性或将其设置为false,如何仅启用Spring数据和JPA?

(请不要建议使用配置文件。我不能使用配置文件。这是政策问题,而不是选择问题。)

最佳答案

如果要告诉JPA不要创建存储库Bean,可以将@ Conditional放在存储库接口上,而不是配置类上。

然后,RepositoryComponentProvider将遵循您的设置。

10-07 19:27
查看更多