Ways to autowire request scoped bean

Viewed 11335

I just wonder if there is any other way to autowire a request scoped bean. So for now I created a bean in configuration file:

@Bean
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT)
public List<String> stringBean(){
    return new ArrayList<String>();
}

So normally I would autowire the applicationContext to use the bean:

@Autowired
private ApplicationContext context; 

@Override
public void anyName() {
    List<String> list = (List<String>) getContext().getBean("stringBean");
}

This works totally fine. But I dont like to autowire the context and the need of a cast. So I tried to autowire the bean directly:

@Autowired
private List<String> stringBean;

I got an exception by startup of the application what is also clear because the bean is not created before a request is started.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stringBean': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

Are there other ways to autowire a request scoped bean?

1 Answers
Related