我已经在 application.properties 文件中写入了数据库的 url、用户名等。我还在@Autowired
控制器中为 JdbcTemplate定义了注解。但是现在当我执行时,我收到此错误-
应用程序无法启动
描述:
com.sab.Controller 中的字段 jdbc 需要一个无法找到的“org.springframework.jdbc.core.JdbcTemplate”类型的 bean。- 未加载 Bean 方法“jdbcTemplate”,因为 @ConditionalOnSingleCandidate(类型:javax.sql.DataSource;SearchStrategy:all)未找到任何 Bean
行动:
考虑重新访问上述条件或org.springframework.jdbc.core.JdbcTemplate
在您的配置中定义类型的 bean 。
谁能帮我解决这个错误。
您需要定义一个类型为 的 Spring bean JdbcTemplate
。您可以通过向@Bean
Spring Boot 应用程序类添加一个方法来创建并返回JdbcTemplate
. 例如:
@SpringBootApplication
public class ExampleApplication {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
此外,如果您还没有这样做,您必须将数据库连接的属性添加到文件src/main/resources/application.properties
. Spring Boot 使用这些来创建DataSource
bean。例如(您需要在此处放置适当的值;这是使用 H2 内存数据库的示例):
spring.datasource.url=jdbc:h2:mem:demo
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
最后,您需要确保您的pom.xml
. 例如(对于 H2 数据库),您需要在以下dependencies
部分中包含此内容pom.xml
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句