默认情况下,Spring 的 IoC 容器创建的 Bean 对象是单例的(单例模式)
默认情况下,Bean 对象的创建是在初始化 Spring 上下文的时候就完成的
package org.qiu.spring.bean;
/**
* @author 秋玄
* @version 1.0
* @email [email protected]
* @project Spring
* @package org.qiu.spring.bean
* @date 2022-11-09-11:27
* @since 1.0
*/
public class SpringBean {
}
@Test
public void testBeanScope(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
SpringBean springBean1 = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean1);
SpringBean springBean2 = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean2);
SpringBean springBean3 = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean3);
}
运行结果:
如果想让 Spring 的 Bean 对象以多例的形式存在,可以在 bean 标签中指定 scope 属性的值为:prototype,这样 Spring 会在每一次执行 getBean() 方法的时候创建 Bean 对象,调用几次则创建几次
public class SpringBean {
public SpringBean(){
System.out.println("SpringBean 无参数构造方法执行了......");
}
}
运行结果:
这一次在初始化 Spring 上下文的时候,并没有创建 Bean 对象
没有指定 scope 属性时,默认是 singleton 单例的
scope 属性的值不止两个,它一共包括8个选项:
singleton:默认的,单例
prototype:原型。每调用一次 getBean() 方法则获取一个新的 Bean 对象。或每次注入的时候都是新对象
request:一个请求对应一个 Bean。仅限于在 WEB 应用中使用
session:一个会话对应一个 Bean。仅限于在 WEB 应用中使用
global session:portlet 应用中专用的。如果在 Servlet 的 WEB 应用中使用 global session 的话,和session一个效果(portlet 和 servlet 都是规范。servlet运行在servlet容器中,例如Tomcat,portlet 运行在 portlet 容器中)
application:一个应用对应一个 Bean。仅限于在 WEB 应用中使用
websocket:一个 websocket 生命周期对应一个 Bean。仅限于在 WEB 应用中使用
自定义 scope:很少使用
自定义一个 Scope,线程级别的 Scope,在同一个线程中,获取的 Bean 都是同一个,跨线程则是不同的对象:(以下内容作为了解)
当 scope 为 singleton 时,多个线程共享一个 Bean
@Test
public void testThreadScope(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
SpringBean springBean = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean);
// 启动一个线程
new Thread(new Runnable() {
@Override
public void run() {
SpringBean springBean1 = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean1);
}
}).start();
}
运行结果:
第一步:自定义 Scope(实现 Scope 接口)
Spring 内置了线程范围的类:org.springframework.context.support.SimpleThreadScope,可以直接用
第二步:将自定义的 Scope 注册到 Spring 容器中
使用Scope
测试
@Test
public void testThreadScope(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
SpringBean springBean = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean);
// 启动一个线程
new Thread(new Runnable() {
@Override
public void run() {
SpringBean springBean1 = applicationContext.getBean("springBean", SpringBean.class);
System.out.println(springBean1);
}
}).start();
}
运行结果:
一 叶 知 秋,奥 妙 玄 心