Accessing Services managed by the Injector
The injector is responsible for constructing and linking components together. In many scenarios,
it is desirable for the injector to expose services so that they can be accessed by the host
application. This is done by adding an "output" method on the injector. The methods must be an
abstract instance method that returns the desired service. The annotation processor
will treat these methods as dependencies that must be resolved. These methods can also
return qualified services if they are annotated with the @Named
annotation
as described in the naming document. These output methods can also be the different
types of dependency described in the dependency kinds document.
A simple example to illustrate how services can be accessed from an injector follows.
The injector:
@Injector
public interface LibraryApplication
{
static LibraryApplication create()
{
return new Sting_LibraryApplication();
}
BookCatalog getBookCatalog();
}
Using the injector from the host application:
{
final LibraryApplication application = LibraryApplication.create();
final BookCatalog bookCatalog = application.getBookCatalog();
// Lookup Hitchiker's Guide to the Galaxy
final Book book = bookCatalog.queryByIsbn( "0434023396" );
if ( null != book )
{
System.out.println( "Huzzah! The book is available" );
}