【发布时间】:2017-05-04 22:36:18
【问题描述】:
我的目标是进行集成测试,以确保在查找期间不会发生太多数据库查询。 (这有助于我们捕获由于不正确的 JPA 配置而导致的 n+1 个查询)
我知道数据库连接是正确的,因为只要MyDataSourceWrapperConfiguration 不包含在测试中,测试运行期间就没有配置问题。但是,一旦添加,就会发生循环依赖。 (见下面的错误)我相信 @Primary 是必要的,以便 JPA/JDBC 代码使用正确的 DataSource 实例。
MyDataSourceWrapper 是一个自定义类,用于跟踪给定事务发生的查询数量,但它将真正的数据库工作委托给通过构造函数传入的DataSource。
错误:
The dependencies of some of the beans in the application context form a cycle:
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
┌─────┐
| databaseQueryCounterProxyDataSource defined in me.testsupport.database.MyDataSourceWrapperConfiguration
↑ ↓
| dataSource defined in org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat
↑ ↓
| dataSourceInitializer
└─────┘
我的配置:
@Configuration
public class MyDataSourceWrapperConfiguration {
@Primary
@Bean
DataSource databaseQueryCounterProxyDataSource(final DataSource delegate) {
return MyDataSourceWrapper(delegate);
}
}
我的测试:
@ActiveProfiles({ "it" })
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({ DatabaseConnectionConfiguration.class, DatabaseQueryCounterConfiguration.class })
@EnableAutoConfiguration
public class EngApplicationRepositoryIT {
@Rule
public MyDatabaseQueryCounter databaseQueryCounter = new MyDatabaseQueryCounter ();
@Rule
public ErrorCollector errorCollector = new ErrorCollector();
@Autowired
MyRepository repository;
@Test
public void test() {
this.repository.loadData();
this.errorCollector.checkThat(this.databaseQueryCounter.getSelectCounts(), is(lessThan(10)));
}
}
更新:这个原始问题是针对 springboot 1.5 的。但是,接受的答案反映了@rajadilipkolli 的答案适用于springboot 2.x
【问题讨论】:
-
您可能对vladmihalcea.com/2014/02/01/… 感兴趣(它实际上使用了一个库来这样做)。要包装您的数据源,我建议使用
BeanPostProcessor将原始DataSource包装在代理类中。
标签: spring spring-boot spring-jdbc