Friday, 5 June 2009

No Scope registered for scope request

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:

[sourcecode language='java']
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();
}
}
[/sourcecode]