同weblogic不同,在jboss中配置數據源并沒有可視化的控制臺.一般.大家都是到%JBOSS_HOME%\docs\examples\jca目錄下,找到自己所要配置的數據源的模板文件,然后修改jndi-name,connection-url,driver-class,user-name,password,等等,然后把修改后的配置文件丟到要使用的domain下的deploy目錄下就可以了,但是這時住往會有個問題.
你會發現,你在客戶端查找不到你剛剛配置的數據源.

結果是一大堆異常:
  • Exception in thread "main" javax.naming.NameNotFoundException: MySqlDS not bound   
  •     at org.jnp.server.NamingServer.getBinding(NamingServer.java:542)   
  •     at org.jnp.server.NamingServer.getBinding(NamingServer.java:550)   
  •     at org.jnp.server.NamingServer.getObject(NamingServer.java:556)   
  •     at org.jnp.server.NamingServer.lookup(NamingServer.java:296)   
  •     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   

  • JNDI查找不到"MySqlDS"這個名稱..
    為什么呢?
    我們去JBOSS的控制臺去查看JNDI樹結構.

    Other components with java:comp namespace
    java: Namespace
      +- ClusteredXAConnectionFactory (class: org.jboss.jms.client.JBossConnectionFactory)
      +- jaas (class: javax.naming.Context)
      |   +- messaging (class: org.jboss.security.plugins.SecurityDomainContext)
      +- TransactionPropagationContextImporter (class: com.arjuna.ats.internal.jbossatx.jta.PropagationContextManager)
      +- MySqlDS (class: org.jboss.resource.adapter.jdbc.WrapperDataSource)

    很明顯"MySqlDS"做為key被綁定在JNDI上了.那么為什么還會出錯呢...

    : )我浪費了很長時間在找這個錯誤的過程中,中間甚至一度以為,JBOSS不支持在服務器外獲取數據源.后來一個家伙好像在寫EJB3.0的時候也遇到這個問題,并且找來了下面這個項文文檔..讓我驚為天人啊...

    <use-java-context> - A boolean indicating if the jndi-name should be prefixed with java: which causes the DataSource to only be accessible from within the jboss server vm. The default is true.

    Configuring a DataSource for remote usage
    As of jboss-4.0.0 there is support for accessing a DataSource from a remote client. The one change that is necessary for the client to be able to lookup the DataSource from JNDI is to specify use-java-context=false as shown here:

    <datasources>  <local-tx-datasource>    <jndi-name>GenericDS</jndi-name>    <use-java-context>false</use-java-context>    <connection-url>...</connection-url>...
    This results in the DataSource being bound under the JNDI name "GenericDS" instead of the default of "java:/GenericDS" which restricts the lookup to the same VM as the jboss server.

    身為高級知識分子,我相信大家即使讀不懂上面的英文,金山詞霸總是會使用的.
    它說的大概意思就是.
    當你指定<use-java-context>的值為false時,你就可以在jboss運行的VM外的VM上查找到這個DataSource.
    這個屬性默認.為true   :( 
    即,默認情況下你是不可以在JBOSS的VM外來查找這個數據源. 

    其實吧,這個問題看起來很普通,解決起來也很簡單只是加了一行代碼,但是.JBOSS服務器的提供廠商是否有想過,一個example配置文件中,具然少了這種重要的配置信息.
    至少你把它配上,然后注掉也好啊.