nanocontainer對picocontainer容器作了一些擴充的封裝,它提供了用多種指令碼(groovy, .bsh, .js, .py or .xml等)配置容器管理的對象的功能,同時提供了對web容器的支援,並且針對struts、webwork也有專門的支援,這裡我調試成功了在struts中如何使用nanocontainer容器。nanocontainer的網站上的文檔提供的非常少,從這裡可以下載到一個簡單的web應用的例子。
http://dist.codehaus.org/nanocontainer/war/nanocontainer-sample-nanowar.war
但是這個war並不完整,解開war看到只有一些編譯過的class,要看原始碼可以從cvs上下載到
http://www.nanocontainer.org/Source+Repositories
並沒有web.xml struts-config.xml等設定檔和jsp檔案。nanocontainer也太不注重文檔和例子代碼的詳細程度了。我自己補充完整了這個例子需要的其他檔案,在下面貼出來。
運行這個例子需要以下幾個檔案:
1. web.xml
這個檔案只要從struts提供的例子中的blank中找到一個空的web.xml檔案,加入下面配置就可以了
<context-param>
<param-name>nanocontainer.groovy</param-name>
<param-value>/WEB-INF/nanocontainer.groovy</param-value>
</context-param>
<listener>
<listener-class>org.nanocontainer.nanowar.ServletContainerListener</listener-class>
</listener>
2.nanocontainer.groovy 放到/WEB-INF中,我在這裡使用了groovy 指令碼的配置方式。
pico = new org.picocontainer.defaults.DefaultPicoContainer(parent)
if(assemblyScope instanceof javax.servlet.ServletContext) {
pico.registerComponentImplementation(org.nanocontainer.sample.nanowar.service.defaults.DefaultCheeseService)
pico.registerComponentImplementation(org.nanocontainer.sample.nanowar.dao.simple.MemoryCheeseDao)
} else if(assemblyScope instanceof javax.servlet.http.HttpSession) {
} else if(assemblyScope instanceof javax.servlet.ServletRequest) {
}
3.struts-config.xml檔案內容如下
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<!-- ============================================ Data Source Configuration -->
<!-- ================================================ Form Bean Definitions -->
<form-beans>
<form-bean
name="inputForm"
type="org.nanocontainer.sample.nanowar.struts.CheeseForm"/>
</form-beans>
<!-- ========================================= Global Exception Definitions -->
<global-exceptions>
<!-- sample exception handler
<exception
key="expired.password"
type="app.ExpiredPasswordException"
path="/changePassword.jsp"/>
end sample -->
</global-exceptions>
<!-- =========================================== Global Forward Definitions -->
<global-forwards>
<!-- Default forward to "Welcome" action -->
<!-- Demonstrates using index.jsp to forward -->
<!-- =========================================== Action Mapping Definitions -->
<action-mappings>
<action
path="/nanicoTest"
type="org.nanocontainer.sample.nanowar.struts.CheeseAction"
name="inputForm" >
<forward redirect="false" name="next"
path="/result.jsp" />
</action>
</action-mappings>
<!-- ============================================= Controller Configuration -->
<controller
processorClass="org.nanocontainer.nanowar.struts.PicoRequestProcessor"/>
<!-- ======================================== Message Resources Definitions -->
<message-resources parameter="MessageResources" />
</struts-config>
4. naoweb.jsp 一個測試的jsp form表單頁面。
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested" %>
<%
out.println(session.getAttribute(org.apache.struts.Globals.LOCALE_KEY)+"--<br>");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
<html:base />
<title>zmlogin.jsp</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<html:errors/>
<html:form action="nanicoTest">
<INPUT type="hidden" name="method" value="vtest">
<table width="41%" border="1">
<tr>
<td width="26%">Name</td>
<td width="74%"><input type="text" name="name"></td>
</tr>
<tr>
<td>Country</td>
<td><input type="text" name="country"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input name="submit" type="submit">
</div></td>
</tr>
</table>
<br>
</html:form>
</body>
</html:html>
5.提交的結果頁面 result.jsp
<%
out.println("=="+request.getAttribute("cheesesOfTheWord"));
%>
將這幾個檔案儲存,放到合適的位置,啟動tomcat,請求naoweb.jsp檔案即可。
我們可以從源碼CheeseAction看到,CheeseService 是個介面,這個代碼中並沒有給出介面的實現,
並沒有和某一個具體的實現產生依賴關係,可見依賴關係是在運行時由容器建立的,pico容器使用的是構造子注入,可以看到代碼中有對應的構造器。容器是從nanocontainer.groovy設定檔中找到具體實現的。然而代碼是可以正常啟動並執行,這就是我們想要達到的理想的效果,真正的面向介面的編程。這樣的結果對我們的單元測試是非常有利的。
public class CheeseAction extends Action {
private final CheeseService cheeseService;
public CheeseAction(CheeseService cheeseService) {
this.cheeseService = cheeseService;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CheeseForm cheeseForm = (CheeseForm) form;
if (!isEmpty(cheeseForm.getName())) {
Cheese cheese = new Cheese(cheeseForm.getName(), cheeseForm.getCountry());
cheeseService.save(cheese);
}
Collection cheeses = cheeseService.getCheeses();
request.setAttribute("cheesesOfTheWord", cheeses);
return mapping.findForward("next");
}
private boolean isEmpty(String s) {
return s == null || "".equals(s.trim());
}
}
補充:
讀
org.nanocontainer.nanowar.struts.PicoRequestProcessor和
org.nanocontainer.nanowar.struts.ActionFactory 的源碼。
processActionCreate方法在發出一個request請求時執行。該方法用於建立action,他覆蓋了struts中原有的該方法操作,替代之用nanico容器來建立和管理action,這樣可以完成對action對象的構造器注入。
ActionFactory中,getActionsContainer方法,用來取得ActionsContainer,用這個索引值KeyConstants.ACTIONS_CONTAINER從request中取,如果沒有就建立他並以該索引值放到request中。
private MutablePicoContainer getActionsContainer(HttpServletRequest request) {
MutablePicoContainer actionsContainer = (MutablePicoContainer) request.getAttribute(KeyConstants.ACTIONS_CONTAINER);
if (actionsContainer == null) {
actionsContainer = new DefaultPicoContainer(containerFinder.findContainer(request));
request.setAttribute(KeyConstants.ACTIONS_CONTAINER, actionsContainer);
}
return actionsContainer;
}
在建立的過程中,用到了containerFinder.findContainer(request)方法,在代碼org.nanocontainer.nanowar.ServletContainerFinder中,findContainer方法,將按request、session、Application的順序尋找,但是索引值分別是 KeyConstants.REQUEST_CONTAINER 、KeyConstants.SESSION_CONTAINER、 KeyConstants.APPLICATION_CONTAINER.
以下是findContainer方法的代碼片斷。
MutablePicoContainer container = getRequestContainer(request);
if (container == null) {
container = getSessionContainer(request.getSession());
}
if (container == null) {
container = getApplicationContainer(request.getSession().getServletContext());
}