Java SpringBootApplication中的字段jdbcTemplate需要类型为';org.springframework.jdbc.core.JdbcTemplate';那是找不到的
我的主要课程如下:Java SpringBootApplication中的字段jdbcTemplate需要类型为';org.springframework.jdbc.core.JdbcTemplate';那是找不到的,java,spring-boot,autowired,jdbctemplate,Java,Spring Boot,Autowired,Jdbctemplate,我的主要课程如下: @SpringBootApplication @ComponentScan(basePackages = {"com.example"}) public class SpringGuideApplication implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(SpringGuideApplication.class);
@SpringBootApplication
@ComponentScan(basePackages = {"com.example"})
public class SpringGuideApplication implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(SpringGuideApplication.class);
@Autowired
JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringGuideApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
log.info("Creating tables");
jdbcTemplate.execute("DROP TABLE clients IF EXISTS");
}
}
此时,我收到一个错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field jdbcTemplate in com.example.spring_guide.SpringGuideApplication required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.jdbc.core.JdbcTemplate' in your configuration.
Process finished with exit code 1
我理解错误,但要创建@Bean JdbcTemplate
,我需要使用:
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
但我不想要,我不想要任何数据源
文件,我想要的只是内存数据库。有没有办法在没有数据源的情况下创建JdbcTemplate
bean?这本教程到底是如何工作的
在pom.xml中,我现在有:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
org.springframework
SpringJDBC
5.2.10.释放
但是也试过了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.4.0</version>
</dependency>
org.springframework.boot
弹簧靴启动器jdbc
2.4.0
没有成功。这就是
弹簧靴的魅力所在。它看到您正在使用JdbcTemplate
,所以它需要创建数据源,因为您没有提供任何信息,所以它失败了。即使您使用的是内存数据库,也需要提供这些信息,因此springboot
可以为您创建JdbcTemplate
。我不确定您使用的是内存中的哪一个db,但这里有一个关于如何使用H2的示例。您可以在单个dB用户文档中找到这些信息
spring.datasource.url=jdbc:h2:mem:yourdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=
spring.datasource.password=
spring.jpa.database platform=org.hibernate.dialent.h2dialent
您认为数据源是什么?它始终表示一个数据库,可能在内存中,也可能不在内存中。关于DataSource的更多信息:另一个链接:您可以看到嵌入式数据库是构建并返回DataSource的。但是,Spring Boot足够智能,您看不到这段代码,但是它的功能与链接中的完全相同。这并没有什么神奇之处。在pom.xml中使用spring boot starter jdbc
和h2
,我不必声明@Bean JdbcTemplate
显式。感谢您的回答。不过在教程中,即使没有配置文件,它也可以工作,他们在运行时使用内存数据库中的h2