1概要

  • デフォルトでは、SpringはすべてのシングルトンBeanをアプリケーションコンテキストの起動時または起動時に積極的に作成します。

ただし、アプリケーションコンテキストの起動時ではなく、要求したときにBeanを作成する必要がある場合があります。

  • このクイックチュートリアルでは、Springの

    @ Lazy

    アノテーションについて説明します。**

2.遅延初期化


@ Lazy

アノテーションはSpringバージョン3.0から存在しています。

IoCコンテナにBeanを遅延初期化するように指示する方法はいくつかあります。


2.1.

@設定

クラス


  • @ Launch

    アノテーションを

    @ Configuration

    クラスの上に置くと、

    @ Bean

    アノテーションを持つすべてのメソッドが遅延ロードされることを示します。

これはXMLベースの設定の

default-lazy-init =

“ true



属性と同等です。

ここで見てみましょう:

@Lazy
@Configuration
@ComponentScan(basePackages = "com.baeldung.lazy")
public class AppConfig {

    @Bean
    public Region getRegion(){
        return new Region();
    }

    @Bean
    public Country getCountry(){
        return new Country();
    }
}

機能をテストしましょう。

@Test
public void givenLazyAnnotation__whenConfigClass__thenLazyAll() {

    AnnotationConfigApplicationContext ctx
     = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.class);
    ctx.refresh();
    ctx.getBean(Region.class);
    ctx.getBean(Country.class);
}

ご覧のとおり、すべてのBeanは最初にリクエストしたときにのみ作成されます。

Bean factory for ...AnnotationConfigApplicationContext:
...DefaultListableBeanFactory:[...];//application context started
Region bean initialized
Country bean initialized

これを特定のBeanだけに適用するには、クラスから

@ Lazy

を削除しましょう。

次に、それを目的のBeanの設定に追加します。

@Bean
@Lazy(true)
public Region getRegion(){
    return new Region();
}


2.2

@ Autowired


を使う

先に進む前に、


@Autowired





@Component


annotationsについてのこれらのガイドをチェックしてください。

ここで、遅延Beanを初期化するために、別のBeanから参照します。

遅延ロードしたいBean:

@Lazy
@Component
public class City {
    public City() {
        System.out.println("City bean initialized");
    }
}

そしてそれは参照です:

public class Region {

    @Lazy
    @Autowired
    private City city;

    public Region() {
        System.out.println("Region bean initialized");
    }

    public City getCityInstance() {
        return city;
    }
}

  • @ @ Lazy__は両方の場所で必須です。**


City

クラスに

@ Component

アノテーションを付けて、それを

@ Autowiredで参照しながら:

@Test
public void givenLazyAnnotation__whenAutowire__thenLazyBean() {
   //load up ctx appication context
    Region region = ctx.getBean(Region.class);
    region.getCityInstance();
}

ここで、

City

Beanは、

getCityInstance()

メソッドを呼び出したときにのみ初期化されます。


3結論

このクイックチュートリアルでは、Springの

@ Lazy

アノテーションの基本を学びました。我々はそれを設定し使用するいくつかの方法を検討しました。

いつものように、このガイドの完全なコードはhttps://github.com/eugenp/tutorials/tree/master/spring-core[over on GitHub]にあります。