Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么Spring的@ContextConfiguration在给定一个不存在的文件时运行?_Java_Spring - Fatal编程技术网

Java 为什么Spring的@ContextConfiguration在给定一个不存在的文件时运行?

Java 为什么Spring的@ContextConfiguration在给定一个不存在的文件时运行?,java,spring,Java,Spring,我正在调试某人的java,并试图弄清楚spring配置文件是否正确加载。这一点很复杂,因为Spring似乎会默默地忽略不存在的文件。例如,以下各项运行正常: import org.springframework.test.context.*; import org.junit.runner.*; import org.junit.Test; import org.springframework.test.context.junit4.*; @ContextConfiguration(locat

我正在调试某人的java,并试图弄清楚spring配置文件是否正确加载。这一点很复杂,因为Spring似乎会默默地忽略不存在的文件。例如,以下各项运行正常:

import org.springframework.test.context.*;
import org.junit.runner.*;
import org.junit.Test;
import org.springframework.test.context.junit4.*;

@ContextConfiguration(locations={"classpath:I_DONT_EXIST.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class Test3 {
    public static void main(String [] args){
        System.out.println("Hello World");
    }

    @Test
    public void testSomething() {
    }
}

尽管指定的文件I_DONT_EXIST.xml在任何地方都不存在。有没有办法修改它,这样如果指定的文件不存在,运行时就会抱怨?

Spring会抱怨缺少上下文xml文件

我不确定您是如何使用粘贴的类的,但为了启动spring上下文以在JUnit framework上执行测试,您可以如下注释您的类:

@ContextConfiguration(locations={"classpath:I_DONT_EXIST.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class Test2 {
    public static void main(String [] args){
        System.out.println("Hello World");
    }

    @Test
    public void testSomething() {
    }
}
当尝试作为JUnit测试执行时,这将引发以下异常:

Caused by: java.io.FileNotFoundException: class path resource [I_DONT_EXIST.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) ~[org.springframework.core-3.2.4.RELEASE.jar:3.2.4.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ~[org.springframework.beans-3.2.4.RELEASE.jar:3.2.4.RELEASE]

我会编辑这个问题,删除所有对汇编的引用。在编译时检查资源是没有意义的。您是运行该类还是将其作为测试用例运行?main方法没有对@ContextConfiguration或@RunWith执行任何操作,它只是运行类并用它来完成。不,我没有得到那个异常。我编辑了OP以反映您的答案,但它仍然毫无怨言地运行。奇怪,您是如何运行代码的?如果您只是执行它,它将不会启动任何spring上下文,您需要将其作为JUnit测试运行。啊,没关系,我是以类的形式运行它的,必须将其作为JUnit测试用例运行。谢谢你的帮助