0

我正在尝试使用ServerConfigratpack.groovy 中的块合并服务器和数据库配置,但postgresConfig在尝试创建数据源时为空。

PostgresConfig.groovy

@Compile Static
class PostgresConfig {
    String user
    String password
    String serverName
    String databaseName
    Integer portNumber
}

PostgresModule.groovy

@CompileStatic
class PostgresModule extends ConfigurableModule<PostgresConfig> {
    @Override
    protected void configure() {
    }

    @Provides
    DataSource dataSource(final PostgresConfig config) {
        createDataSource(config)
    }

    protected DataSource createDataSource(final PostgresConfig config) {
        new PgSimpleDataSource(
            user:         config.user,
            password:     config.password,
            serverName:   config.serverName,
            databaseName: config.databaseName,
            portNumber:   config.portNumber
        )
    }
}

ratpack.groovy

ratpack {
    serverConfig {
        props([
            'postgres.user':         'username',
            'postgres.password':     'password',
            'postgres.serverName':   'localhost',
            'postgres.databaseName': 'postgres',
            'postgres.portNumber':   5432
        ] as Map<String, String>)
        yaml "config.yaml"
        env()
        sysProps()
        require("/postgres", PostgresConfig)
    }
    bindings {
        PostgresConfig postgresConfig
        module HikariModule, { HikariConfig config ->
            config.dataSource = new PostgresModule().dataSource(postgresConfig)
        }
    }
}
4

1 回答 1

0

在该bindings块中,您可以引用serverConfig配置,从而获得配置的PostgresConfig. 在您的用例中,您不需要该require("/postgres", PostgresConfig)语句。

您可以使PostgresModule该类不扩展ConfigurableModule,因为它不用作模块。

ratpack {
    serverConfig { ... }
    bindings {
        module HikariModule, { HikariConfig config ->
            config.dataSource = new PostgresModule().dataSource(serverConfig.get("/postgres", PostgresConfig)
        }
    }
}
于 2017-04-26T07:59:06.370 回答