03点目のSpring 4.1-scope

2065 ワード

3.1 scope
scopeはspring容器がどのように新しい種類の実例であるかを説明します.springでデフォルトのscopeはsingletonであり、これはあなたがプログラムの中でどれだけ多くの場所でこのbeanを使っても、それらは唯一のインスタンスを共有することを意味する.スプリング内蔵のscopeは以下のいくつかあります.
singleton:spring容器の中で一つのbeanだけの例.prototype:毎回新しいbeanの例を呼び出します.request:webプロジェクトでは、http requestごとに、beanの例を新規作成します.session:webプロジェクトでは、http sessionごとに、beanの例を新規作成します.global Session:これはポルタージュの応用にのみ役立ちます.global http sessionごとに、beanのインスタンスを新規作成します.
3.2プレゼンテーション
3.2.1新しいscopeはsingletonの種類です.
package com.wisely.scope;

import org.springframework.stereotype.Service;

@Service//  scope singleton
public class DemoSingletonService {

}

3.2.2新規作成scopeはprototypeのクラスです.
package com.wisely.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class DemoPrototypeService {

}

3.2.3テスト
package com.wisely.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                  new AnnotationConfigApplicationContext("com.wisely.scope");
        //   spring         , singleton       , prototype         
        DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

        DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

        System.out.println("s1 s2    :"+s1.equals(s2));
        System.out.println("p1 p2    :"+p1.equals(p2));
        context.close();
    }

}

出力
s1 s2    :true
p1 p2    :false