使用ClassPathXmlApplicationContext的applicationContext.xml的正确路径

mar*_*osh 8 java spring integration-testing

我在WEB-INF/config/applicationContext.xml中使用applicationContext.xml工作web应用程序.现在我需要将一些测试工具实现为独立应用程序,它可以使用相同的applicationContext.xml,但是对于ClassPathXmlApplicationContext类的配置路径有问题.

我知道当我将applicationContext.xml复制到默认包(其中.java所在的位置)时,我可以使用ClassPathXmlApplicationContext("applicationContext.xml"),但这是必要的吗?

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AdminTool {

    private Logger log = Logger.getLogger(getClass());

    /** all below doesn't work - FileNotFoundException) **/
    private static final ApplicationContext ac = new ClassPathXmlApplicationContext("/WEB-INF/config/applicationContext.xml");
    private static final ApplicationContext ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
    private static final ApplicationContext ac = new ClassPathXmlApplicationContext("../config/applicationContext.xml");

    public static void main(String[] args) {
        new AdminTool();
    }

    public AdminTool() {
        log.debug(ac);
    }

}
Run Code Online (Sandbox Code Playgroud)

Sea*_*oyd 14

在本地测试场景中,您不在Jar中,因此您不需要基于Classpath的访问.请FileSystemXmlApplicationContext改用.

可能是这样的:

private static final ApplicationContext ac =
    new FileSystemXmlApplicationContext(
        "src/WEB-INF/config/applicationContext.xml"
    );
Run Code Online (Sandbox Code Playgroud)

(路径与执行目录相对)