The following link describes how to handle module initialization and destruction in Guice using a Service interface with a start() and stop() method:
https://github.com/google/guice/wiki/ModulesShouldBeFastAndSideEffectFree
The documentation explains that the creation of the service looks like this in client code:
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(
new DatabaseModule(),
new WebserverModule(),
...
);
Service databaseConnectionPool = injector.getInstance(
Key.get(Service.class, DatabaseService.class));
databaseConnectionPool.start();
addShutdownHook(databaseConnection开发者_开发百科Pool);
Service webserver = injector.getInstance(
Key.get(Service.class, WebserverService.class));
webserver.start();
addShutdownHook(webserver);
}
But does not list any sample implementation of a Concrete Service class. Can anyone provide me with one? At least a sample implementation of what would start() and stop() contain.
Take a look at the Service interface in Guava and the abstract implementations of it. I'm pretty sure that interface (and others that are similar to it) is generally what that documentation is referring to. It's the basic infrastructure anyway.
As far as what your service would actually need to do when it starts up or shuts down, that depends on the service itself. In the example, the webserver service might start listening on ports when it starts and stop listening when it stops. The connection pool might fetch some connections when it starts and would need to release any connections it holds when it stops.
精彩评论