LoginSignup
8
10

More than 5 years have passed since last update.

springのデフォルトスコープをprototypeにする

Posted at

良いか悪いかは別にしてspringのDIでデフォルトのScopeが「singleton」になっているために事件が発生してしまう事があります。

これを変更する際には@Scopeアノテーションを使って都度指定する方法が良く見つかりますが「いちいち面倒だし忘れて事故るの嫌だから全部prototypeでいいよ!」って時にデフォルトを変更する方法。

springの設定ファイルでcomponent-scanの設定時にscope-resolverに「org.springframework.context.annotation.Jsr330ScopeMetadataResolver」を指定します。

<context:component-scan base-package="your.base.package"
  scope-resolver="org.springframework.context.annotation.Jsr330ScopeMetadataResolver" />

こうする事で、意図的にsingletonにしたい時だけ@Scope("singleton")と書けるようになります。

本来、Jsr330ScopeMetadataResolverはJSR330の仕様ではデフォルトスコープがprototypeであるため、JSR330のアノテーションでDIしたいときに使うものです。

8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10