简体   繁体   中英

Guice: Is it possible to inject an instance depending on wether it exists on classpath?

I have a Guice 3.0 module and some interface, which implementations may vary. What I want is to instantiate and inject some dependency by searching for it on my classpath.

Ie

@Inject 
private MyInterface instance;

ConcreteImplementationA implements MyInterface {...}

ConcreteImplementationB implements MyInterface {...}

So if ConcreteImplementationA.class is found on classpath of application - it should be injected, if ConcreteImplementationB - then B.

It is not an issue if I have to configure all possible bindings for my interface.

Is it possible to implement it with Guice?

You can register a custom provider like this:

public class MyModule extends AbstractModule {

    private static final Class<MyInterface> myInterfaceClass = getMyInterfaceClass();

    @SuppressWarnings("unchecked")
    private static Class<MyInterface> getMyInterfaceClass() {
        try {
            return (Class<MyInterface>) Class.forName("ConcreteImplementationA");
        } catch (ClassNotFoundException e) {
            try {
                return (Class<MyInterface>) Class.forName("ConcreteImplementationB");
            } catch (ClassNotFoundException e1) {
                // Handle no implementation found
            }
        }
    }

    @Provides
    MyInterface provideMyInterface() {
        return myInterfaceClass.newInstance();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM