2011-10-04 30 views
1

下面的链接介绍如何使用服务接口启动(以处理吉斯模块的初始化和销毁​​)和stop()方法: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()所包含内容的示例实现。

回答

2

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

只要你的服务实际需要当它启动或关闭,这取决于服务本身。在该示例中,webserver服务可能会在启动时在端口上侦听,并在停止时停止侦听。连接池在启动时可能会获取一些连接,并且在连接池停止时需要释放它保留的任何连接。

+0

详细说明可以在这里找到:http://hellotojavaworld.blogspot.co.il/2010/11/runtimeaddshutdownhook.html – forhas