这篇文章主要为大家详细介绍了SpringIOC容器中bean的作用范围是什么,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:
bean的作用范围:
可以通过scope属性进行设置:
singleton 单例的(默认)
prototype 多例的
request 作用于web应用的请求范围
session 作用于web应用的会话范围
global-session 作用于集群环境的会话范围(全局会话范围)
测试:
<!-- 默认是单例的(singleton)-->
<bean id="human" class="com.entity.Human"></bean>
<bean id="human" class="com.entity.Human" scope="singleton"></bean>
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//获取Spring容器中的bean对象,通过id和类字节码来获取
Human human = applicationContext.getBean("human", Human.class);
Human human1 = applicationContext.getBean("human", Human.class);
System.out.println(human==human1);
}
结果:
将scope属性设置为prototype时
<bean id="human" class="com.entity.Human" scope="prototype"></bean>
结果:
singleton和prototype的区别
如果bean属性设置为singleton时,当我们加载配置文件时对象已经被初始化
而如果使用prototype时,对象的创建是我们什么时候获取bean时什么时候创建对象
当设置为prototype时
当设置为singleton时
bean对象的生命周期
单例对象:
出生:当容器创建时对象出生
活着:只有容器还在,对象一直活着
死亡:容器销户,对象死亡
单例对象和容器生命周期相同
测试:
先设置属性init-method和destroy-method,同时在person类中写入两个方法进行输出打印
public void init(){
System.out.println("初始化...");
}
public void destroy(){
System.out.println("销毁了...");
}
<bean id="person" class="com.entity.Person" scope="singleton" init-method="init" destroy-method="destroy">
</bean>
测试类:
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ClassPathXmlApplicationContext Context=new ClassPathXmlApplicationContext("bean.xml");
// //获取Spring容器中的bean对象,通过id和类字节码来获取
Person person = Context.getBean("person", Person.class);
//销毁容器
Context.close();
}
结果:
总结:单例对象和容器生命周期相同
当属性改为prototype多例时
出生:当我们使用对象时spring框架为我们创建
活着:对象只要是在使用过程中就一直活着
死亡:当对象长时间不用,且没有别的对象应用时,由java垃圾回收器回收对象
测试类:
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ClassPathXmlApplicationContext Context=new ClassPathXmlApplicationContext("bean.xml");
// //获取Spring容器中的bean对象,通过id和类字节码来获取
Person person = Context.getBean("person", Person.class);
//销毁容器
Context.close();
}
结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。