java 使用带有 Maven 结构的 @ContextConfiguration("/applicationContext.xml") “无法加载 ApplicationContext”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36288083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:13:07  来源:igfitidea点击:

"Failed to load ApplicationContext" using @ContextConfiguration("/applicationContext.xml") with Maven structure

javaspringmavenspring-test

提问by J. álvarez

I'm trying to run a JUnit Test using Spring but the console shows: Failed to load ApplicationContexterror. I'm using the Maven structure, and I have the applicationContext.xmlfile in src/main/resourcesfolder. I have read all the questions related and tried the solutions, but no success.

我正在尝试使用 Spring 运行 JUnit 测试,但控制台显示: 无法加载 ApplicationContext错误。我正在使用 Maven 结构,并且我在applicationContext.xml文件src/main/resources夹中有文件。我已经阅读了所有相关问题并尝试了解决方案,但没有成功。

Here is the folder structure.

这是文件夹结构

Here is the code:

这是代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class ConsultarProveedorPorLlave {

@Resource
private SessionFactory fabricaSesionPostgreSQL;

@Test
public void test()
{
    Session sesion = fabricaSesionPostgreSQL.openSession();
    Proveedor proveedor = (Proveedor) sesion.get(Proveedor.class, 1);
    assertNotNull("El proveedor no existe", proveedor);
    System.out.println("Proveedor: " + proveedor.getProveedor() + " - " + proveedor.getNombre() + " - " + proveedor.getEstado());
    sesion.close();
}

Here is the error trace:

这是错误跟踪:

java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fabricaSesionPostgreSQL' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ... 25 more Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:591) at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:603) at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:204) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1527) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1486) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ... 39 more Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:302) at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:576) ... 45 more

org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 在 org.eclipse.jdt。 internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 引起:org.springframework.beans.factory.BeanCreationException:在类路径资源 [applicationContext.xml] 中定义名称为“fabricaSesionPostgreSQL”的 bean 创建时出错:初始化豆子失败;嵌套异常是 org.springframework.beans.ConversionNotSupportedException:无法将 [java.lang.String] 类型的属性值转换为属性“dataSource”所需的类型 [javax.sql.DataSource];嵌套异常是 java.lang.IllegalStateException:无法将类型 [java.lang.String] 的值转换为所需的类型 [javax.sql。support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261) 在 org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) 在 org.springframework.test.context.cache.load. java:116) ... 25 导致:org.springframework.beans.ConversionNotSupportedException:无法将 [java.lang.String] 类型的属性值转换为属性“dataSource”所需的类型 [javax.sql.DataSource];嵌套异常是 java.lang.IllegalStateException:无法将 [java.lang.String] 类型的值转换为属性“dataSource”所需的类型 [javax.sql.DataSource]:

Here is the pom.xmlfile:

这是pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sacc</groupId>
<artifactId>sacc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
    <hibernate.version>4.3.8.Final</hibernate.version>
    <postgresql.version>9.1-901-1.jdbc4</postgresql.version>
    <junit.version>4.12</junit.version>
    <spring.version>4.2.5.RELEASE</spring.version>
</properties>
<dependencies>
    <!-- Hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <!-- Hibernate -->

    <!-- PostgreSQL -->
    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>${postgresql.version}</version>
    </dependency>
    <!-- PostgreSQL -->

    <!-- JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    <!-- JUnit -->

    <!-- Spring Framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument-tomcat</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jms</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc-portlet</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- Spring Framework -->
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Here is the applicationContext.xmlfile:

这是applicationContext.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:tx="http://www.springframework.org/schema/tx"
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-4.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

<bean id="fuenteDatosPostgreSQL"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5432/sacc" />
    <property name="username" value="postgres" />
    <property name="password" value="admin" />
</bean>
<bean id="fabricaSesionPostgreSQL"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate_postgresql.cfg.xml" />
    <property name="dataSource" value="fuenteDatosPostgreSQL" />
</bean>
<bean id="gestorTransaccionesPostgreSQL"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="fabricaSesionPostgreSQL" />
</bean>

<tx:annotation-driven transaction-manager="gestorTransaccionesPostgreSQL" />
<context:component-scan base-package="com" scoped-proxy="interfaces" />

回答by Aaron Kanter

Edit: based on your provided applicationContext.xml

编辑:根据您提供的 applicationContext.xml

<property name="dataSource" value="fuenteDatosPostgreSQL" />

<property name="dataSource" value="fuenteDatosPostgreSQL" />

needs to be

需要是

<property name="dataSource" ref="fuenteDatosPostgreSQL" />.

<property name="dataSource" ref="fuenteDatosPostgreSQL" />.

That way it looks for the object referenced by "fuenteDatosPostgreSQL" rather than the simply the String "fuenteDatosPostgreSQL".

这样它会查找“fuenteDatosPostgreSQL”引用的对象,而不是简单的字符串“fuenteDatosPostgreSQL”。

回答by Sajan Chandran

The exception clearly shows

异常清楚地表明

java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource':

java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [javax.sql.DataSource] for property 'dataSource':

When you referencebean you need to use refinstead you used value.

当你reference需要使用 bean 时,ref你使用了value.

<bean id="fabricaSesionPostgreSQL"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate_postgresql.cfg.xml" />
    <property name="dataSource" value="fuenteDatosPostgreSQL" />
</bean>

replace the line with

<property name="dataSource" ref="fuenteDatosPostgreSQL" />

回答by Xin1258

You can put your configuration into src/main/resourcesr and try use try @ContextConfiguration("classpath:applicationContext.xml") in your unit test.

您可以将配置放入 src/main/resourcesr 并尝试在单元测试中使用 try @ContextConfiguration("classpath:applicationContext.xml") 。