【问题标题】:How to enable jdbc template in my spring boot test如何在我的 Spring Boot 测试中启用 jdbc 模板
【发布时间】:2019-03-15 16:10:30
【问题描述】:

我有一个使用@SpringBootTest 的黄瓜测试框架代码,在我的测试类中我想配置JdbcTemplate 以连接到数据库。我无法autowire 它。如果我使用@EnableAutoConfiguration,它看起来可以工作,但会看到许多其他错误。有没有办法启用注释,我可以用它来启用 jdbc 模板

@SpringBootTest(classes = AppTestConfiguration.class)
@EnableEncryptableProperties
public class CucumberContextConfiguration {
}

@Configuration
@ComponentScan(basePackages = { "com.*" })
public class AppTestConfiguration {
}

我看到的错误是

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

【问题讨论】:

  • 请出示AppTestConfiguration.java的内容
  • 按票更新
  • 您以什么方式为应用程序的非测试范围配置了 jdbc 模板?具体是作为 bean 还是通过 .properties 文件中设置的属性?

标签: spring-boot cucumber spring-test


【解决方案1】:

JdbcTemplate 实际上可以是@Autowired@Injected,因为它是documented in the Spring Boot docs

如果这不起作用,请检查您的 pom.xml 以了解托管依赖项的版本冲突。

@EnableAutoConfiguration 不需要手动操作,因为它已包含在@SpringBootApplication 中。或者您是否没有 Application 类本身,例如因为您有一个仅用于测试的工件?

【讨论】:

  • 如上所述,它不是 Spring Boot 应用程序,而是 Spring Boot 测试。我可以通过添加 @Import(value = {DataSourceAutoConfiguration .class})@Autowired private DataSource dataSource; @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource){ return new JdbcTemplate(dataSource); } 使其工作,但看到 hikari pool isValid 错误
【解决方案2】:

尝试在您的测试代码中添加@RunWith(SpringJUnit4ClassRunner.class)

【讨论】:

  • 你不能在 JUnit5 - Jupiter 中使用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2015-06-01
  • 2019-01-30
  • 2016-12-09
  • 1970-01-01
  • 2015-06-14
相关资源
最近更新 更多