我正在尝试创建JdbcTemplate bean,如下所示:
@Configuration
public class ServiceBeanConfiguration {
@Bean
public JdbcTemplate jdbcTemplate() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432/sp");
driverManagerDataSource.setUsername("posthres");
driverManagerDataSource.setPassword("password");
DataSource dataSource = driverManagerDataSource;
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
我将这个@Bean自动绑定到我的服务类中。但结果是我收到了错误:
**************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
发布于 2018-08-23 21:18:54
创建一个application.properties
并将spring.datasource
属性放入其中。
spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password
删除ServiceBeanConfiguration
并重新启动应用程序。
Spring Boot将自动为您配置DataSource
和JdbcTemplate
。
发布于 2018-08-24 16:19:31
您应该在pom.xml中添加一个数据库依赖项。
原因:无法确定合适的驱动程序类
添加postgre依赖项或内存中的数据库:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
如果您选择使用postgre数据库,则不需要创建@bean。创建应用程序属性,就像M. Deinum写的那样。
spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password
如果您选择"In memory database“,Application.properties将不是必需的(Spring boot将为您配置所有内容) -->不要在生产环境中使用此方法
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
https://stackoverflow.com/questions/51985986
复制相似问题