好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解SpringIOC容器中bean的作用范围和生命周期

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

singleton 单例的(默认) prototype 多例的 request 作用于web应用的请求范围 session 作用于web应用的会话范围 global-session 作用于集群环境的会话范围(全局会话范围)

测试:

?

1

2

<!-- 默认是单例的(singleton)-->

<bean id= "human" class = "com.entity.human" ></bean>

?

1

<bean id= "human" class = "com.entity.human" scope= "singleton" ></bean>

?

1

2

3

4

5

6

7

8

9

@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时

?

1

<bean id= "human" class = "com.entity.human" scope= "prototype" ></bean>

结果:

singleton和prototype的区别

如果bean属性设置为singleton时,当我们加载配置文件时对象已经被初始化 而如果使用prototype时,对象的创建是我们什么时候获取bean时什么时候创建对象

当设置为prototype时


当设置为singleton时

bean对象的生命周期

单例对象:

出生:当容器创建时对象出生 活着:只有容器还在,对象一直活着 死亡:容器销户,对象死亡 单例对象和容器生命周期相同

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

?

1

2

3

4

5

6

7

public void init(){

  system.out.println( "初始化..." );

}

 

public void destroy(){

  system.out.println( "销毁了..." );

}

?

1

2

3

<bean id= "person" class = "com.entity.person" scope= "singleton" init-method= "init" destroy-method= "destroy" >

   

   </bean>

测试类:

?

1

2

3

4

5

6

7

8

9

@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垃圾回收器回收对象

测试类:

?

1

2

3

4

5

6

7

8

9

@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作用范围和生命周期内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/weixin_45608165/article/details/113842753

查看更多关于详解SpringIOC容器中bean的作用范围和生命周期的详细内容...

  阅读:9次