Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure Google-Guice using a generic interface?

Tags:

java

guice

I have a bunch of entity type factories that derive from a common, generic interface. For instance,

public class ConnectionFactory implements IEntityFactory<Connection> { ... }

I'd like to use Google-Guice to break hard dependencies on these factories.

However, there's a syntax error when I try to configure Guice:

public class EntityFactoryModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(IEntityFactory<Connection>.class).to(ConnectionFactory.class);
    }
}

Eclipse says "IEntityFactory cannot be resolved to a variable."

Can someone please help me understand why this doesn't work? Also, is there an alternate syntax that will work?

like image 321
retrodrone Avatar asked May 26 '11 16:05

retrodrone


People also ask

What does Guice createInjector do?

Google's Guice is a Java-based dependency injection framework, which means approximately nothing to people who aren't familiar with it. Google's Guice is a way to build a graph of dependencies so you can instantiate complex objects made of simpler parts.

What does bind mean in Guice?

A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.

What is Guice dependency?

Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google. This tutorial covers most of the topics required for a basic understanding of Google Guice and to get a feel of how it works.

What is module in Google Guice?

The Module is the core building block for an Injector which is Guice's object-graph builder. First step is to create an injector and then we can use the injector to get the objects. public static void main(String[] args) { /* * Guice.createInjector() takes Modules, and returns a new Injector * instance.


1 Answers

My Guice-fu is generally limited, but I think you want a type literal here:

bind(new TypeLiteral<IEntityFactory<Connection>>() {})
    .to(ConnectionFactory.class);
like image 100
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet