Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring request scope bean

How can I set up a bean which will created once per request.

I Tried to do like this :

   @Component
   @Scope(value = "request")
   public class TestBean {
        @PostConstruct
        public void init() {
             System.out.println("start request");
        }

        @PreDestroy
        public void onDestroy() {
             System.out.println("ends request");
        }
   }

Thanks.

like image 658
john Smith Avatar asked Feb 06 '13 14:02

john Smith


People also ask

What is request bean scope in Spring?

A request-scoped bean is an object managed by Spring, for which the framework creates a new instance for every HTTP request. The app can use the instance only for the request that created it. Any new HTTP request (from the same or other clients) creates and uses a different instance of the same class (figure 2).

What is a request scope?

If a component is marked with request scope, simultaneous requests each see a different instance of the component. This is true even when the same session sends two requests simultaneously; each request gets a pointer to a separate object.

What is the difference between singleton and request scope in Spring?

A request can be made to the bean instance either programmatically using getBean() method or by XML for Dependency Injection of secondary type. Generally, we use the prototype scope for all beans that are stateful, while the singleton scope is used for the stateless beans.

How can use session scoped bean in Spring?

The request scope creates a bean instance for a single HTTP request, while the session scope creates a bean instance for an HTTP Session. The application scope creates the bean instance for the lifecycle of a ServletContext, and the websocket scope creates it for a particular WebSocket session.


1 Answers

Try this @Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)

For more details see this blog post.

like image 193
Teja Kantamneni Avatar answered Sep 19 '22 06:09

Teja Kantamneni