我正在尝试使用注释配置在春季启动中配置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.IollegalArgumentException:URL必须以"jdbc"开头
尝试通过定义postgres的端口号来更改url参数的值。假设postgres在5432上运行,5432是默认端口
更改
jdbc:postgresql://localhost/mydb
至
jdbc:postgresql://localhost:5432/mydb
对于端口号检查,使用PSQL命令查找主机名和端口
更新:
还可以通过前缀database
将@Value("${username}")
更改为@Value("${database.username}")
和其他属性。