当前HikariModule
包含Java代码中硬编码的值,这不是一个好的做法,使用db.properties
中定义的值会更好。如何做到这一点?我是否需要创建自定义ConfigurableModule<MyModule.Settings>
并在MyModule
中注册HikariModule
?我还没有找到如何在模块内注册模块的方法。谢谢!
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
...
)
);
}
}
假设您在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