2016-09-04 2 views
0

Текущий HikariModule содержит жестко закодированное значение в коде Java, что не является хорошей практикой, гораздо лучше использовать значения, определенные в db.properties. Как достичь этого? Нужно ли создать заказ ConfigurableModule<MyModule.Settings> и зарегистрировать HikariModule внутри MyModule? Я не нашел способ регистрации модуля внутри модуля. Благодаря!Как зарегистрировать конфигурационный файл Ratpack с использованием конфигурации приложения

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

Допустим, у вас есть 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

+0

Благодаря Дэн! Специально для ссылки. –