JdbcTemplate引发异常

时间:2018-08-23 12:36:45

标签: java spring spring-boot

我正尝试如下创建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).

2 个答案:

答案 0 :(得分:1)

创建一个application.properties并在其中放置spring.datasource个属性。

spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password

删除ServiceBeanConfiguration,然后重新启动应用程序。

Spring Boot将自动为您配置DataSourceJdbcTemplate

答案 1 :(得分:1)

您应该在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

如果您选择的是“在内存数据库中”,则不需要Application.properties(Spring boot将为您配置所有属性)->不要在生产环境中使用此方法

   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.197</version>
   <scope>test</scope>