微服务 教程
1085个小节阅读:195.6k
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Spring通过配置<bean>
中的scope
属性设置对象的创建策略,共有五种创建策略:
singleton:单例,默认策略。整个项目只会创建一个对象,通过<bean>
中的lazy-init
属性可以设置单例对象的创建时机:
lazy-init="false"(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
lazy-init="true":延迟创建,第一次使用Bean对象时才会创建。
配置单例策略:
xxxxxxxxxx
<!-- <bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" lazy-init="true"></bean>-->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="singleton" lazy-init="false"></bean>
测试单例策略:
xxxxxxxxxx
// 为Bean对象的类添加构造方法
public StudentDaoImpl2(){
System.out.println("创建StudentDao!!!");
}
public void t2(){
// 创建Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
// 从容器获取对象
StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
StudentDao studentDao3 = (StudentDao) ac.getBean("studentDao");
System.out.println(studentDao1.hashCode());
System.out.println(studentDao2.hashCode());
System.out.println(studentDao3.hashCode());
}
prototype:多例,每次从容器中获取时都会创建对象。
xxxxxxxxxx
<!-- 配置多例策略 -->
<bean id="studentDao" class="com.itbaizhan.dao.StudentDaoImpl2" scope="prototype"></bean>
request:每次请求创建一个对象,只在web环境有效。
session:每次会话创建一个对象,只在web环境有效。
gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
1. Spring配置文件中,<bean>
中的scope
属性值为表示该对象是单例的
A singleton
B prototype
C request
D session
2. Spring单例对象设置lazy-init="false"
表示它的创建时机为
A 第一次使用对象时创建
B 每次从容器中获取时都会创建
C 在容器启动时会创建
D 每次请求时创建
1=>A 2=>C