ビーンのスコープ

1189 ワード

デフォルトの場合は、全てのbeanオブジェクトが単一の例である(同じspringのコンテキストで取得されるものは常に同じオブジェクトである).spring容器にbeanが割り当てられている場合、それは常に同じ例を返します.springが要求毎に新しいインスタンスを生成することを望むなら、beanを配置するscopeがprototypeであればいいです.

テストクラス:
public class TestSingle {
    private Integer i;

    public Integer getI() {
        return i;
    }

    public void setI(Integer i) {
        this.i = i;
    }
}
xml構成:



テスト:
//     bean       
TestSingle testSingle = (TestSingle) context.getBean("testSingle");
testSingle.setI(1);
System.out.println(testSingle.getI());
TestSingle testSingle2 = (TestSingle) context.getBean("testSingle");
System.out.println(testSingle2.getI());

//                
TestSingle testpro = (TestSingle) context.getBean("testPro");
testpro.setI(1);
System.out.println(testpro.getI());
TestSingle testpro2 = (TestSingle) context.getBean("testPro");
System.out.println(testpro2.getI());
運転結果:
1
1
1
null