Right path to applicationContext.xml using ClassPa

2019-03-11 08:39发布

I have working web-application with applicationContext.xml in WEB-INF/config/applicationContext.xml. Now i need to implement some testing tool as standalone application, that can use the same applicationContext.xml, but have problem with path to config for ClassPathXmlApplicationContext class.

I know that when i copy applicationContext.xml to default package (where .java resides) i can use ClassPathXmlApplicationContext("applicationContext.xml"), but is this necessary ?

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);
    }

}

5条回答
爷、活的狠高调
2楼-- · 2019-03-11 09:17
private static final ApplicationContext ac =
    new FileSystemXmlApplicationContext(
        "/WEB-INF/config/applicationContext.xml"
    );
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-11 09:21

please go to property>Java Build Path>Source of your project check the classpath and add the directory before WEB-INF in the classpath. definitely it's work

查看更多
Luminary・发光体
4楼-- · 2019-03-11 09:25
private static final ApplicationContext ac =
new FileSystemXmlApplicationContext(
    "/WEB-INF/config/applicationContext.xml"
);
查看更多
【Aperson】
5楼-- · 2019-03-11 09:32

This is the reason why I prefer to put all configuration files in classes folder. In fact, using Maven, you can put all these files in src/main/resources. Then, in your test files you can access as 'classpath:applicationContext.xml'.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-03-11 09:40

In a local test scenario, you are not inside a Jar, so you don't need Classpath-based access. Use FileSystemXmlApplicationContext instead.

Probably something like this:

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

(paths are relative from the execution directory)

查看更多
登录 后发表回答