zoukankan      html  css  js  c++  java
  • Spring中设置bean作用域

    在Spring中,bean对象可以有多种作用域

    singletion 默认的,每个IOC容器只创建一个Bean实例

    prototype每次请求创建一个Bean实例

    request每次http请求创建一个实例

    session每次会话创建一个实例

    globalsession每个全局Http请求创建一个实例

    如下:

    package com.wfb.beans;

    import java.util.ArrayList;
    import java.util.List;

    public class ShoppingCart {
    private List<Product>items=new ArrayList<Product>();
    public void addItem(Product p){
       items.add(p);
      
    }
    public List<Product> getItems() {
       return items;
    }
    }
    上面的类代表了购物车:

    xml中配置如下:

    <bean id="bbb" class="com.wfb.beans.Battery">
    <property name="name" value="AAA"></property>
    <property name="price" value="2.5"></property>
    </bean>

    <bean id="cdrw" class="com.wfb.beans.Disc">
    <property name="name" value="CD-RW"></property>
    <property name="price" value="1.5"></property>
    </bean>
    <bean id="dvdrw" class="com.wfb.beans.Disc">
    <property name="name" value="CD-RW"></property>
    <property name="price" value="3.5"></property>
    </bean>
    <bean id="shopCart" class="com.wfb.beans.ShoppingCart"></bean>

    下面的过程代表了购物车的使用:

    Product aaa=(Product) context.getBean("bbb");
       Product cdrw=(Product) context.getBean("cdrw");
       ShoppingCart sc1=(ShoppingCart) context.getBean("shopCart");
       sc1.addItem(aaa);
       sc1.addItem(cdrw);
       System.out.println(sc1.getItems());
       ShoppingCart sc2=(ShoppingCart) context.getBean("shopCart");
       Product dvdrw=(Product) context.getBean("dvdrw");
      
       sc2.addItem(dvdrw);
       System.out.println(sc2.getItems());

    程序运行结果如下:

    [com.wfb.beans.Battery@de1b8a, com.wfb.beans.Disc@1e232b5]
    [com.wfb.beans.Battery@de1b8a, com.wfb.beans.Disc@1e232b5, com.wfb.beans.Disc@16f144c]

    可以看出创建的两个购物车是同一个购物车,这是因为Spring默认的singleton格式,在配置中改为ie:


    <bean id="shopCart" class="com.wfb.beans.ShoppingCart" scope="prototype"></bean>

    程序运行结果如下:

    [com.wfb.beans.Battery@16f144c, com.wfb.beans.Disc@19da4fc]
    [com.wfb.beans.Disc@baa466]

    两次产生的是不同的购物车对象

  • 相关阅读:
    Binary Tree Maximum Path Sum
    ZigZag Conversion
    Longest Common Prefix
    Reverse Linked List II
    Populating Next Right Pointers in Each Node
    Populating Next Right Pointers in Each Node II
    Rotate List
    Path Sum II
    [Leetcode]-- Gray Code
    Subsets II
  • 原文地址:https://www.cnblogs.com/macula7/p/1960444.html
Copyright © 2011-2022 走看看