I have one simple resource class and autowiring bean from BeanConfig class, which declared one bean.
Whenever request is hit on API, then i am getting an exception.
Code:
#Component
public class BeanConfig {
#Autowired
Environment environment;
#Bean
#RequestScope
public Map<String, String> eventAttributes() {
return new HashMap<>();
}
}
public class SampleResource {
#Autowired
SampleServiceImpl sampleService;
#Autowired
private Map<String, String> eventAttributes; }
Following error:
org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.eventAttributes': 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: In this case, use RequestContextListener or RequestContextFilter to expose the current request
Related
I want to capture some request specific data 'under the covers' for every request coming into my spring controllers and store this in a request scoped bean for use at a lower level in the app , like the DAO layer. I've tried using interceptors, but the request scoped bean is always null in that case. This is my latest attempt using RequestContextListener.
#Configuration
#WebListener
public class MyRequestListener extends RequestContextListener {
#Autowired
RequestContext requestContext;
#Override
public void requestInitialized(ServletRequestEvent sre) {
// requestContext.setHttpRequestId(((HttpServletRequest)sre.getServletRequest()).getSession().getId());
System.out.println(requestContext);
}
}
then in some config class I have this (RequestContext is a simple class with one setter/getter for a piece of String data)
#Bean
#RequestScope
public RequestContext requestContext() {
return new RequestContext();
}
Error in the requestInitialized method now is
"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: In this case, use RequestContextListener or RequestContextFilter to expose the current request."
What's the idiomatic way of achieving this seemingly simple and surely common requirement ?
I'm trying to run Unit tests on a service class that has an auto wired dependency which is request scoped. When running the unit test, it seems like spring container is unable to find the bean to auto wire into the service class. What should I do to fix this?
Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
AppConfig.java
#Configuration
public class AppConfig {
#Bean
#Scope("request")
public ClassA classA(){
return new ClassA();
}
}
ServiceA.java
#Service
public class ServiceA {
#Autowired
private ClassA classA;
public void doSomething(){
String value = classA.getValue();
System.out.println(value);
}
}
ServiceTest.java
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ServiceATest {
#Test
void contextLoads() {
}
}
Error message
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'serviceA': Unsatisfied dependency
expressed through field 'classA'; nested exception is
org.springframework.beans.factory.support.ScopeNotActiveException:
Error creating bean with name 'classA': 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:
In this case, use RequestContextListener or RequestContextFilter to
expose the current request.
I have Spring configuration file where I am defining beans but somehow this bean is not accessible from one of the class in same package, though same beans are accessible from Controller class which was annotated as #Controller. I was thinking may be this class was not managed by Spring but that's not the case.
1) Configuration class
#Bean
public FooConsumer fooConsumer() {
return new FooConsumer();
}
#Bean
public Map<String, ProxyConsumer> appProxyConsumerMap() {
Map<String, ProxyConsumer> proxyConsumer = new HashMap<String, ProxyConsumer>();
proxyConsumer.put(FOO_APP, FooConsumer());
return proxyConsumer;
}
#Bean
public FooEventConsumer fooEventConsumer() {
return new FooEventConsumer();
}
#Bean
public Map<String, FooConsumer> fooConsumerMap(){
Map<String, FooConsumer> fooEventConsumer = new HashMap<String, FooConsumer>();
fooEventConsumer.put(FOO_EVENT, fooEventConsumer());
}
2) Controller class
#Resource
#Qualifier("appProxyConsumerMap")
Map<String, ProxyConsumer> appProxyConsumerMap;
//proxyApp comes as path variable
ProxyConsumer consumer = appProxyConsumerMap.get(proxyApp);
//invoke consumer
boolean consumed = consumer.consumeEvent(eventRequest);
//here consumer is my FooConsumer class, till now all works fine.
3) now in FooConsumer class it tries to access Map bean named fooConsumerMap to get which event to call but somehow it returns null.
#Resource
#Qualifier("fooConsumerMap")
Map<String, FooConsumer> fooConsumerMap;
FooEventConsumer consumer = fooConsumerMap.get(eventType);
//Here fooConsumerMap comes as null in this class, though it comes as object in controller class , please advise.
In your configuration file, construct your FooConsumer bean with the FooConsumerMap bean declared in the same configuration.
You can autowire other beans into a configuration file, but to pull together beans within the file you pass them as constructor arguments.
Note that if you call a Bean annotated method multiple times, you will surprisingly always get the same instance even if the method logic constructs a new instance.
Check documentation at https://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html
In Spring Web application, I have to use specific value from request object in another spring classes within application. Value is request specific value.
In the following example, is it good way to register value coming from Request Body every time and use #Autowired with #RequestScope annotation to use value in another spring(e.g. #Service) classes? Is it good to register RequestScopedType bean value for each request through BeanFactory?
#RestController
#RequestMapping("/")
public class VehicleServiceController {
#Autowired
private BeanFactory beanFactory;
#Autowired
private ServiceClass serviceClass;
#PostMapping(path = "/postDetails", consumes = MediaType.APPLICATION_JSON_VALUE)
public OutputPayload postDetails(
#RequestBody InputPayload inboundPayload) throws Exception {
beanFactory.getBean(RequestScopedType.class).setValue(inboundPayload.getType());
return serviceClass.methodToCall();
}
}
Will there be any impact on performance as load is very huge? Is there any another way to inject/get RequestBody object value(inboundPayload.getType())?
You don't have to do beanFactory.getBean(RequestScopedType.class). You can just simply autowire it #Autowired RequestScopedType requestScopedType.
Just don't forget to change the scope of the bean as Request.
#Component
#Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestScopedType {
But this begs another question, why over complicate things, why can't you pass inboundPayload.getType() to the serviceClass.methodToCall(); ?
What is stopping you from using it this way return serviceClass.methodToCall(inboundPayload.getType());
I would like to use Spring Event to "speak" with my beans in my web application.
So, for example, my bean which fires event is like this:
#Controller
#Scope("request")
#KeepAlive
public class Controller extends InitializingBean, ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
public void test() {
applicationEventPublisher.publishEvent(new TestEvent(this));
}
}
And my listener event is like this:
#Component
#Scope("request")
#KeepAlive
public class Module implements ApplicationListener<TestEvent> {
#Override
public void onApplicationEvent(TestEvent event) {
}
}
The most important point is these beans are scope request because they need to be initialized at every time the page is called.
But in startup, I get this message:
Caused by: 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.
Like if Spring try to instantiate my Module bean in startup and as the bean is scope request, it can't do this (the context request is not instantiate)
If I delete event management, everything works fine.
So, my question is:
Is it possible to have event listener is scope request ? And how to do this ?
Thanks
Try to inject a scoped proxy in a Singleton ApplicationListener to handle the TestEvent.
#Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value="request")
public class TestEventHandler {
public void onTestEvent(TestEvent event)
// ...
}
}
public class TestEventApplicationListener implements ApplicationListener<TestEvent> {
#Autowired
private TestEventHandler handler;
#Override
public void onApplicationEvent(TestEvent event) {
handler.onTestEvent(event);
}
}