Calling a class annotated with @RequestScope inside a Listener using Spring boot

1.6k Views Asked by At

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.movimentacaoEntradaRadarNotaBuilderImpl': 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.

I need something to solve the problem without removing @RequestScope and that is only for this case and not for the whole project.

@Component
@RequestScope
public class BuilderImplementation implements BuilderInterface {

    @Override
    public void build(){

    }

}

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MovimentacaoEntradaQueueStorageListener {

    private final @NonNull BuilderInterface builderInterface;

    public MessageStatus listen() {

        builderInterface.build();
    }
}

1

There are 1 best solutions below

0
On

According to (springs documentation the three scopes 'request', 'session', and 'global session' are only possible if there is a web-aware ApplicationContext:

The scopes that are described in the following paragraphs are only 
available if you are using a web-aware Spring ApplicationContext 
implementation (such as XmlWebApplicationContext). If you try using these 
next scopes with regular Spring IoC containers such as the XmlBeanFactory 
or ClassPathXmlApplicationContext, you will get an IllegalStateException 
complaining about an unknown bean scope.

Follow the guidance of the official spring documentation to solve your problem.