8.单例与多例的bean实例.md

zhanglei 2022年05月30日 385次浏览

8.单例与多例的bean实例

Order类

package Spring5;

public class Order {
    private String orderName;
    private String orderAddress;

    public Order(){}

    public Order(String orderName, String orderAddress) {
        this.orderName = orderName;
        this.orderAddress = orderAddress;
    }

    public void show(){
        System.out.println(orderName+"  "+orderAddress);
    }
}

bean7.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="Order" class="Spring5.Order" scope="singleton"></bean>
</beans>
    -->


    <bean id="Order" class="Spring5.Order" scope="prototype"></bean>
</beans>

测试类

public class TEST {
   
    //设置 创建的bean实例 是单实例还是多实例
    @Test
    public void testBean7() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
        Order order1 = context.getBean("Order", Order.class);
        Order order2 = context.getBean("Order", Order.class);
        System.out.println(order1);
        System.out.println(order2);
    }
}

测试结果

//多例的测试结果如下:
Spring5.Order@6aba2b86
Spring5.Order@158da8e