@Scopeアノテーションを使ってSingletonを明示する

Spring Beanのスコープがシングルトンの場合、Spring IoCコンテナーは、そのBean定義によって定義されたオブジェクトのインスタンスを1つだけ作成します。

デフォルトでは、Spring IoCコンテナーは、すべてのBeanをシングルトンとして作成および初期化します。ただしscope="singleton" <bean/>要素の属性または@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)アノテーションを使用して、Beanのスコープをシングルトンとして定義できます。

@Component + @Scope

@RequiredArgsConstructor
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class MessageHelper {

private final MessageSource messageSource;

public String getMessage(MessageId messageId) {
return this.getMessage(messageId, null, Locale.getDefault());
}

public String getMessage(MessageId messageId, Object[] args) {
return this.getMessage(messageId, args, Locale.getDefault());
}

public String getMessage(MessageId messageId, Object[] args, Locale locale) {
return messageSource.getMessage(messageId.name(), args, locale);
}
}
  • SpringbootでBeanはSingletonとして扱っていると知っていますが、@Scopeアノテーションを使って明示しました。
  • 各違うクラス内でBeanを挿入して確認した結果です。

コメントを残す