Hi guys,
the last days I worked on a new way to use Guice for injection. The
reason for starting this was a request to do similar things at the
german Java forums. So I started experimenting with it and recognized
that Guice 4 trunk has exactly the last missing key implemented to do
what was requested, ProvisionListener.
So what does Identity Injection?
Well Identity Injection takes place for the ID (identity) of object,
for example entites. Instead of just bind one special instance you can
bind a special ID. It can be seen as a special version of @Named
binding but that can be retrieved dynamically. The ID is given as one
or more properties of binding annotations. Compared to normal Guice
binding with annotation bindings you not bind a static instance but
the IdentityProvider retrieves the actual annotation instance (at the
provision point) and can return the value dynamically (for example
retrieve it from database by an EntityManager). In combination with an
RequestScope or Transactional-Scope you can directly bind special
instances.
<pre>public class UserInjectable2 {
@User(byId = 1)
private UserEntity user1;
@User(byId = 2)
private UserEntity user2;
}</pre>
It can be bound by the new IdentityModule:
<pre>final Injector injector = Guice.createInjector(new
IdentityModule() {
@Override
protected void configure() {
bindIdentity(UserEntity.class).annotatedWith(User.class)
.toIdentityProvider(new UserValueInjector());
}
});</pre>
A IdentityProvider is a new interface which works very similar to the
Provider interface but it has a parameter according to the actual
annotation instance:
<pre>public class UserValueInjector implements
IdentityProvider<UserEntity, User> {
@Override
public UserEntity buildValue(final User annotation) {
switch (annotation.byId()) {
case 1:
return new UserEntity("User1", 1);
case 2:
return new UserEntity("User2", 2);
}
throw new IllegalArgumentException("No user found for Id "
+ annotation.byId());
}
@Override
public Class<UserEntity> getInjectionType() {
return UserEntity.class;
}
}</pre>
I would love to discuss the idea and possibly contribute the code to
the official Guice extensions codebase. At the moment the code is
located at bitbucket and can be reviewed at
https://bitbucket.org/noctarius/guiceannotationextender/src.
Looking into an inspiring discussion I will answer all further
questions.
Greeting from Germany,
Noctarius