Recently I was working with some code which defined beans as request scope. Junit tests failed with the following exception while trying to initialize the application context:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: …; nested exception is java.lang.IllegalStateException: No Scope registered for scope ‘request’
I found the solution by searching around (unfortunately I didn’t record the sources). Basically, you can register the required scopes as shown below:
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestScope;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.SessionScope;
public class SampleTest extends AbstractDependencyInjectionSpringContextTests {
@Override
protected void prepareTestInstance() throws Exception {
context.getBeanFactory().registerScope("session", new SessionScope());
context.getBeanFactory().registerScope("request", new RequestScope());
MockHttpServletRequest request = new MockHttpServletRequest();
attributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(attributes);
super.prepareTestInstance();
}
}


{ 2 comments… read them below or add one }
is context of type ApplicationContext? I can’t find method getBeanFactory for it
It’s been available on AbtractApplicationContext from at least spring 2.0 :
http://static.springsource.org/spring/docs/3.0.0.RC1/javadoc-api/org/springframework/context/support/AbstractApplicationContext.html#getBeanFactory%28%29
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/support/AbstractApplicationContext.html#getBeanFactory%28%29
http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/context/support/AbstractApplicationContext.html#getBeanFactory%28%29