I am using the pure example code of simple REST service from the spring guide as a base: http://spring.io/guides/gs/rest-service/
I have added single Bean configuration:
@Configuration
public class Config {
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public RequestData requestHelper() {
return new RequestData();
}
}
Then my modified controller looks as follows:
@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));
}
}
and I am getting
java.lang.IllegalStateException: No Scope registered for scope 'session']
as the result of calling "/greeting"
I have read some description here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html however I am still confused.
they write: "The request, session, and global session scopes are only available if you use a web-aware Spring ApplicationContext implementation".
Does it mean that "AnnotationConfigApplicationContext" which I am using is not allowed in such case? Am I forced to use some xml configuration instead?
The quote
web-aware Spring ApplicationContext implementation
refers to an appropriate subclass of WebApplicationContext
. You're instantiating a AnnotationConfigApplicationContext
which is not a subtype of WebApplicationContext
and which does not register the SESSION
and REQUEST
scopes.
It also makes very little sense to create a brand new ApplicationContext
in your @RestController
. The @RestController
object is already a bean within a Spring WebApplicationContext
. Just add your new request scoped @Bean
to that context and autowire into your controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.