400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

SpringIOC容器中bean的作用范围是什么-创新互联

这篇文章主要为大家详细介绍了SpringIOC容器中bean的作用范围是什么,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:

创新互联是专业的北戴河网站建设公司,北戴河接单;提供成都网站设计、成都网站制作、外贸网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行北戴河网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

bean的作用范围:
可以通过scope属性进行设置:

测试:


@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);
 }

结果:

SpringIOC容器中bean的作用范围是什么

将scope属性设置为prototype时

  

结果:

SpringIOC容器中bean的作用范围是什么

singleton和prototype的区别

当设置为prototype时

SpringIOC容器中bean的作用范围是什么
SpringIOC容器中bean的作用范围是什么

当设置为singleton时

SpringIOC容器中bean的作用范围是什么

bean对象的生命周期

单例对象:

测试:
先设置属性init-method和destroy-method,同时在person类中写入两个方法进行输出打印

 public void init(){
  System.out.println("初始化...");
 }

 public void destroy(){
  System.out.println("销毁了...");
 }

   
  

测试类:

@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();
 }

结果:

SpringIOC容器中bean的作用范围是什么

总结:单例对象和容器生命周期相同

当属性改为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();
 }

结果:

SpringIOC容器中bean的作用范围是什么

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联网站建设公司,。


分享标题:SpringIOC容器中bean的作用范围是什么-创新互联
本文链接:http://mbwzsj.com/article/ccoiji.html

其他资讯

让你的专属顾问为你服务