原始的 BeanFactory 无法支持 Spring 的许多插件,例如 AOP,Web 等等。
ApplicationContext 由 BeanFactory 派生,既能提供 BeanFactory 的所有功能,也能提供其他功能,例如 AOP,Web 等等。
假设有如下的配置文件用来配置一个 Student 的 Bean,student.xml:
<bean id = "student" class="Student">
<property name="name" value="Tom" />
<property name="age" value="18" />
</bean>
如何通过 BeanFactory 来生成对象?
BeanFactory f = new XMLBeanFactory(new FileSystemResource("student.xml"));
Student s = f.getBean("student");
注意:BeanFactory 生成 Bean 是延时加载的。如果 Bean 的某一个属性没有注入,例如 address,直至第一次 getBean() 时才会抛出异常。
如何通过 ApplicationContext 来生成对象?
ApplicationContext c = new ClassPathXmlApplicationContext("student.xml");
Student s = c.getBean("student");
注意:ApplicationContext 生成 Bean 不是延时加载的。在初始化自身时检查所有依赖属性是否注入。