Spring应用程序在配置文件中找不到数据源

时间:2012-05-10 09:11:25

标签: spring configuration datasource jndi

当我将Spring应用程序(Spring 2.5.6)部署到Tomcat(6.0)上时,启动失败,

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateSessionFactory' defined in class path resource [C.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined

我的web.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="[snip]" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>[snip]</display-name>
<welcome-file-list>
   [snip]
</welcome-file-list>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:All.xml</param-value>
</context-param>

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

<servlet>
    <servlet-name>[snip]</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>[snip]</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

All.xml导入许多配置文件:

<import resource="A.xml"/>
<import resource="B.xml"/>
<import resource="C.xml"/>
...

B.xml定义了一个数据源:

<jee:jndi-lookup id="dataSource" jndi-name="[snip]"/>

C.xml创建一个hibernate会话工厂,引用来自B.xml的数据源:

<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="mappingResources">
        <list>
            <value>[snip]</value>
            <value>[snip]</value>
        </list>
    </property>
    <property name="hibernateProperties">
  <props>
       [snip]
  </props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>

当我部署WAR文件时,会发生上述异常。我的问题是:

  1. 为什么?
  2. 为什么在我为测试弹簧配置的有效性而编写的JUnit测试中没有出现相同的异常?这是测试:

    @RunWith(SpringJUnit4ClassRunner.class)来 @ContextConfiguration(locations = {“/ All.xml”}) 公共类ImfSpringConfigurationTest {   [剪断]] }

  3. 注意:在JUnit测试中,我使用不同的All.xml文件将B.xml替换为定义没有jndi查找的数据源的文件,如下所示:

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName = "oracle.jdbc.driver.OracleDriver"
        [snip] />
    

    **

    原来,这个配置是正确的。这是部署另一个模块运行在一些相同的配置文件上引发异常,而不是这个部署过程。

1 个答案:

答案 0 :(得分:0)

尝试使用通配符运算符拉入顶级上下文:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/classes/spring*.xml</param-value>
</context-param>