私はSpring MVCを使用してWebアプリケーションを開発していますが、各リクエストがいつ発生するかを示すリクエストスコープDate
のリクエストスコープが必要です。このようなDate
beanを定義するために、私はアプリケーションコンテキストxmlに次のBean定義を記述しました。コンストラクタインジェクションを使用してスコープ付きプロキシBeanをシングルトンBeanに挿入する方法
<bean id="now"
class="java.util.Date"
scope="request">
<aop:scoped-proxy/>
</bean>
フィールドインジェクションを使用してこのビーンをシングルトンBeanに注入すると、正常に動作します。
public class ASingletonBean {
@Autowired
private Date now;
...
}
しかし、私はフィールドの注入を推奨していないので使用したくありません。私のIDEでは、代わりにコンストラクタインジェクションを使用することを提案しています。
public class ASingletonBean{
private final Date now;
@Autowired
public ASingletonBean(Date now) {
this.now = now;
}
}
上記のコードは、アプリケーションの起動時に以下の例外をスローします。
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'scopedTarget.java.util.Date#0':
Scope 'request' is not active for the current thread;
consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;
nested exception is java.lang.IllegalStateException:
No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?
If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet:
In this case, use RequestContextListener or RequestContextFilter to expose the current request.
どうすればこのエラーを回避できますか?
ありがとうございます。私は実際にアプリケーションの多くの場所でリクエストが発生したときの 'Date'オブジェクトを使用したいと思います。だから、「サプライヤ」を使ったアプローチは私の場合にはあまり適していません。私は 'OncePerRequestFilter'を使うことに興味があります。どうすればそれを使うことができますか、なぜリクエストスコープのBeanを使うのが望ましいのでしょうか? – umainyosu