ApplicationContext的三个常用实现类
ClassPathXmlApplicationContext
:它 可以加载类路径下的配置文件
FileSystemXmlApplicationContext
:它可以加载键盘任意路径下的配置文件(必须有访问权限)
AnnotationConfigApplicationContext
:它是用于读取注解创建容器
核心容器的两个接口引出的问题
ApplicationContext
:它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说一读取完配置文件马上就创建配置文件中配置的对象。(单例对象使用)
BeanFactory
:创建对象采用的策略是延迟加载的方式,也就是说,什么时候根据id获取了对象,什么时候才真正的创建对象。(多例对象使用)
参考 解释
spring对bean的管理细节
创建bean的三种方式
使用默认构造函数创建
使用默认构造函数创建,在Spring的配置文件中使用bean标签,其没有其他属性和标签时采用的就是默认构造函数创建bean对象,此时如果类中没有默认的构造函数,则对象无法创建。
<bean id="accountService" class="com.lg.service.impl.AccountServiceImpl"></bean>
使用普通工厂类中的方法创建对象
使用某个类中的方法创建,并存入Spring容器
<bean id="instanceFactory" class="com.lg.factory.InstanceFactory"/>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"/>
/**
* 模拟一个工厂类(该类存在jar包中无法通过修改源码的方式来提供默认构造函数)
*/
public class InstanceFactory {
public AccountService getAccountService(){
System.out.println("通过InstanceFactory创建的!");
return new AccountServiceImpl();
}
}
使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入Spring容器)
<bean id="accountService" class="com.lg.factory.StaticFactory" factory-method="getAccountService"/>
/**
* 模拟一个工厂类(该类存在jar包中无法通过修改源码的方式来提供默认构造函数)
*/
public class StaticFactory {
public static AccountService getAccountService(){
System.out.println("通过StaticFactory创建的!");
return new AccountServiceImpl();
}
}
目录结构
bean的作用范围
bean标签的scope属性
作用:用于指定Bean的作用范围
singleton:
(单例,默认值)
prototype:
(多例)
request:
作用于WEB应用的请求范围
session:
作用于WEB应用的会话范围
global-session:作用于集群环境的会话范围(全局会话范围),不是集群环境时就是session。
bean对象的生命周期
单例对象
出生:当容器创建时对相出生
活着:只要容器存在对象就活着
死亡:容器销毁,对象死亡
总结:单例对象的生命周期和容器相同
<bean id="accountService" class="com.lg.service.impl.AccountServiceImpl"scope="singleton" init-method="initMethod" destroy-method="desMethod"></bean>
public class AccountServiceImpl implements AccountService {
/*public AccountServiceImpl(){
System.out.println("对象创建了!");
}*/
@Override
public void saveAccount() {
System.out.println("service中的方法执行了!");
}
public void initMethod() {
System.out.println("对象初始化了!");
}
public void desMethod() {
System.out.println("对象销毁了!");
}
}
public class Client {
/**
* 获取Spring的Ioc核心容器,并根据Id获取对象
* @param args
*/
public static void main(String[] args) {
//AccountService as = new AccountServiceImpl();
//1、获取核心容器对象
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ClassPathXmlApplicationContext as = new ClassPathXmlApplicationContext("bean.xml");
//根据beanId获取对象
AccountService as1 = (AccountService) as.getBean("accountService");
//System.out.println(as);
as1.saveAccount();
as.close();
}
}
多例对象
出生:当我们使用对象时Spring框架为我们创建
活着:对象只要在使用就一直活着
死亡:容器销毁,对象死亡
总结:当对象长时间不使用,由Java垃圾回收机制回收
<bean id="accountService" class="com.lg.service.impl.AccountServiceImpl"scope="prototype" init-method="initMethod" destroy-method="desMethod"></bean>