Spring beanスコープの例

Spring Beanスコープの例

Springでは、Beanスコープを使用して、Springコンテナから呼び出し元に返されるBeanインスタンスのタイプを決定します。

5種類のBeanスコープがサポートされています:

  1. singleton – Spring IoCコンテナごとに単一のBeanインスタンスを返します

  2. prototype –要求されるたびに新しいBeanインスタンスを返します

  3. request – HTTPリクエストごとに単一のBeanインスタンスを返します。 *

  4. session – HTTPセッションごとに単一のBeanインスタンスを返します。 *

  5. globalSession –グローバルHTTPセッションごとに単一のBeanインスタンスを返します。 *

ほとんどの場合、Springのコアスコープであるシングルトンとプロトタイプのみを扱うことができ、デフォルトのスコープはシングルトンです。

P.S * means only valid in the context of a web-aware Spring ApplicationContext

シングルトンとプロトタイプ

Beanスコープの違いを示す例を次に示します:singletonprototype

package com.example.customer.services;

public class CustomerService
{
    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

1. シングルトンの例

Bean構成ファイルでBeanスコープが指定されていない場合、デフォルトはシングルトンです。



       

それを実行します

package com.example.common;

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

import com.example.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
        ApplicationContext context =
         new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

        CustomerService custA = (CustomerService)context.getBean("customerService");
        custA.setMessage("Message by custA");
        System.out.println("Message : " + custA.getMessage());

        //retrieve it again
        CustomerService custB = (CustomerService)context.getBean("customerService");
        System.out.println("Message : " + custB.getMessage());
    }
}

出力

Message : Message by custA
Message : Message by custA

Bean「customerService」はシングルトンスコープにあるため、「custB」による2回目の取得では、「gettA」によって設定されたメッセージも表示されます。新しいgetBean()メソッドによって取得された場合でも同様です。 シングルトンでは、Spring IoCコンテナーごとに1つのインスタンスのみが、getBean()で何度取得しても、常に同じインスタンスを返します。

2. プロトタイプの例

新しい「customerService」Beanインスタンスが必要な場合は、呼び出すたびにプロトタイプを使用してください。



   

もう一度実行する

Message : Message by custA
Message : null

プロトタイプスコープでは、呼び出されるgetBean()メソッドごとに新しいインスタンスがあります。

3. Beanスコープの注釈

アノテーションを使用して、Beanスコープを定義することもできます。

package com.example.customer.services;

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

@Service
@Scope("prototype")
public class CustomerService
{
    String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

自動コンポーネントスキャンを有効にする



       

ソースコードをダウンロード

ダウンロード–Spring-Bean-Scopes-Example.zip(7 KB)