I'm developing a web application using Spring MVC, and want to have a request scoped Date bean which indicates when each request happens. To define such Date bean, I have written a following bean definition into application context xml.
<bean id="now"
class="java.util.Date"
scope="request">
<aop:scoped-proxy/>
</bean>
Injecting this bean into a singleton bean by using field injection works fine.
public class ASingletonBean {
@Autowired
private Date now;
...
}
But I don't want to use field injection because it's not recommended. My IDE suggests to use constructor injection instead.
public class ASingletonBean{
private final Date now;
@Autowired
public ASingletonBean(Date now) {
this.now = now;
}
}
Now the code above throws a following exception when the application launches.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'scopedTarget.java.util.Date#0':
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.
How can I avoid this error?