Saturday 15 August 2015

hibernate - Guice, bind different database provider based on yaml config -


I have an application config file that looks something like this:

  Database: Type: [db-type] Username: [name] password: [pw] server: [ip] database: [db-name]  

db-type is any of the following May be: {postgresql, Mysql, mssql, file} I want to configure binding, such as this (it is based in hibernation) Ape is a special provider that is based on Sistine Factory And is used, which means that Postgresclseshnfinetprovenr.

The problem is, that the guide also takes care of injection of one instance of Config.class to that class, which it needs to be accessed. Now I need to use config, setting binding ... this is a chicken-egg problem.

How do I get around this?

I have found a way to do this. This can not be the best way to do this, so if you know better then I will also see the answers.

The issue is, that the binder has to be fully configured so it should provide an example of Config.class.

That's why I came with a custom provider for the session Factory.class, which needs an expert and the director himself needs the injector, so that all information slurped by Guise It is meant to provide implementation on a different basis by configuring it.

  Public category SessionFactoryProvider provider provider & lt; SessionFactory & gt; {Private Configuration Config; Private Injector Injector; @ Inject public SessionFactoryProvider (Config Config, Injector Injector) {this.config = config; This.injector = Injector; } @ Override Public Session Session () {Switch (config.database.type) {case postgresql: return injector.getInstance (PostgresqlSessionFactoryProvider.class) .get (); Case mysql: return injector.getInstance (MysqlSessionFactoryProvider.class) .get (); Case File: Return Injector. Gate Instance (filebasexensefancy provider.class) .get (); / * Some other providers ... * / Default: Return Injector .get instance (FileBasedSessionFactoryProvider.class) .get (); }}}  

What do you think? Is there a good way to do this?


No comments:

Post a Comment