我想在我的应用程序中使用请求范围的 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
但我注意到他使用了AbstractDependencyInjectionSpringContextTests,这在 Spring 3.0 中似乎已被弃用。我此时使用 Spring 2.5,但认为按照文档建议切换此方法以使用 AbstractJUnit4SpringContextTests 应该不会太难(好的文档链接到 3.8 版本,但我使用的是 4.4)。所以我将测试更改为扩展 AbstractJUnit4SpringContextTests... 相同的消息。同样的问题。现在我想要覆盖的 prepareTestInstance() 方法没有定义。好的,也许我会将那些 registerScope 调用放在其他地方......所以我阅读了更多关于TestExecutionListeners并认为这会更好,因为我不想继承 spring 包结构。所以我将我的测试更改为:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/TestScopedBeans-context.xml" })
@TestExecutionListeners({})
public class TestScopedBeans {
期望我必须创建一个自定义侦听器,但是当我运行它时。有用!很好,但为什么呢?我看不到任何股票侦听器在哪里注册请求范围或会话范围,为什么会这样?没什么可说的,我想要那个,这可能不是 Spring MVC 代码的测试......