六.bean的作用域

1.singleton单例

(https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes-singleton)

容器仅仅创建一个对象,所有引用都仅仅使用这一个对象

<bean name="student" class="com.why.Student" scope="singleton">

测试代码:

  <!--配置类:address-->
    <bean class="com.why.Address" id="address" scope="singleton">
        <property name="address" value="中国"/>
    </bean>

测试代码,此时输出true,说明这2个引用指向同一个对象

 public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        Object address = context.getBean("address");
        Object address1 = context.getBean("address");
        System.out.println(address.equals(address1));
    }

2.原型prototype

<!--配置类:address-->
    <bean class="com.why.Address" id="address" scope="prototype">
        <property name="address" value="中国"/>
    </bean>

此时输出false,说明2个引用指向的是不同的对象

 public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        Object address = context.getBean("address");
        Object address1 = context.getBean("address");
        System.out.println(address.equals(address1));
    }

 

 

 

posted @ 2020-08-31 14:11  why666  阅读(110)  评论(0)    收藏  举报