如何将本地文件名传递给ClassPathXmlApplicationContext?

时间:2012-11-01 12:39:59

标签: java spring classpath applicationcontext

“本地文件名”是指资源文件与类文件位于同一目录中。在下面的情况下,这是JUnitRunner.class文件。如果路径不以/'

开头,则Java的getResource()文件可以处理此问题

我无法弄清楚,如何做同样的ClassPathXmlApplicationContext构造函数?


package springtests;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JUnitRunner {

    private final static Logger log = LoggerFactory.getLogger(JUnitRunner.class);

    @Test
    public void test() throws URISyntaxException {

        String filename = "test01.xml";

        URL url = getClass().getResource(filename);


        File file = new File(url.toURI());
        log.info("File exists: {}", file.exists());

        try {
            new ClassPathXmlApplicationContext(filename);
        }
        catch(Exception e) {
            log.error("Can't load context", e);
        }

    }
}

输出如下

15:32:27,375 3    [main] INFO  springtests.JUnitRunner  - File exists: true
15:32:27,422 50   [main] INFO  org.springframework.context.support.ClassPathXmlApplicationContext  - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ee3aa7: startup date [Thu Nov 01 15:32:27 MSK 2012]; root of context hierarchy
15:32:27,475 103  [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader  - Loading XML bean definitions from class path resource [test01.xml]
15:32:27,477 105  [main] ERROR springtests.JUnitRunner  - Can't load context
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [test01.xml]; nested exception is java.io.FileNotFoundException: class path resource [test01.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

...

更新

XML文件与类文件位于同一文件夹中。从getResource()看到它的事实可以看出它。

4 个答案:

答案 0 :(得分:11)

我不明白你在问什么,但你试过了吗?

new ClassPathXmlApplicationContext("classpath*:test01.xml");

这将在test01.xml的所有类路径中搜索。您可以在Spring resources文档页面中阅读更多相关信息。

答案 1 :(得分:2)

所以,包springtests中的xml文件和AppContext的正确创建应该是

new ClassPathXmlApplicationContext("springtests/test01.xml");

答案 2 :(得分:0)

可能需要配置DocumentBuilderFactoryReference

示例:

@BeforeClass
public static void init() {
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
}

答案 3 :(得分:0)

可以从相对于当前Class的位置加载applicationcontext。

这就是你需要做的一切:

URL resourceUrl = JUnitRunner.class.getResource("test01.xml");
ApplicationContext applicationContext = new GenericXmlApplicationContext(
    new UrlResource(resourceUrl));