1、FileSystemXmlApplicationContext
这个方法是从文件绝对路径加载配置文件,例如:
ApplicationContext ctx = new FileSystemXmlApplicationContext( "G:/Test/applicationcontext.xml ");
如果在参数中写的不是绝对路径,那么方法调用的时候也会默认用绝对路径来找,我测试的时候发现默认的绝对路径是eclipse所在的路径。
采用绝对路径的话,程序的灵活性就很差了,所以这个方法一般不推荐。
(如果要使用classpath路径,需要加入前缀classpath: )
关于FileSystemXmlApplicationContext这个路径有2总写法
- 有盘符的代表的是绝对路径,如 D:/wokespace/spring/WebRoot/WEB-INF/classes/xxx.xml。
- 没有盘符的代表的项目的根路径。比如放在Webroot的WEB-INF下面,路径可以写成"/WebRoot/WEB-INF/xxx.xml"
如果想要在FileSystemXmlApplicationContext读取classpath下面的文件,可以写成/WebRoot/WEB-INF/classes/xxx.xml,也可以写成classpath:xxx.xml,classpath代表的路径就是:/WebRoot/WEB-INF/classes/。
2、ClassPathXmlApplicationContext
这个方法是从classpath下加载配置文件(适合于相对路径方式加载),例如:
ApplicationContext ctx = new ClassPathXmlApplicationContext( "/applicationcontext.xml ");
该方法参数中classpath: 前缀是不需要的,默认就是指项目的classpath路径下面;这也就是说用ClassPathXmlApplicationContext时默认的根目录是在WEB-INF/classes下面,而不是项目根目录。这个需要注意!
3、XmlWebApplicationContext
专为web工程定制的方法,推荐Web项目中使用。例如:
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);