【Spring】学习笔记004--Bean的作用域

  Spring官方给出的bean作用域如下

 

1. 单例模式

  单例模式是Spring的默认机制,每次从容器中get的时候,都会创建一样的对象

<bean id="helloBean" class="com.aircl.domain.Hello" scope="singleton">
    <property name="str" value="Hello Spring"></property>
</bean>

  测试

    @Test
    public void testHello(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Hello helloBean = (Hello) context.getBean("helloBean");
        Hello helloBean1 = (Hello) context.getBean("helloBean");
        System.out.println(helloBean == helloBean1);
    }

2. 原型模式

  原型模式下,每次从容器中get的时候,都会产生一个新对象

<bean id="helloBean" class="com.aircl.domain.Hello" scope="prototype">
    <property name="str" value="Hello Spring"></property>
</bean>

  测试

  如上相同代码

3. 其他模式

  其余模式在Spring MVC下生效,在此暂不讨论。

posted @ 2021-02-04 13:12  AirCL  阅读(62)  评论(0)    收藏  举报