JNDI配备DataSource的那些事儿

JNDI配置DataSource的那些事儿
在使用TOMCAT6的时候,配置和使用JNDI都是非常简单的.

只要在应用的<Context>节点下配置RESOURCE:
<Resource name="jdbc/myds" auth="Container" type="javax.sql.DataSource"
               maxActive="50" maxIdle="30" maxWait="10000" logAbandoned="true" 
               username="xxxxxx" password="xxxxxxx"
               driverClassName="com.ibm.db2.jcc.DB2Driver"
               url="jdbc:db2://xxxxx:60200/yyyyy"/>


应用中直接
lookup("java:comp/env/jdbc/myds")



但是公司用的是IBM WebSphere Application Server,在服务器配置好了DataSource后,总是不能用java:comp/env/jdbc/myds来取得DS,而要用jdbc/myds

这就造成了我的代码无法再两个容器间移植。

解决办法:
1.web.xml,ID随便设置,但必须:
<resource-ref id="ResourceRef_1">
	<description>DEMO</description>
	<res-ref-name>jdbc/demo</res-ref-name>
	<res-type>javax.sql.DataSource</res-type>
	<res-auth>Container</res-auth>
	<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>



2.ibm-web-bnd.xmi,该文件位于WEB-INF目录下,href中的ID要和上面的ID一致:
<?xml version="1.0" encoding="UTF-8"?>
<webappbnd:WebAppBinding xmi:version="2.0"
	xmlns:xmi="http://www.omg.org/XMI" xmlns:webappbnd="webappbnd.xmi"
	xmi:id="WebAppBinding_1243746226890" virtualHostName="default_host">

	<webapp href="WEB-INF/web.xml#WebApp_ID" />
	


	<resRefBindings xmi:id="ResourceRefBinding_1"
		jndiName="jdbc/demo">
	    <bindingResourceRef href="WEB-INF/web.xml#ResourceRef_1" />
	</resRefBindings>	
</webappbnd:WebAppBinding>




如此,便可以用java:comp/env/jdbc/myds来查找DataSource了!!

相信主流的J2EE服务器应该都有类似的解决方案!