Spring 读取XML配置文件的两种方式

时间:2022-05-09 01:35:35
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestAction { public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Action bean = (Action) ctx.getBean("theAction");
System.out.println(bean.execute("Rod"));
}
}

方式一

这种方式的缺点是,

ClassPathXmlApplicationContext  构造函数中的参数不能是文件所在的绝对路径;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; public class TestAction { public static void main(String[] args) throws FileNotFoundException {
Resource is = new FileSystemResource("E:\\Users\\panteng\\Workspaces\\MyEclipse 10\\mySpring\\src\\applicationContext.xml");
BeanFactory factory = new XmlBeanFactory((Resource) is);
Action bean = (Action) factory.getBean("theAction");
System.out.println(bean.execute("Rod"));
}
}

方式二

这种方式可以弥补第一种方式的缺点,建议使用第二种!