0

CurrentHikariModule在 Java 代码中包含硬编码的值,这不是一个好习惯,最好使用db.properties. 如何做到这一点?我需要创建一个自定义ConfigurableModule<MyModule.Settings>HikariModule在里面注册MyModule吗?我还没有找到如何在模块中注册模块的方法。谢谢!

public class App {

    public static void main(String[] args) throws Exception {
        RatpackServer.start(s -> s 
             .serverConfig( configBuilder -> configBuilder
                .findBaseDir()
                .props("db.properties")
                .require("/database", Settings.class)
             )
             .registry(Guice.registry( bindings -> bindings
                     .module(HikariModule.class, hm -> {
                         hm.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource");
                         hm.addDataSourceProperty("url", "jdbc:postgresql://localhost:5433/ratpack");
                         hm.setUsername("postgres");
                         hm.setPassword("postgres");
                     }).bind(DatabaseInit.class)
             ))
             .handlers( chain -> chain
                    ...
             )
        ); 
    }
}
4

1 回答 1

3

假设您有一个postgres.yaml文件,src/ratpack/postgres.yaml其内容为:

db:
  dataSourceClassName: org.postgresql.ds.PGSimpleDataSource
  username: postgres
  password: password
  dataSourceProperties:
    databaseName: modern
    serverName: 192.168.99.100
    portNumber: 5432

在同一个目录中,假设您有一个空.ratpack文件。

然后,您可以从您的主要课程中执行以下操作:

RatpackServer.start(serverSpec -> serverSpec
      .serverConfig(config -> config
        .baseDir(BaseDir.find()) // locates the .ratpack file
        .yaml("postgres.yaml") // finds file relative to directory containing .ratpack file
        .require("/db", HikariConfig.class) // bind props from yaml file to HikariConfig class
      ).registry(Guice.registry(bindings -> bindings
        .module(HikariModule.class) // this will use HikariConfig to configure the module
      )).handlers(...));

这里有一个完整的工作示例https://github.com/danhyun/modern-java-web

于 2016-09-04T20:19:01.913 回答