0

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 can be any of the following: {postgresql, mysql, mssql, file}. I wanted to configure the binding, such that (it's hibernate based) the app loads a special Provider of SessionFactory depending on which of the values is used, i.e. a PostgresqlSessionFactoryProvider.

The problem is, that Guice also takes care of injecting an instance of Config.class into classes that need access to it. Now I need to access the config, while setting up the binding... It's sort of a chicken-egg problem.

How do I get around that?

4

1 に答える 1

1

これを行う方法を見つけました。それは最善の方法ではないかもしれないので、もしあなたがもっとよく知っていれば、私はまだ答えを見ます.

ポイントは、最初にバインダーを完全に構成する必要があるため、Config.class のインスタンスを提供できるということです。

そこで、構成とguice インジェクター自体を必要とする SessionFactory.class のカスタム プロバイダーを思いつきました。これにより、すべての情報が guice によって丸呑みされたときに、構成に基づいて異なる実装を提供する手段が得られます。

public class SessionFactoryProvider implements Provider<SessionFactory> {

    private Config config;
    private Injector injector;

    @Inject
    public SessionFactoryProvider(Config config, Injector injector) {
        this.config = config;
        this.injector = injector;
    }

    @Override
    public SessionFactory get() {
        switch (config.database.type) {
        case postgresql:
            return injector.getInstance(PostgresqlSessionFactoryProvider.class).get();
        case mysql:
            return injector.getInstance(MysqlSessionFactoryProvider.class).get();
        case file:
            return injector.getInstance(FileBasedSessionFactoryProvider.class).get();
            /* some more providers... */
        default:
            return injector.getInstance(FileBasedSessionFactoryProvider.class).get();
        }
    }
}

どう思いますか?これはこれを行う良い方法ですか?

于 2009-12-03T10:04:01.013 に答える