Spring容器
Spring有两个核心接口:BeanFactory和ApplicationContext,其中ApplicationContext是BeanFactory的子接口。ApplicationContext的两个常用实现类是ClassPathXmlApplicationContext和FileSystemXmlApplicationContext,具体依赖关系见图1。它们都可以代表Spring容器,Spring容器是生成Bean实例的工厂,并管理容器中的Bean。
图1. Spring容器依赖关系图
1.使用BeanFactory
- 项目代码结构如图2所示:
图2. BeanFactory使用示例项目结构图
- 其中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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="org.crazyit.app.Dog">
<property name="name" value="旺财"/>
</bean>
</beans>
- Dog类的代码如下:
package org.crazyit.app;
public class Dog
{
private String name;
private int age;
public void setName(String name)
{
System.out.println("--setName--");
this.name = name;
}
@Override
public String toString()
{
return "Dog [name=" + name + ", age=" + age + "]";
}
}
- SpringTest类的代码如下:
package lee;
import org.crazyit.app.Dog;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class SpringTest
{
public static void main(String[] args)
{
// 搜索类加载路径下的beans.xml文件创建Resource对象
ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory ctx = new XmlBeanFactory(resource);
System.out.println("--------");
}
}
- 运行SpringTest类结果如下
- 然后在SpringTest类的main方法最下方加入如下代码
Dog dog = ctx.getBean("dog",Dog.class);
- 再次运行SpringTest类的结果如下
对比上述两个运行结果发现BeanFactory加载配置文件的时候不会为配置文件中的singleton Bean创建对象,而是在获取(使用)对象的时候才去创建对象。
2.使用ApplicationContext
- 此项目的实例代码除了SpringTest类不一样外其余与BeanFactory使用实例代码全部相同,此处不再赘述,仅给出不一样的代码
- SpringTest类的代码如下:
package lee;
import org.crazyit.app.Dog;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest
{
public static void main(String[] args)
{
BeanFactory ctx = new ClassPathXmlApplicationContext("beans.xml");
System.out.println("------------------------");
}
}
- 运行SpringTest类结果如下
观察上述运行结果发现ApplicationContext·会与初始化容器中所有的singleton Bean。
-
总结
- ApplicationContext会预初始化容器中所有的singleton Bean;
- BeanFactory默认延迟初始化容器中的Bean