2013-05-16 35 views
0

我在尝试在我的应用程序中使用Spring和jndi时遇到BeanCreationException。 我使用这些文件:Spring应用程序无法使用jndi和正在运行的Tomcat 7服务器创建DataSource bean

对于Tomcat 7:

server.xml中

<?xml version='1.0' encoding='utf-8'?> 
<!-- 
    Licensed to the Apache Software Foundation (ASF) under one or more 
    contributor license agreements. See the NOTICE file distributed with 
    this work for additional information regarding copyright ownership. 
    The ASF licenses this file to You under the Apache License, Version 2.0 
    (the "License"); you may not use this file except in compliance with 
    the License. You may obtain a copy of the License at 

     http://www.apache.org/licenses/LICENSE-2.0 

    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License. 
--> 
<!-- Note: A "Server" is not itself a "Container", so you may not 
    define subcomponents such as "Valves" at this level. 
    Documentation at /docs/config/server.html 
--> 
<Server port="8005" shutdown="SHUTDOWN"> 
    <!-- Security listener. Documentation at /docs/config/listeners.html 
    <Listener className="org.apache.catalina.security.SecurityListener" /> 
    --> 
    <!--APR library loader. Documentation at /docs/apr.html --> 
    <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> 
    <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --> 
    <Listener className="org.apache.catalina.core.JasperListener" /> 
    <!-- Prevent memory leaks due to use of particular java/javax APIs--> 
    <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> 
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
    <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> 

    <!-- Global JNDI resources 
     Documentation at /docs/jndi-resources-howto.html 
    --> 
    <GlobalNamingResources> 
    <!-- Editable user database that can also be used by 
     UserDatabaseRealm to authenticate users 
    --> 
    <Resource name="jdbc/SpringMvcDatabase" auth="Container" 
       type="javax.sql.DataSource" 
       description="User database that can be updated and saved" 
       username="root" password="myPassword" 
       url="jdbc:mysql://localhost:3306/SpringMvcDatabase" 
       driverClassName="com.mysql.jdbc.Driver" 
       initialSize="5" maxWait="5000" 
       maxActive="120" maxIdle="5" 
       validationQuery="select 1" 
       poolPreparedStatements="true"/> 

    <Resource auth="Container" 
      description="User database that can be updated and saved" 
      factory="org.apache.catalina.users.MemoryUserDatabaseFactory" 
      name="UserDatabase" 
      pathname="conf/tomcat-users.xml" 
      type="org.apache.catalina.UserDatabase"/> 
    </GlobalNamingResources> 

    <!-- A "Service" is a collection of one or more "Connectors" that share 
     a single "Container" Note: A "Service" is not itself a "Container", 
     so you may not define subcomponents such as "Valves" at this level. 
     Documentation at /docs/config/service.html 
    --> 
    <Service name="Catalina"> 

    <!--The connectors can use a shared executor, you can define one or more named thread pools--> 
    <!-- 
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
     maxThreads="150" minSpareThreads="4"/> 
    --> 


    <!-- A "Connector" represents an endpoint by which requests are received 
     and responses are returned. Documentation at : 
     Java HTTP Connector: /docs/config/http.html (blocking & non-blocking) 
     Java AJP Connector: /docs/config/ajp.html 
     APR (HTTP/AJP) Connector: /docs/apr.html 
     Define a non-SSL HTTP/1.1 Connector on port 8080 
    --> 
    <Connector port="8080" protocol="HTTP/1.1" 
       connectionTimeout="20000" 
       redirectPort="8443" /> 
    <!-- A "Connector" using the shared thread pool--> 
    <!-- 
    <Connector executor="tomcatThreadPool" 
       port="8080" protocol="HTTP/1.1" 
       connectionTimeout="20000" 
       redirectPort="8443" /> 
    --> 
    <!-- Define a SSL HTTP/1.1 Connector on port 8443 
     This connector uses the JSSE configuration, when using APR, the 
     connector should be using the OpenSSL style configuration 
     described in the APR documentation --> 
    <!-- 
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" 
       maxThreads="150" scheme="https" secure="true" 
       clientAuth="false" sslProtocol="TLS" /> 
    --> 

    <!-- Define an AJP 1.3 Connector on port 8009 --> 
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> 


    <!-- An Engine represents the entry point (within Catalina) that processes 
     every request. The Engine implementation for Tomcat stand alone 
     analyzes the HTTP headers included with the request, and passes them 
     on to the appropriate Host (virtual host). 
     Documentation at /docs/config/engine.html --> 

    <!-- You should set jvmRoute to support load-balancing via AJP ie : 
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> 
    --> 
    <Engine name="Catalina" defaultHost="localhost"> 

     <!--For clustering, please take a look at documentation at: 
      /docs/cluster-howto.html (simple how to) 
      /docs/config/cluster.html (reference documentation) --> 
     <!-- 
     <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
     --> 

     <!-- Use the LockOutRealm to prevent attempts to guess user passwords 
      via a brute-force attack --> 
     <Realm className="org.apache.catalina.realm.LockOutRealm"> 
     <!-- This Realm uses the UserDatabase configured in the global JNDI 
      resources under the key "UserDatabase". Any edits 
      that are performed against this UserDatabase are immediately 
      available for use by the Realm. --> 
     <Realm className="org.apache.catalina.realm.UserDatabaseRealm" 
       resourceName="UserDatabase"/> 
     </Realm> 

     <Host name="localhost" appBase="webapps" 
      unpackWARs="true" autoDeploy="true"> 

     <!-- SingleSignOn valve, share authentication between web applications 
      Documentation at: /docs/config/valve.html --> 
     <!-- 
     <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
     --> 

     <!-- Access log processes all example. 
      Documentation at: /docs/config/valve.html 
      Note: The pattern used is equivalent to using pattern="common" --> 
     <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
       prefix="localhost_access_log." suffix=".txt" 
       pattern="%h %l %u %t &quot;%r&quot; %s %b" /> 

     </Host> 
    </Engine> 
    </Service> 
</Server> 

的context.xml

<?xml version='1.0' encoding='utf-8'?> 
<!-- 
    Licensed to the Apache Software Foundation (ASF) under one or more 
    contributor license agreements. See the NOTICE file distributed with 
    this work for additional information regarding copyright ownership. 
    The ASF licenses this file to You under the Apache License, Version 2.0 
    (the "License"); you may not use this file except in compliance with 
    the License. You may obtain a copy of the License at 

     http://www.apache.org/licenses/LICENSE-2.0 

    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License. 
--> 
<!-- The contents of this file will be loaded for each web application --> 
<Context> 

    <!-- Default set of monitored resources --> 
    <WatchedResource>WEB-INF/web.xml</WatchedResource> 

    <!-- Uncomment this to disable session persistence across Tomcat restarts --> 
    <!-- 
    <Manager pathname="" /> 
    --> 

    <!-- Uncomment this to enable Comet connection tacking (provides events 
     on session expiration as well as webapp lifecycle) --> 
    <!-- 
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> 
    --> 

    <ResourceLink name="jdbc/SpringMvcDatabase" 
    global="jdbc/SpringMvcDatabase" 
    type="javax.sql.DataSource"/> 

</Context> 

而对于我使用的Spring应用程序:

spring-config.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:jee="http://www.springframework.org/schema/jee" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> 
    <context:annotation-config /> 
    <context:component-scan base-package="foo.bar"/> 

    <jee:jndi-lookup id="dbDataSource" 
        jndi-name="java:comp/env/jdbc/SpringMvcDatabase" 
        expected-type="javax.sql.DataSource" /> 

    <bean id="contactDao" class="foo.bar.dao.jdbc.xml.JdbcContactDao"> 
     <property name="dataSource"> 
      <ref local="dbDataSource"/> 
     </property> 
    </bean> 
</beans> 

我得到的错误是:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbDataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1488) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) 
    at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:71) 
    at foo.bar.JdbcContactDaoSample.main(JdbcContactDaoSample.java:16) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:601) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662) 
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307) 
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344) 
    at javax.naming.InitialContext.lookup(InitialContext.java:411) 
    at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154) 
    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:178) 
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95) 
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105) 
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201) 
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1547) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1485) 
    ... 16 more 

Process finished with exit code 1 

的web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
      version="2.5"> 
    <description>MySQL Test App</description> 
    <resource-ref> 
     <description>DB Connection</description> 
     <res-ref-name>jdbc/SpringMvcDatabase</res-ref-name> 
     <res-type>javax.sql.DataSource</res-type> 
     <res-auth>Container</res-auth> 
    </resource-ref> 
</web-app> 

JdbcContactDaoSample.java

package foo.bar; 

import foo.bar.dao.ContactDao; 
import org.springframework.context.support.GenericXmlApplicationContext; 


public class JdbcContactDaoSample { 

    public static void main(String[] args) { 
     GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml"); 

     ContactDao contactDao = ctx.getBean("contactDao", ContactDao.class); 

     //Find first name by id 
     System.out.println("First name for contact id 1 is: " + contactDao.findFirstNameById(1L)); 
    } 
} 

的Tomcat 7与无故障运行。 任何想法? 谢谢。

更新1:我使用的IDE是Intelli Idea 12 Ultimate(最新版本)。

+0

这是否与一些库(jar)有关,我必须添加到tomcat的lib目录中?我已经添加了com.mysql.jdbc.Driver jar,但是我想知道是否需要添加另一个库。 – skiabox

+0

是否必须添加属性文件(http:// blog。jonschneider.com/2009/05/fix-spring-based-jndi-lookup-can-see.html)链接建议? – skiabox

+0

任何想法家伙?我很努力寻找解决方案使用谷歌的这个错误,但我没有找到关于这个主题的答案。 – skiabox

回答

3

这样看来,无论是:

1)将tomcat JNDI上下文无法初始化自身由于错误(这是很少见的),或

2)Spring应用程序上下文越来越在Tomcat JNDI上下文被初始化之前加载。

首先,你确定没有Tomcat报告过的错误吗?您需要查看{tomcat}/logs/localhost.yyy.mm.dd.log,因为并非所有错误都写入控制台。

其次,你如何启动Tomcat并初始化Spring应用程序上下文?一种常见的方法是使用Spring的ContextLoaderListener,像这样(在web.xml中):

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

如果您使用的是一些自定义的技术来初始化春天,那么也许你正在这样做之前JNDI在Tomcat中被初始化?

要进一步排查您的情况,您应该使用单个servlet创建一个非Spring简单的Web应用程序。在这个servlet,你可以使用这样的代码:

Context initContext = new InitialContext(); 
Context envContext = (Context)initContext.lookup("java:/comp/env"); 
DataSource ds = (DataSource)envContext.lookup("jdbc/SpringMvcDatabase"); 
Connection conn = ds.getConnection(); 

如果这样的作品,那么你知道你的Tomcat/JNDI /数据源配置是否正确。

+0

我使用IntelliJ Idea,所以我从IDE启动Tomcat,但我首先将环境变量CATALINA_BASE(name)设置为/ Library/Tomcat(value)。 – skiabox

+0

然后,我会首先尝试启动没有Intellij的Tomcat,以确保您已正确配置jndi/datasource。有很多方法可以从Intellij启动和使用Tomcat。无论如何,底层的问题仍然是一样的:在Spring应用程序上下文加载之前,tomcat的JNDI没有被初始化。更具体地说,你如何初始化Spring应用程序上下文? – kaliatech

+0

检查上面的spring-config.xml以获取弹簧配置。 – skiabox

相关问题