【问题标题】:Module Initialization And Destruction handlers in Guice?Guice 中的模块初始化和销毁​​处理程序?
【发布时间】:2011-10-04 22:38:16
【问题描述】:

以下链接描述了如何使用带有 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);
}

但没有列出具体服务类的任何示例实现。谁能给我一份?至少是 start() 和 stop() 包含的示例实现。

【问题讨论】:

    标签: guice guice-3


    【解决方案1】:

    看看Guava 中的Service 接口及其抽象实现。我很确定该界面(以及其他类似的界面)通常是该文档所指的。无论如何,它是基本的基础设施。

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

    【讨论】:

    猜你喜欢
    • 2012-10-14
    • 2018-08-29
    • 2015-07-18
    • 2023-03-30
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多