Sven
unread,Jan 28, 2008, 3:18:55 AM1/28/08Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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!