2013-05-16 32 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

相關問題