Binding one Instance to Two Interfaces in Guice

Sometimes, you need to bind one instance to two interfaces in Guice, for example:

interface Foo { ... }

interface Bar extends Foo { ... }

class FooBarImpl implements Bar { ... }

Let’s imaging FooBarImpl is a stateful bean which is saved in a session scope:

bind(Bar.class)
    .to(FooBarImpl.class)
    .in(Session.class);

This works when someone injects Bar but injecting Foo fails. There are two solutions for this: Bind Foo to Bar or use a provider method to transform the type.

Solution 1: Binding Interfaces

bind(Foo.class)
    .to(Bar.class);

This will use the mapping for Bar to satisfy requests for Foo.

Solution 2: Provider Method

Provider methods are a nice way to build complex objects from bound instances. In our case, we can map the types like so:

@Provides
@Session
public Foo fooProvider(Bar impl) {
    return impl;
}

Note: These approaches will put two keys into your scope but they will point to the same instance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.