Spring request scope bean
Asked Answered
K

4

17

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.

Kamila answered 6/2, 2013 at 14:9 Comment(1)
And what happened? What did you want to happen?Conductor
P
29

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

For more details see this blog post.

Petrochemical answered 6/2, 2013 at 14:33 Comment(3)
Thanks for your replay,but it didn't help. Still the bean is not being initialized.Kamila
Do you mean that @PostConstruct is not being called?Petrochemical
Are you sure your context is web aware application context?Petrochemical
D
0

You can set your bean to request scope by xml configuration as

 <bean id="testBean" class="com.test.TestBean" scope="request">
    <aop:scoped-proxy/>
  </bean>

Tag aop:scoped-proxy will be used to inject your bean using proxy. This is xml based way to set your bean to request scope.

Detriment answered 29/5, 2019 at 9:23 Comment(0)
S
0

Try scopeName instead of value:

@Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
Samothrace answered 9/6, 2022 at 16:8 Comment(0)
O
0

How do you know if it works or not? What is your desired behavior?

As Spring creates a proxy for request-scope beans and inject them into other beans. So the bean will be created just once, and its PostConstruct will be called just once, and PreDestroy probably never (except shutting down the application).

If you need a method be called on every single request, you can write an event handler handling org.springframework.web.context.support.RequestHandledEvent, this handler will be executed after each request have been handled. I am not aware of any event being published before handling a request.

Other solution is having a org.springframework.web.servlet.HandlerInterceptor and then configure it to be executed on all requests (this way you can do anything you want before and after request-handling).

Owner answered 9/1 at 5:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.