postgresql - 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' 开头
解决方案
尝试通过为 postgres 定义端口号来更改 url 参数的值。假设 postgres 在默认端口 5432 上运行。
改变
jdbc:postgresql://localhost/mydb
到
jdbc:postgresql://localhost:5432/mydb
对于端口号检查使用 PSQL 命令查找主机名和端口
更新:
也通过前缀更改@Value("${username}")
为和其他属性。@Value("${database.username}")
database
推荐阅读
- python - python导入模块 - 我错过了什么?
- django - 在 django 中获取外键 id 时出错
- mysql - 为什么子查询中的 OR 会使查询慢得多?
- sql - 使用 Python 连接到 Jupyter Notebook 中的 SQL 数据库
- javascript - 在用户滚动到它们之前触发所有 `content-visibility: auto` 元素的渲染,而不会阻塞主线程超过 50 毫秒
- python - 如何只保留字符串中的某些字符
- sql-server - SQL Server 中的类型转换问题
- python - GCP 没有名为“tensorflow”的模块
- python - Gurobi 中的简单二次问题没有产生最佳结果?
- c++ - 为什么没有指针就无法打印数组?下面的代码是否正确?