spring学习之bean的作用域

15次阅读

共计 2379 个字符,预计需要花费 6 分钟才能阅读完成。

scope

包括 Singleton、Prototype、Request, Session, Application, WebSocket,这边主要讲常用的 Singleton 和 Prototype。

Singleton

当定义一个 bean 为单例对象时,IoC 容器只创建该 bean 对象的一个实例。这个 bean 对象存储在容器的缓存(map)中,后续的对该 bean 的引用,都是从缓存中取(map.get)。
这个单例跟设计模式的单例模式是不一样的。spring 的单例是指在容器中仅有一个实例,而设计模式的单例是在 JVM 进程中仅有一个实例。

Prototype

当需要每次 getBean 的时候,都返回不同的实例,这个时候,就需要用 Prototype。

Singleton 和 Prototype

如果 bean 是无状态的,就需要用 Singleton,如果是有状态的,就用 Prototype。
对于 Singleton 的 bean,spring 容器会管理他的整个生命周期。
对于 Prototype 的 bean,spring 容器不管理他的整个生命周期,尽管初始化的方法会被调用,但是与 scope 的范围无关。而且容器关闭时不会调用销毁方法。

示例

XML

XML 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="singletonBean" class="com.learn.beanScope.SingletonBean" scope="singleton"/>
    <bean id="prototypeBean" class="com.learn.beanScope.PrototypeBean" scope="prototype"/>

</beans>

测试代码

@Test
public void test() {ApplicationContext app = new ClassPathXmlApplicationContext("beanScope.xml");
    SingletonBean singletonBean1 = app.getBean("singletonBean",SingletonBean.class);
    SingletonBean singletonBean2 = app.getBean("singletonBean",SingletonBean.class);
    PrototypeBean prototypeBean1 =app.getBean("prototypeBean",PrototypeBean.class);
    PrototypeBean prototypeBean2 =app.getBean("prototypeBean",PrototypeBean.class);
    System.out.println(singletonBean1);
    System.out.println(singletonBean2);
    System.out.println(prototypeBean1);
    System.out.println(prototypeBean2);
}

运行结果:

作用域为 Singleton 的时候,可以看出,从容器中取了两次,地址是一样的,所以是同一个 bean。
作用域为 Prototype 的时候,可以看出,从容器中取了两次,地址是不一样的,所以不是同一个 bean。

注解

MyConfig

@Configuration
public class MyConfig {
    @Bean
    @Scope("prototype")
    public PrototypeBean prototypeBean() {return new PrototypeBean();
    }

    @Bean
    @Scope("singleton")
    public SingletonBean singletonBean() {return new SingletonBean();
    }
}

测试代码

@Test
public void test() {ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
    SingletonBean singletonBean1 = app.getBean("singletonBean",SingletonBean.class);
    SingletonBean singletonBean2 = app.getBean("singletonBean",SingletonBean.class);
    PrototypeBean prototypeBean1 =app.getBean("prototypeBean",PrototypeBean.class);
    PrototypeBean prototypeBean2 =app.getBean("prototypeBean",PrototypeBean.class);
    System.out.println(singletonBean1);
    System.out.println(singletonBean2);
    System.out.println(prototypeBean1);
    System.out.println(prototypeBean2);
}

运行结果:

结果同 XML。

正文完
 0