配置Jndi資料來源遇到的一個問題
因為之前大多配置的是jdbc連線方式,偶然一次用到了jndi連線方式,遇到了個比較頭疼的問題,故記錄下來,方便以後查閱.
異常如下:
Caused by: javax.naming.NameNotFoundException: Name mysqlDataSource is not bound in this Context
at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:155)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:179)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:231)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:217)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 27 more
檢測配置檔案.
注入的配置檔案如下
執行時就會出現上面的異常Name mysqlDataSource is not bound in this Context
在例項化JndiTemplate時去找我配置的mysqlDataSource驅動
java:/comp/env/這裡是上下文環境.
因為找不到我的mysqlDataSource,所以就報錯了.
然後去看JndiName原始碼介紹.
Convenient superclass for JNDI-based service locators,
* providing configurable lookup of a specific JNDI resource.
*
* <p>Exposes a {@link #setJndiName "jndiName"} property. This may or may not
* include the "java:comp/env/" prefix expected by J2EE applications when
* accessing a locally mapped (Environmental Naming Context) resource. If it
* doesn't, the "java:comp/env/" prefix will be prepended if the "resourceRef"
* property is true (the default is <strong>false</strong>) and no other scheme
* (e.g. "java:") is given.
大意是需要給JndiName配置一個JNDI資料來源,這個資料來源是包括 "java;comp/env"為字首的的資料來源.
會去訪問上下文中配置的對映源.然而並沒有配置這個對映.
如果沒找到就會去找resourceRef這個預先的資料來源配置.
很遺憾,這裡我也沒有配置...就 蹦沙卡拉卡了...
於是,在web.xml裡面加入引用的資源 <resource-ref>
<description>MYSQL DB Connection</description>
<res-ref-name>mysqlDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
注意res-ref-name配置的Jndi名,要與配置檔案中的jndiName後面的(去掉java:/comp/env/上下文)一致.
res-type指定資料來源是dataSource
res-auth指定容器啟動時載入.
再次啟動就可以正常啟動了.