アプリでリクエスト スコープ Bean を利用したいと考えています。テストには JUnit4 を使用します。次のようなテストで作成しようとすると:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
public class TestScopedBeans {
protected final static Logger logger = Logger
.getLogger(TestScopedBeans.class);
@Resource
private Object tObj;
@Test
public void testBean() {
logger.debug(tObj);
}
@Test
public void testBean2() {
logger.debug(tObj);
}
次の Bean 定義を使用します。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="java.lang.Object" id="tObj" scope="request" />
</beans>
そして私は得る:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.nasa.arc.cx.sor.query.TestScopedBeans': Injection of resource fields failed; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'request'
<...SNIP...>
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'request'
そこで、役立つと思われるこのブログを見つけました: http://www.javathinking.com/2009/06/no-scope-registered-for-scope-request_5.html
しかし、Spring 3.0 で廃止されたように見えるAbstractDependencyInjectionSpringContextTestsを使用していることに気付きました。現時点ではSpring 2.5を使用していますが、ドキュメントが示唆するように、このメソッドをAbstractJUnit4SpringContextTestsを使用するように切り替えるのはそれほど難しくないと考えました(ドキュメントは3.8バージョンにリンクしていますが、私は4.4を使用しています)。したがって、テストを変更して AbstractJUnit4SpringContextTests を拡張します...同じメッセージ。同じ問題。そして、オーバーライドしたい prepareTestInstance() メソッドが定義されていません。OK、多分私はそれらの registerScope 呼び出しを別の場所に置きます...だから私はTestExecutionListenersについてもっと読んで、Springパッケージ構造を継承する必要がないので、それがより良いと思います。そこで、テストを次のように変更しました。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
@TestExecutionListeners({})
public class TestScopedBeans {
カスタムリスナーを作成する必要があると思っていましたが、それを実行したときです。できます!素晴らしいですが、なぜですか?ストックリスナーがリクエストスコープまたはセッションスコープを登録している場所がわかりません。なぜですか? まだ何も言いたいことはありません。これはSpring MVCコードのテストではないかもしれません...