2016-09-04 39 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

感谢丹!尤其是链接。 –

相关问题