1.Bean创建的两种规则:
BeanFactory:提供一种延迟加载思想来创建Bean对象。在调用对象的时候加载Bean对象。
ApplicationContext:提供一种立即加载思想来创建Bean对象。只要一解析完配置文件,立马加载Bean对象。
2.Bean的三种创建方式:
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
(1)调用默认无参构造函数创建。默认情况下,如果类中没有默认无参构造函数,则创建失败,会报异常。(平时所用)
<bean id="customerService" class="com.iafei.service.impl.CustomerServiceImpl"></bean>
CustomerService cs1=(CustomerService) ac.getBean("customerService");
(2)使用静态工厂中的方法创建对象。需要使用bean标签factory-method属性,指定静态工厂中创建对象的方法。
public class StaticFactory {
public static CustomerService getCustomerService() {
return new CustomerServiceImpl();
}
}
<bean id="staticCustomerService" class="com.iafei.factory.StaticFactory" factory-method="getCustomerService"></bean>
CustomerService cs2=(CustomerService) ac.getBean("staticCustomerService");
(3)使用实例工厂中的方法创建。
public class InstanceFactory {
public CustomerService getCustomerService() {
return new CustomerServiceImpl();
}
}
<bean id="instanceFactory" class="com.iafei.factory.InstanceFactory"></bean>
<bean id="instanceCustomerService" factory-bean="instanceFactory" factory-method="getCustomerService"></bean>
CustomerService cs3=(CustomerService) ac.getBean("instanceCustomerService");
3.Bean的取值范围
可以通过配置的方式来调整作用范围。配置的属性:bean标签的scope属性。
属性的取值:
singleton:单例的(默认值)
prototype:多例的(当我们让spring接管Struts2的action时,必修是此选项)
request:作用范围是一次请求和当前请求的转发
session:作用范围是一次会话
globalsession:作用范围是一次全局会话
4.Bean的生命周期
单例:
(1)出生:容器创建,对象出生。
(2)存活:容器在,对象在。
(3)死亡:容器销毁,对象消亡。
多例:
(1)出生:每次使用时,创建对象。
(2)存活:只要对象在使用中,就一直存活。
(3)死亡:对象长时间不使用,并且也没有别的对象引用,由java的垃圾回收器回收。