Guice中的模块初始化和销毁​​处理程序?

时间:2011-10-04 22:38:17

标签: guice guice-3

以下链接描述了如何使用带有start()和stop()方法的Service接口在Guice中处理模块初始化和销毁​​:

http://code.google.com/p/google-guice/wiki/ModulesShouldBeFastAndSideEffectFree

文档说明服务的创建在客户端代码中如下所示:

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(databaseConnectionPool);

    Service webserver = injector.getInstance(
        Key.get(Service.class, WebserverService.class));
    webserver.start();
    addShutdownHook(webserver);
}

但是没有列出Concrete Service类的任何示例实现。任何人都可以提供一个吗?至少start()和stop()的示例实现包含。

1 个答案:

答案 0 :(得分:2)

查看Service中的Guava接口及其抽象实现。我非常确定界面(和其他类似的界面)通常是文档所指的内容。无论如何,这是基础设施。

至于您的服务在启动或关闭时实际需要执行的内容,这取决于服务本身。在该示例中,Web服务器服务可能在启动时开始侦听端口,并在停止时停止侦听。连接池在启动时可能会获取一些连接,并且需要在它停止时释放它所持有的任何连接。