首页 > 解决方案 > Spring Boot 给出 URL 必须以 'jdbc' 开头的错误

问题描述

我正在尝试使用注释配置在 Spring Boot 中配置 Postgres 数据库。我在一个名为的文件中拥有所有数据库凭据,database.properties并调用了配置文件DBconfig.java

database.url= jdbc:postgresql://localhost/mydb 
database.driverClassName= com.postgresql.jdbc.Driver
database.username= postgres
database.password= password

dbConfig 文件 -

@Configuration
@PropertySource("classpath:databaseAccess/database.properties")

public class DBconfig {

  @Value("${username}")
  private String username;

  @Value("${password}")
  private String password;

  @Value("${url}")
  private String url;

  @Bean
  @Qualifier("postgresDB")
  public DataSource dataSource() {
    DataSourceBuilder dataSource = DataSourceBuilder.create();
    dataSource.url(url);
    dataSource.password(password);
    //dataSource.driverClassName(driverClassName);
    dataSource.username(username);
    return dataSource.build();
  }

  @Bean
  @Qualifier("jdbcTemplate")
  public JdbcTemplate jdbcTemplate() {
      return new JdbcTemplate(dataSource());
  }
}

这是我的主要文件

     @SpringBootApplication
     public class GetNotificationsApplication {

        public static void main(String[] args) {

           ApplicationContext ctx = new AnnotationConfigApplicationContext(DBconfig.class);
           JdbcTemplate template= ctx.getBean("jdbcTemplate", JdbcTemplate.class);
           template.execute("CREATE TABLE TEST( test VARCHAR(20))");

        }

     }

我不断收到错误工厂方法'dataSource'抛出异常;嵌套异常是 java.lang.IllegalArgumentException: URL 必须以 'jdbc' 开头

标签: postgresqlspring-bootspring-jdbc

解决方案


尝试通过为 postgres 定义端口号来更改 url 参数的值。假设 postgres 在默认端口 5432 上运行。

改变

jdbc:postgresql://localhost/mydb

jdbc:postgresql://localhost:5432/mydb

对于端口号检查使用 PSQL 命令查找主机名和端口

更新:

也通过前缀更改@Value("${username}")为和其他属性。@Value("${database.username}")database


推荐阅读