cla*_*ius 2 java spring spring-mvc
我将使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我修改后的控制器如下所示:
@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));
}
}
Run Code Online (Sandbox Code Playgroud)
而我得到
java.lang.IllegalStateException: No Scope registered for scope 'session']
Run Code Online (Sandbox Code Playgroud)
称为“ / greeting”的结果
我在这里阅读了一些描述:http : //docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html但是我仍然很困惑。
他们写道:“只有在使用Web感知的Spring ApplicationContext实现时,请求,会话和全局会话作用域才可用”。
这是否意味着在这种情况下不允许使用“ AnnotationConfigApplicationContext”?我是否被迫使用一些xml配置?
报价单
Web感知的Spring ApplicationContext实现
指的适当子类WebApplicationContext。您要实例化一个AnnotationConfigApplicationContext不是的子类型的WebApplicationContext,并且不注册SESSION和REQUEST范围。
ApplicationContext在您的商店中创建全新品牌也毫无意义@RestController。该@RestController对象已经是Spring中的bean WebApplicationContext。只需将您的新请求添加@Bean到该上下文,然后自动连接到您的控制器即可。
| 归档时间: |
|
| 查看次数: |
4452 次 |
| 最近记录: |