Spring 框架学习(六)---- Bean作用域

Spring 框架学习(六)---- Bean作用域


  经过前面的学习,我们可以知道bean是存在作用域的。

  从spring的官方文档中发现spring支持六种作用域,我们只需要重点认识singleton、protoType即可,后面的作用域都是于web框架相关的。


在这里插入图片描述


一、singleton(单例模式)


在这里插入图片描述


  就和图中的一样,如果bean的作用域为singleton,那么在IOC容器中只有每个bean只有一个唯一的实例被创建。

我们通过代码来认识一下,bean的单例模式

bean的作用域默认是singleton,我们也可以手动通过在xml的bean中scope进行设置。

<?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="user" class="pojo.User" scope="singleton"/>

</beans>

根据同一个bean 获取两次实例,查看实例是否相同

    public static void main(String[] args) {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user",User.class);
        System.out.println(user1==user2);
    }

查看运行结果

在这里插入图片描述

说明 这个Bean的作用域是单例模式,根据这个bean只能创建一个唯一的实例。


二、protoType(原型模式)


在这里插入图片描述


就和图中的一样,如果bean的作用域为protoType,那么在IOC容器中每个bean都可以创建多个实例。

我们通过代码来认识一下,bean的原型模式

bean的作用域默认是singleton,我们也可以手动通过在xml的bean中scope进行设置成 protoType。

<?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="user" class="pojo.User" scope="prototype"/>

</beans>

根据同一个bean 获取两次实例,查看实例是否相同

    public static void main(String[] args) {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user1 = context.getBean("user", User.class);
        User user2 = context.getBean("user",User.class);
        System.out.println(user1==user2);
    }

查看运行结果

在这里插入图片描述

说明了当设置bean为 protoType时,一个bean可以创建多个不同的实例。

猜你喜欢

转载自blog.csdn.net/rain67/article/details/125324625