helpermethod
helpermethod

Reputation: 62244

Guice 3.0 - Purpose of Constructor Bindings?

I've just read the chapter about Constructor Bindings in Guice's User Guide but don't really understand when to use Constructor bindings.

As far as I understand, they provide the same functionality as @Provider methods, except instances created with Constructor Bindings participate in AOP. Is this correct? Can anyone give a better example than the one in the doc?

Upvotes: 2

Views: 278

Answers (1)

ColinD
ColinD

Reputation: 110084

As far as I understand, they provide the same functionality as @Provider methods, except instances created with Constructor Bindings participate in AOP.

That's more or less correct, though there are some advantages that constructor binding has. Basically, it's a way of binding to a class as if it had an @Inject on a specific constructor even if it doesn't and you can't add the annotation yourself. Unlike @Provides methods, you could write utilities to allow you to do more interesting things. For instance, you could have a utilitiy method that returns the only constructor of a class, throwing an exception if there are more than one:

bind(Foo.class).toConstructor(getOnlyConstructor(FooImpl.class));

You could also use some other annotation (besides @Inject) if you wanted for some reason and have a utility method that gets the constructor that's annotated with that for binding.

Upvotes: 4

Related Questions