首页 > 解决方案 > 运行 mvn clean install app 尝试将 postgres 连接到错误的端口

问题描述

运行时出现此错误

$ mvn clean install

org.postgresql.util.PSQLException: Connection to localhost:5432
refused. Check that the hostname and port are correct and that the
postmaster is accepting TCP/IP connections.

然而,在我的 application.properties 中,我已将端口明确定义为 5433:

spring.datasource.url=jdbc:postgresql://localhost:5433/mydb

我还在 postgres.conf 中所述的端口 5433 上运行 postgres:

port = 5433                             # (change requires restart)

我确实跑了

$ systemctl postgresql restart

更改端口后。

这里有什么问题?我没有在我的项目文件中的其他任何地方定义端口。

完整的 application.properties 文件:

spring.main.banner-mode=off
logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=none

spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5433/mydb
spring.datasource.username=myuser
spring.datasource.password=mypass

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.profiles.active=@spring.profiles.active@

标签: javaspringpostgresqlmaven

解决方案


问题出在您的配置文件中(您没有提供)。如果您使用的是 spring boot,您很可能有一个 java 文件而不是 xml 文件,并且您必须从 application.properties 文件中调用您的属性。

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

您应该有一个数据源的 @Bean 定义,看起来应该是这样的:

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    return dataSource;
}

问题是您没有将 url 设置为您在 application.properties 文件中指定的内容,或者您​​正在将其覆盖在某处。

*编辑

@Configuration
public class PostgreConfiguration {

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

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

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

    @Value("${spring.datasource.driver_class_name}")
    private String driverClassName;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }
}

推荐阅读