No Scope registered for scope request

by paul on June 5, 2009

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();
    }
}

Previous post: Trinidad and text wrapping

Next post: Adding items to Gnome menus