我使用 Spring 指南中简单 REST 服务的纯示例代码作为基础: http://spring.io/guides/gs/rest-service/
我添加了单个 Bean 配置:
@Configuration
public class Config {
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public RequestData requestHelper() {
return new RequestData();
}
}
然后我修改后的 Controller 如下所示:
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
System.out.println(applicationContext.getBean(RequestData.class));
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
我正在得到
java.lang.IllegalStateException: No Scope registered for scope 'session']
作为调用“/greeting”的结果
我在这里阅读了一些描述: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html但我还是很困惑。
他们写道: “仅当您使用 Web 感知的 Spring ApplicationContext 实现时,请求、 session 和全局 session 范围才可用”。
这是否意味着我正在使用的“AnnotationConfigApplicationContext”在这种情况下是不允许的?我是否被迫使用某些 xml 配置?
最佳答案
报价
web-aware Spring ApplicationContext implementation
指的是 WebApplicationContext
的适当子类。您实例化的 AnnotationConfigApplicationContext
不是 WebApplicationContext
的子类型,并且不注册 SESSION
和 REQUEST
范围。
在 @RestController
中创建一个全新的 ApplicationContext
也没有什么意义。 @RestController
对象已经是 Spring WebApplicationContext
中的一个 bean。只需将您的新请求作用域 @Bean
添加到该上下文并 Autowiring 到您的 Controller 中即可。
关于java - Spring RESTful Web 服务和 bean "request"和 "session"范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28904115/