目录
1、bean对象的三种创建方式
1)通过调用构造函数创建:
在默认情况下,准备好配置文件后,spring就会调用默认构造函数创建对象,如果不存在默认构造函数,则创建失败,如下图:
2)通过静态工厂创建bean对象
bean.xml:
<!-- 静态工厂创建 -->
<bean id="staticaccountService" class="factory.StaticBeanFactory" factory-method="getBean"></bean>
StaticBeanFactory:
package factory;
import rumen.AccountServiceImpl;
import rumen.IAccountService;
public class StaticBeanFactory {
public static IAccountService getBean() {
return new AccountServiceImpl();
}
}
Client:
package rumen;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//表现层
public class Client {
//获取Spring的核心容器,并根据id获取对象
public static void main(String[] args) throws ClassNotFoundException {
//1.获取Spring的核心容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
IAccountService as = (IAccountService) ac.getBean("staticaccountService");
System.out.println(as);
}
}
3)通过实例工厂创建对象
bean.xml:
<!-- 实例工厂创建 -->
<bean id="instanceFactory" class="factory.InstanceBeanFactory"></bean>
<bean id="instanceaccountService" factory-bean="instanceFactory" factory-method="getBean"></bean>
InstanceBeanFactory:
package factory;
import rumen.AccountServiceImpl;
import rumen.IAccountService;
public class InstanceBeanFactory {
public IAccountService getBean() {
return new AccountServiceImpl();
}
}
Client:
package rumen;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//表现层
public class Client {
//获取Spring的核心容器,并根据id获取对象
public static void main(String[] args) throws ClassNotFoundException {
//1.获取Spring的核心容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取对象
IAccountService as = (IAccountService) ac.getBean("instanceaccountService");
System.out.println(as);
}
}
2、bean对象的作用范围
它通过配置的方式来指定
配置的属性:bean的scope标签
属性:singleton:单例的。默认(常用)
prototype:多例的
request:请求范围
session:会话范围
global-session:全局会话范围
3、bean对象的生命周期
单例对象:
出生:容器创建时,对象出生
活着:只要容器存在,对象就一直存在
死亡:容器销毁,对象死亡
多例对象:
出生:每次使用时,容器会创建对象
活着:只要对象一直使用,就一直活着
死亡:当对象长时间不用,并且也没呀其他对象引用时,java的垃圾回收器回收