因为之前大多配置的是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指定容器启动时加载.
再次启动就可以正常启动了.