Spring加载applicationContext.xml实现spring容器管理的几种方式
package com.etc.test; import org.junit.Test; 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.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import com.etc.pojo.AX; import com.etc.pojo.Person; public class TestDemo { @Test public void test01() { //传统创建对象的实现方式 Person p = new Person(); p.setPname("张三"); System.out.println(p); AX ax = new AX(); ax.setAname("木斧"); p.setAx(ax); System.out.println(p); } @Test public void test02() { //实现方式一 加载applicationContext.xml会实例化,会立即加载类路径 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); // Person p=(Person)ac.getBean("person"); // AX ax=(AX)ac.getBean("ax"); // ax.setAname("木斧"); // // p.setPname("李四"); // p.setAx(ax); // System.out.println(p); } @Test public void test03() { //实现方式二 加载applicationContext.xml不会去实例化,不会立即加载类路径 Resource rs=new ClassPathResource("applicationContext.xml"); BeanFactory ac=new XmlBeanFactory(rs); // Person p=(Person)ac.getBean("person"); // AX ax=(AX)ac.getBean("ax"); // ax.setAname("木斧"); // // p.setPname("李四"); // p.setAx(ax); // System.out.println(p); } @Test public void test04() { //实现方式三 加载applicationContext.xml不会去实例化,不会立即加载类路径 ResourcePatternResolver rpr=new PathMatchingResourcePatternResolver(); Resource rs=rpr.getResource("applicationContext.xml"); BeanFactory ac=new XmlBeanFactory(rs); } }