Alok Pathak
Alok Pathak

Reputation: 875

How do we get bean object from Spring session-scoped beans?

I am trying to get bean from spring session scoped bean. As far as I know that Beans instantiated based on session scope lives through the HTTP session. So how do I get this bean object from Http Session.

Upvotes: 3

Views: 2890

Answers (2)

paul
paul

Reputation: 13471

You can access the ApplicationContext and retrieve beans from there.

    ApplicationContext context = RequestContextUtils.getWebApplicationContext(request);
    SessionInfo info = context.getBean("SessionInfo");-->Whatever bean you want

Upvotes: 4

skaffman
skaffman

Reputation: 403481

You don't obtain the scoped bean from the Session object itself, you just get it from the Spring context in the same way that you get any other bean (e.g. using BeanFactory#getBean). Spring will take care of synchronization between the context and the session.

While it's true that Spring will store the bean reference within the Session object, that's an internal implementation detail, you're not supposed to rummage around in there yourself. That's liable to change across different Spring versions, and the session attribute key under which the bean is stored is not documented.

Upvotes: 2

Related Questions