我们有像这样的单例控制器
@Controller
class C {
@Autowire MyObject obj;
public void doGet() {
// do something with obj
}
}
MyObject 在过滤器/拦截器中创建并放入 HttpServletRequest 属性中。然后在@Configuration中获取:
@Configuration
class Config {
@Autowire
@Bean @Scope("request")
MyObject provideMyObject(HttpServletRequest req) {
return req.getAttribute("myObj");
}
}
在主代码中一切正常,但在测试中却不行:当我从集成测试中运行它时:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/web-application-config_test.xml")
class MyTest {
@Autowired
C controller;
@Test
void test() {
// Here I can easily create "new MockHttpServletRequest()"
// and set MyObject to it, but how to make Spring know about it?
c.doGet();
}
}
它抱怨说NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.http.HttpServletRequest]
。(起初,它抱怨请求范围不活跃,但我按照这里的建议使用带有 SimpleThreadScope 的 CustomScopeConfigurer 解决了它)。
如何让 Spring 注入知道我的 MockHttpServletRequest?还是直接MyObject?