当Bean作用域更改为“原型”时,Setter方法不起作用

时间:2019-04-07 09:07:16

标签: spring

我在spring项目中定义了以下类

Triangle.java

public class Triangle 
{

    private double breadth;
    private double length;

    public double getBreadth() {
        return breadth;
    }

    public void setBreadth(double breadth) {
        this.breadth = breadth;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }
}

下面的类计算三角形的面积

Area.java


public class Area 
{
    Triangle triangle;

    public Triangle getTriangle() {
        return triangle;
    }

    public void setTriangle(Triangle triangle) {
        this.triangle = triangle;
    }

    public double triArea()
    {
        return (triangle.getBreadth() * triangle.getLength())/2;
    }
}

spring.xml配置文件如下所示

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd
/spring-beans-2.0.dtd">

<beans>
    <bean id="triangle" class="src.jayant.spring.Triangle" scope="prototype">
        <property name = "breadth" value = "20"/>
        <property name = "length" value = "20"/> 
    </bean>

    <bean id="area" class="src.jayant.spring.Area">
        <property name = "triangle" ref="triangle"/>
    </bean>

</beans>

最后,我们有了AreaApp.java,它获取xml中定义的“ area”和“ triangle” bean并计算面积。

AreaApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;                                                                                           

public class AreaApp 
{
    public static void main(String args [])
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

        Triangle triangle = (Triangle)context.getBean("triangle");
        Area area = (Area)context.getBean("area");

        System.out.println("Area of Triangle is : "+area.triArea());

        triangle.setBreadth(40);

        System.out.println("Area of Triangle is : "+area.triArea());
    }
} 

现在

当我们将'triangle'bean范围设为'singleton'

<bean id="triangle" class="src.jayant.spring.Triangle" scope="singleton">

则输出将为

Area of Triangle is : 200.0
Area of Triangle is : 400.0

但是当我将范围更改为“原型”时

<bean id="triangle" class="src.jayant.spring.Triangle" scope="prototype">

则输出将为

Area of Triangle is : 200.0
Area of Triangle is : 200.0

为什么使用setter方法

triangle.setBreadth(40);
当bean作用域是原型时,

不起作用。

谢谢

周杰伦

1 个答案:

答案 0 :(得分:2)

它确实有一个作用:它改变了从上下文中获得的三角形的宽度。

但是这个三角形与Area bean使用的三角形不同,因为您的三角形bean现在是一个原型,因此,根据原型范围的定义,您每次都会得到一个新实例您向上下文请求一个Triangle实例。