Using multiple constructors with @Inject

4,032 views
Skip to first unread message

Andy Davey

unread,
Feb 10, 2009, 6:39:38 AM2/10/09
to google-guice
Hi,

presently I have a class that has multiple constructors:

class SomeClass
{
@AssistedInject
public SomeClass(SomeService service, @Assisted Kicks kicks)
{
...
}

@AssistedInject
public SomeClass(SomeService service, @Assisted Laughs laughs)
{
...
}
}

Since I only want the SomeService parameter injected I've been using
the AssistedInject extension.

Using the Assisted extension I've created a interface that looks
something like:

interface SomeClassFactory
{
SomeClass forKicks(Kicks kicks);
SomeClass forLaughs(Laughs laughs);
}

And I bind it in the usual manner:

bind(SomeClassFactory.class).toProvider(FactoryProvider.newFactory
(SomeClassFactory.class, SomeClass.class));

Everything works fine _except_ @AssistedInject is now deprecated (I'm
currently using snapshot 20090205).

The problem is, if I replace @AssistedInject with @Inject (which was
my understanding of what the documentation said to do) I get
exceptions trying to build the Injector:

SomeClass has more than one constructor annotated with @Inject.
Classes must have either one (and only one) constructor annotated with
@Inject or a zero-argument constructor that is not private.

My question is, is there a way forward that will allow me to have
multiple DI constructors that doesn't rely on deprecated code?

Cheers,

Andy

Andy Davey

unread,
Feb 14, 2009, 12:01:23 AM2/14/09
to google-guice
Well I found a workaround.

Basically instead of letting FactoryProvider create an implementation
of SomeClassFactory, I created my own implementation:

class SomeClassFactoryImpl implements SomeClassFactory
{
private SomeService m_service;

@Inject
public SomeClassFactoryImpl(SomeService service)
{
m_service = service;
}

public SomeClass createForKicks(Kicks kicks)
{
return new SomeClass(m_service, kicsk);
}

public SomeClass createForLaughs(Laughs laughs)
{
return new SomeClass(m_service, laughs);
}
}

However, this seems like a backwards step to me. Why shouldn't a class
be able to have multiple constructors that are annotated with @Inject?

I understand that it's not to hard to come up with an example where
Guice wouldn't know which constructor to call, because all required
dependencies of every
parameter for every constructor are available.

But in the case of assisted injection, the factory method basically
dictates which constructor to call.

Does anyone else have any thoughts?

Miguel Andrade

unread,
Mar 15, 2012, 6:04:26 PM3/15/12
to google...@googlegroups.com
Some years later, I had the same problem.
However I need to use Guice 2.0 because of Resteasy compatibility.

Some flexibility in this matter would be nice.

Anyone found out a solution other than implementing the Factory?
Reply all
Reply to author
Forward
0 new messages