java - JdbcTemplate 抛出异常

标签 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 Autowiring 到我的服务类中。但结果我收到错误:

**************************
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).

最佳答案

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

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

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

Spring Boot 将自动为您配置 DataSourceJdbcTemplate

关于java - JdbcTemplate 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985986/

相关文章:

java - 如何在没有主类的情况下运行JAVA程序

java - 登录成功后如何显示另一个布局

java - Apache Camel - 代码错误 - 必须在 CamelContext 中定义具有名称属性的 PropertiesComponent 以支持属性占位符

java - Spring转换器将null转换为空集合

spring - 如何在不使用 @Scheduled() 注释的情况下在 Spring Boot 中安排 cron 作业

java - spring boot 用户和 session mongo

java - Spring JPA(Hibernate)自动将嵌套对象展平为单个表

spring - 如何在 undertow 中配置 Spring boot 2.4 服务器线程?

java - 定期报告特定指标

java - Spring mvc 映射问题