bean的作用范围:
可以通过scope属性进行设置:
测试:
<!-- 默认是单例的(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的区别
当设置为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多例时
测试类:
@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(); }
结果:
总结:由于Spring容器不知道多例对象什么时候使用,什么时候能用完,只有我们自己知道,因此它不会轻易的把对象销毁,它会通过java垃圾回收器回收对象
到此这篇关于SpringIOC容器中bean的作用范围和生命周期的文章就介绍到这了,更多相关SpringIOC容器bean作用范围和生命周期内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。