Mutli-valued injection points

Posted by    |      

One of the nice new features in the latest draft of JSR-299 is the ability to inject a reference to all beans of a certain type, for example:

@Any Instance<Connection> anyConnections;

There's actually nothing very special about this injection point. @Any is a built-in binding that is defined to be supported by all beans. Instance<T> is an interface which is implemented by a built-in bean that uses InjectionPoint to inspect the binding types of the injection point. (You could implement Instance<T> yourself if the container didn't come with one.)

Now, Instance<T> extends Iteratable<T>, so we can iterate over anyConnections to do something to all beans that implement Connection:

for (Connection c: anyConnections) c.close();

We can narrow the set of connections we're interested in either dynamically:

Connection userDatabaseConnection = anyConnections.select( new AnnotationLiteral<UserDatabase>() {} ).get();

Or using an annotation at the injection point:

@UserDatabase Instance<Connection> userDatabaseConnection;

Of course, we've now got a way to iterate over every bean:

@Any Instance<Object> anyBeans;
for (Object bean: anyBeans) doSomething(bean);

Back to top