本文力求簡潔,希望通過一個簡單的demo應用講解EasyJWeb與Guice容器的集成。
通過EasyJWeb提供的超級IoC容器,你可以非常輕松的把Guice容器集成進來,讓Guice來管理業務層的依賴關系,EasyJWeb只負責表現。我們看下面的配置:
<?xml version="1.0" encoding="utf-8"?>
<easyjf-web>
<modules inject="auto">
<module name="guice" path="/guice" form="" scope="request" action="com.easyjf.demo.action.GuiceAction" defaultPage="index" >
<page name="index" url="/guice.html" type="template"/>
</module>
</modules>
<beans>
<bean name="GuiceContainer" class="com.easyjf.container.impl.GuiceContainer" scope="singleton">
<property name="modules">
<list>
<value>com.easyjf.demo.module.GuiceModule</value>
</list>
</property>
<property name="stage">

<value>DEVELOPMENT</value>

</property>
</bean>
</beans>
</easyjf-web>
熟悉EasyJWeb的朋友都知道,上面的配置通過/guice.ejf便可以訪問GuiceAction業務。特別之處在于我們在這里配置了一個“GuiceContainer”的bean,該bean負責集成EasyJWeb與Guice。屬性modules的每個類都要繼承Guice的AbstractModule類,以實現客戶化的裝配邏輯;stage屬性代表Guice容器的運行環境,既生產環境或開發環境。下面我們看一下上面配置文件中GuiceModule的實現:

/** *//**
*
* @author ecsoftcn@hotmail.com
*
* @version $Id: GuiceModule.java, 2007-4-23 上午03:31:33 Tony Exp $
*/

public class GuiceModule extends AbstractModule
{


/**//*
* @see com.google.inject.AbstractModule#configure()
*/
@Override

protected void configure()
{
this.bindInterceptor(any(), annotatedWith(Logging.class), new LoggingInterceptor());

}

}
至于這個類的具體裝配邏輯我在此不詳細描述,讀者只要知道是綁定攔截器就可以了,有興趣的可以參閱Guice的文檔。在configure方法中,你可以隨心所欲的實現任何客戶化的裝配邏輯。接下來我們再看一下上面GuiceAction的實現:

/** *//**
*
* @author ecsoftcn@hotmail.com
*
* @version $Id: GuiceAction.java, 2007-4-23 上午03:15:47 Tony Exp $
*/
@SessionScoped

public class GuiceAction implements IWebAction
{

@Inject
private GuiceService guiceService;

private int count = 0;


/**//*
* @see com.easyjf.web.IWebAction#execute(com.easyjf.web.WebForm, com.easyjf.web.Module)
*/
@Logging

public Page execute(WebForm form, Module module) throws Exception
{

count++;

form.addResult("message", guiceService.sayHelloToGuice());

form.addResult("count", count);

return module.findPage("index");
}

}
注意到上面的代碼中,GuiceAction實現了EasyJWeb的IWebAction接口,不同的地方是這個類中多了幾個Annotation:@SessionScoped,@Inject和@Logging,:@SessionScoped代表該類的作用域;@Inject代表該類引用了Guice容器中的一個bean[GuiceService];@Logging代表這個方法需要記錄日志,就是通過剛才的攔截器實現的。下面給出GuiceService極其實現類:

/** *//**
*
* @author ecsoftcn@hotmail.com
*
* @version $Id: GuiceService.java, 2007-4-23 上午03:16:20 Tony Exp $
*/
@ImplementedBy(GuiceServiceImpl.class)

public interface GuiceService
{
public String sayHelloToGuice();

}
實現:

/** *//**
*
* @author ecsoftcn@hotmail.com
*
* @version $Id: GuiceServiceImpl.java, 2007-4-23 上午03:17:24 Tony Exp $
*/
@Singleton

public class GuiceServiceImpl implements GuiceService
{


/**//*
* @see com.easyjf.demo.GuiceService#sayHelloToGuice()
*/
@Logging

public String sayHelloToGuice()
{
System.out.println("Execute GuiceServiceImpl#sayHelloToGuice()");
return "Hello, Guice!";

}

}
這兩個類中都使用了Guice的Annotation來聲明裝配原則,具體含義請參考Guice文檔。
到此為止,一個簡單的Demo就算介紹完了,歡迎交流。