Java项目:无法加载ApplicationContext

Byr*_*ron 33 junit spring unit-testing

我有一个Java项目,我正在编写一个简单的JUNIT测试用例.我已将applicatinoContext.xml文件复制到root java源目录中.我已经尝试了一些我在StackOverflow上阅读的推荐设置,但仍然得到相同的错误.这个错误是由于我的项目是一个java项目而不是一个Web项目,或者这甚至是否重要?我不确定我哪里出错了.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"C:/projs/sortation/src/main/java/applicationContext.xml"})
// Also tried these settings but they also didnt work,
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})
//@ContextConfiguration("classpath:applicationContext.xml")
@Transactional
public class TestSS {

    @Autowired
    private EmsDao dao;

    @Test
    public void getSites() {

        List<String> batchid = dao.getList();

        for (String s : batchid) {
            System.out.println(s);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

FrV*_*aBe 27

看起来你正在使用maven(src/main/java).在这种情况下将applicationContext.xml文件放在src/main/resources目录中.它将被复制到类路径目录中,你应该能够访问它

@ContextConfiguration("/applicationContext.xml")
Run Code Online (Sandbox Code Playgroud)

Spring-Documentation:普通路径(例如"context.xml")将被视为来自定义测试类的同一包中的类路径资源.以斜杠开头的路径被视为完全限定的类路径位置,例如"/org/example/config.xml".

因此,在引用类路径的根目录中的文件时添加斜杠非常重要.

如果使用绝对文件路径,则必须使用'file:C:...'(如果我正确理解文档).