I want to inject my request scoped bean to my other bean.
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UiCtx {
@Autowired(required = true)
private ApplicationContext ctx;
@Autowired(required = true)
private ServletWebRequest req;
// [...]
}
I try to inject this bean to a JPage
bean:
@Component
@Scope("prototype")
public class Jpage extends AbstractUiComponent {
// [...]
}
public abstract class AbstractUiComponent {
@Autowired(required = true)
private UiCtx ctx;
// [...]
}
In the controller I have tried:
@RestController
class GreetingController {
@RequestMapping("/jpage")
void jpage(HttpServletRequest request, HttpServletResponse response,
@Autowired @Qualifier("jpage") AbstractUiComponent jpage) throws IOException {
WritePage.writeWebPage(request, response, jpage);
}
}
}
I got:
Failed to instantiate [pl.mirage.components.AbstractUiComponent]: Is it an abstract class?; nested exception is java.lang.InstantiationException
Another attempt. It doesn't work because @RestController
is a singleton - you can't inject request scope into singleton scope:
@RestController
class GreetingController {
@Autowired
@Qualifier("jpage")
AbstractUiComponent jpage;
@RequestMapping("/jpage")
void jpage(HttpServletRequest request, HttpServletResponse response) throws IOException {
WritePage.writeWebPage(request, response, jpage);
}
}
I got:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'greetingController': Unsatisfied dependency expressed through field 'jpage'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jpage': Unsatisfied dependency expressed through field 'ctx'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'uiCtx': 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.
It is possible to fix this by annotating UICtx
or JPage
as @Scope(value = "[..]", proxyMode = ScopedProxyMode.TARGET_CLASS)
.
It only works when JPage
is injected as a controller field. It doesn't work when JPage
is injected as a method parameter.
How do I suppose to inject a request scoped bean?