Inject config into Guice HikariModule

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Inject config into Guice HikariModule

dddpaul
Hi.

Is there a way to inject config class to Guice BindingsSpec? For example, I want to inject "jdbcUrl" from config class to HikaryModule.

And the code example:
private static class AppConfig {
    private String jdbcUrl;

    public String getJdbcUrl() {
        return jdbcUrl;
    }
}

public static void main(String... args) throws Exception {
    RatpackServer.of(server -> server
            .serverConfig(c -> c
                    .props(ImmutableMap.of("app.jdbcUrl", "jdbc:oracle:thin:@10.0.0.1:1521:db"))
                    .sysProps()
                    .require("/app", AppConfig.class))
            .registry(Guice.registry(b ->
                    b.module(HikariModule.class, config -> {
                        config.setDriverClassName("oracle.jdbc.OracleDriver");
                        // Can I change this:
                        config.setJdbcUrl("jdbc:oracle:thin:@10.0.0.1:1521:db");
                        // to something like this:
                        config.setJdbcUrl(ctx.get(AppConfig.class).getJdbcUrl());
                    })
            ))
    ).start();
}
Reply | Threaded
Open this post in threaded view
|

Re: Inject config into Guice HikariModule

wziebicki
You can do it like this:

public class App {
    public static void main(String[] args) throws Exception {
        RatpackServer.start(ratpackServerSpec -> {
                    ratpackServerSpec.serverConfig(c ->
                            c.yaml("dbconfig.yml")
                                    .require("/database", DatabaseConfig.class)
                                    .baseDir(BaseDir.find()).build())
                            .registry(Guice.registry(b -> {
                                        final DatabaseConfig databaseConfig = b.getServerConfig().get("/database", DatabaseConfig.class);
                                        b.module(HikariModule.class, hikariConfig -> {
                                            hikariConfig.setDataSourceClassName(databaseConfig.getDataSourceClassName());
                                            hikariConfig.addDataSourceProperty("URL", databaseConfig.getAddDataSourceProperty());
                                        });
                                    })
                            )
                            .handlers(chain -> chain
                                    .get("config", ctx -> {
                                        ctx.render(json(ctx.get(DatabaseConfig.class)));
                                    })
                            );
                }
        );
    }
}