首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JdbcTemplate抛出异常

JdbcTemplate抛出异常
EN

Stack Overflow用户
提问于 2018-08-23 20:36:45
回答 2查看 79关注 0票数 0

我正在尝试创建JdbcTemplate bean,如下所示:

代码语言:javascript
运行
复制
@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自动绑定到我的服务类中。但结果是我收到了错误:

代码语言:javascript
运行
复制
**************************
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).
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-23 21:18:54

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

代码语言:javascript
运行
复制
spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password

删除ServiceBeanConfiguration并重新启动应用程序。

Spring Boot将自动为您配置DataSourceJdbcTemplate

票数 1
EN

Stack Overflow用户

发布于 2018-08-24 16:19:31

您应该在pom.xml中添加一个数据库依赖项。

原因:无法确定合适的驱动程序类

添加postgre依赖项或内存中的数据库:

代码语言:javascript
运行
复制
 <dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901-1.jdbc4</version>
</dependency>

如果您选择使用postgre数据库,则不需要创建@bean。创建应用程序属性,就像M. Deinum写的那样。

代码语言:javascript
运行
复制
spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password

如果您选择"In memory database“,Application.properties将不是必需的(Spring boot将为您配置所有内容) -->不要在生产环境中使用此方法

代码语言:javascript
运行
复制
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.197</version>
   <scope>test</scope>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51985986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档