1、ApplicationContext 应用上下文容器取
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml");
当这句代码被执行,spring-config.xml文件中配置的bean就会被实例化。(但要注意bean的生命周期要为singleton),也就是说,不管没有getBean(),使用上下文容器获取bean,就会实例化该bean。
2、Bean工厂容器取
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
这句代码被执行,spring-config.xml文件中配置的bean不会被实例化,即光实例化容器,并不会实例化bean
而是在执行以下代码时才会被实例化,即使用bean的时候:
factory.getBean("beanId");
验证:
1、创建一个类LittleBall,重写该类的构造方法,打印一行日志。
public class LittleBall implements GirlsInterface{/** * 重写构造函数,输出信息,来确定bean初始化时间 */ public LittleBall(){ System.out.println("Hello, I am little ball! I am very beautiful!"); } }
2、编写spring配置文件spring-beans.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <bean id = "littleBall" class="serviceImpl.LittleBall"></bean> </beans>
3、编写main方法测试:
public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-beans.xml"); BeanFactory controllerFactory = new XmlBeanFactory(new ClassPathResource("spring-beans.xml")); LittleBallController littleBallController = (LittleBallController)controllerFactory.getBean(LittleBallController.class); }
结果
1、在ApplicationContext ac = new ClassPathXmlApplicationContext("spring-beans.xml");执行时候,打印了"Hello, I am little ball! I am very beautiful!"
2、在controllerFactory.getBean(LittleBallController.class);执行时候,打印了"Hello, I am little ball! I am very beautiful!"