Spring_Bean的作用域

--Bean的作用域:singleton;prototype;WEB环境作用域

例子:

car类:

package com.xia.entity;

public class Car {
    private String cname;
    private double price;
    public Car(String cname, double price) {
        super();
        this.cname = cname;
        this.price = price;
    }
    
    
    @Override
    public String toString() {
        return "Car [cname=" + cname + ", price=" + price + "]";
    }


    public Car() {
        super();
    }
    
    public String getCname() {
        return cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    
    
}    

配置文件:

<!-- 使用Bean的scope属性来配置Bean的作用域
          singleton:默认值,容器在初始化时创建Bean实例,在容器的生命周期内只创建这一个实例,单例的。
          prototype:原型的,容器初始化时不创建bean实例,而是在每次请求时都创建一个新的Bean实例。,并返回。
   -->
  <bean id="car" class="com.xia.entity.Car" scope="prototype">
      <property name="cname" value="Audo"></property>
      <property name="price">
          <value>1000000</value>
      </property>
  </bean>

测试:

ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Car car = (Car) ac.getBean("car");
        Car car2 = (Car) ac.getBean("car");
        System.out.println(car == car2);

如果bean的scope属性为默认的singleton,则输出

true

如果是prototype,则输出:

false

 

posted @ 2016-10-02 15:02  夏文杰  阅读(103)  评论(0)    收藏  举报