How to use Guice when there's no main class?

76 views
Skip to first unread message

Sven

unread,
Jan 28, 2008, 3:18:55 AM1/28/08
to google-guice
Dear all,

this is the first time I'm using Google Guice or a Dependency
Injection framework at all. I have a question about Best Practices in
the following case:

Let's say we have a project which consists of several subprojects. One
of these subprojects, named "commons", contains classes common to all
projects. Most of these classes are concerned with database
abstraction.

The most important class of "commons" is Database, which houses all
database actions. It utilizes the Decorator pattern to forward method
calls to the underlying service:

public class Database implements IDatabaseHandler {
private IDatabaseHandler handler;

@Inject
public Database( IDatabaseHandler handler ) {
this.handler = handler;
}

// methods from IDatabaseHandler interface which route to
this.handler
}

Since there's no main/startup class in this project I cannot configure
Guice there and inject the database handler into the database class.
Thus I've created a ServiceLocator class which does this job:

public class ServiceLocator {
private static Injector injector = null;
private static final Logger logger =
Logger.getLogger( ServiceLocator.class );

static {
if ( injector == null ) {
logger.debug( "Initializing Guice for partymensch-commons" );

try {
injector = Guice.createInjector( new
CommonsModule() );
} catch ( Exception e ) {
logger.fatal( "Error during initialization of Guice", e );
}
}
}

// this is for test case which require a differently configured
injector
public static void setInjector( Injector injector ) {
ServiceLocator.injector = injector;
}

public static Database getDatabase() {
return injector.getInstance( Database.class );
}

}

Is a service locator a good idea for this use case or do you have any
better ideas?

Thank you!

Sven

unread,
Jan 31, 2008, 5:53:49 AM1/31/08
to google-guice
Never mind! I've refactored the code and now the ServiceLocator is
obsolete.
Reply all
Reply to author
Forward
0 new messages