2016-09-04 103 views
0

當前HikariModule包含Java代碼中的硬編碼值,這不是一種好的做法,要好得多使用在db.properties中定義的值。如何實現這一目標?我是否需要在MyModule內部創建自定義ConfigurableModule<MyModule.Settings>並註冊HikariModule?我還沒有找到如何在模塊內註冊模塊的方法。謝謝!如何使用應用程序配置註冊Ratpack的ConfigurableModule

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 
        ... 
      ) 
     ); 
    } 
} 

回答

2

比方說,你在src/ratpack/postgres.yaml其內容是有一個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

+0

感謝丹!尤其是鏈接。 –

相關問題