这篇文章记录BeanFactory和ApplicationContext创建bean的方法。
文章具体内容有:
- BeanFactory
- ApplicationContext
在初学Spring的IoC过程中,我们需要通过BeanFactory创建bean来了解IoC管理bean的过程,IoC创建bean的实现过程一般为:
- 编写类文件
- xml配置bean
- BeanFactory生成bean
1)首先编写类文件User
package lzgsea.bean;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2)编写bean的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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="lzgsea.bean.User"></bean>
</beans>
3.1)BeanFactory创建bean实现方式
XmlBeanFactory是BeanFactory的实现类,目前XmlBeanFactory已经过期,不推荐使用
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
User user = (User)beanFactory.getBean("user");
System.out.println(user);
3.2)ApplicationContext创建bean实现方式
ApplicationContext是XmlBeanFactory的子接口,ClassPathXmlApplicationContext是ApplicationContext的实现类,现在推荐使用ClassPathXmlApplicationContext替代XmlBeanFactory创建bean
ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) act.getBean("user");
System.out.println(user);
ApplicationContext提供了更多企业级特性,常用的实现类主要有三个:
ClassPathXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径FileSystemXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,XML文件路径使用Ant匹配,容器会从 CLASSPATH 中搜索 bean 配置文件。
Ant有三种匹配方式:
? : 匹配文件名中的一个字符
* :匹配任意字符
** :匹配多层路径
上文创新ClassPathXmlApplicationContext对象也可写成:
//扫描所有.xml文件
ApplicationContext act = new ClassPathXmlApplicationContext("*.xml");
WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。