一般我们会采取两种方式将.xml文件载入,一种是ClassPathXmlApplicationContext,一种是FileSystemXmlApplicationContext。对于刚接触到spring的初学者而言,.xml文件放置在哪里,又如何被保证载入的是正确的,是有些费解的。接下来,用例子来说明这个问题。
在说明之前,我们需要先建立一个java project,引入了两个jar包,建立两个package,分别有相应的java类
在上图中,有四个位置(可能不止四个,因为每一个文件夹中都可以放置.xml文件)。
先来看一下,图中每个类的详细程序。
Action.java,这是一个interface
package com.fang.spring;
public interface Action {
public String execute(String str);
}
UpperAction.java,接口的实现类
package com.fang.spring;
public class UpperAction implements Action{
private String message;
public String getMessage() {
return message;
public void setMessage(String message) {
this.message = message;
Override
public String execute(String str) {
// TODO Auto-generated method stub
return (getMessage()+str).toUpperCase();
}
编写bean.xml
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> description>My first spring
编写测试类SimpleTest
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.fang.spring.Action;
public class SimpleTest {
public static void main(String\\[\\] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//ApplicationContext ctx = new ClassPathXmlApplicationContext("test/bean.xml");
//ApplicationContext ctx = new ClassPathXmlApplicationContext("com/fang/spring/bean.xml");
//ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");
//ApplicationContext ctx = new FileSystemXmlApplicationContext("src/bean.xml");
//ApplicationContext ctx = new FileSystemXmlApplicationContext("src/test/bean.xml");
//ApplicationContext ctx = new FileSystemXmlApplicationContext("src/com/fang/spring/bean.xml");
Action action = (Action) ctx.getBean("UpperAction");
System.out.println(action.execute(" Rod String"));
}
}
由于ClassPathXmlApplicationContext是从当前的classpath寻找bean.xml文件的,xml放置的位置有2、3、4,不能放在1的位置。
对应的载入程序如下:
位置2对应
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
位置3对应
ApplicationContext ctx ={color} new {color:#808080}ClassPathXmlApplicationContext({color}"com/fang/spring/bean.xml"
位置4对应
ApplicationContext ctx ={color} new {color:#808080}ClassPathXmlApplicationContext({color}"test/bean.xml"
而FileSystemXmlApplicationContext是通过系统文件从相对于当前工作目录被载入,所以可以放在1、2、3、4某一个位置,均可以找到。
对应的载入程序如下:
位置1对应
ApplicationContext ctx ={color} new {color:#808080}FileSystemXmlApplicationContext({color}"bean.xml"
位置2对应
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/bean.xml");
位置3对应
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/com/fang/spring/bean.xml");
位置4对应
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/test/bean.xml");
均能够运行正常。