Spring之容器

1.创建容器

注:以下两种方式都可以同时加载多个配置文件,配置文件用逗号隔开
(1)加载类路径下的配置文件

ApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");

(2)加载文件系统下的配置文件

ApplicationContext ctx = new FileSystemXmlApplicationContext("F:\\reusable_code_templates\\Spring-Study\\spring-demo\\src\\main\\resources\\applicationContext.xml");

2.获取bean

(1)根据标签的id属性获取bean

People people = (People) ctx.getBean("people");

(2)根据标签的class属性获取bean

People people = ctx.getBean(People.class);

3.容器类层次结构

Spring之容器_第1张图片

4.BeanFactory

 		Resource resource = new ClassPathResource("applicationContext.xml");
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        People people = (People) beanFactory.getBean("people");
        System.out.println(people);

注:BeanFactory创建完毕之后,所有的bean均为延迟加载。如果想使ApplicationContext接口有bean延迟加载的效果,需要在xml文件中标签的lazy-init属性设为true

你可能感兴趣的:(Spring,spring,java,后端)