Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowired confusion (container or session)

In My app I am using a User bean that is Autowired to my service MyService and its used as the principle logged in user's info (So the user is not coming as a static bean from an xml but dynamically generated from a logged in user) If there are ten users logged in I will have ten candidates for the @AutoWired User field. (right?) and I can get any one of them cos AutoWired looks in the Spring container and not session.

tell me if I am wrong on this. and how to actually solve it if possible. But what if my AutoWired field is annotated with @Scope ("Session")

Like this :

@Component("user")
@Scope("session")
public class User 
{
String userid;
String name;
//getter setters etc
}

@Component
public class MyService
{
    @Autowired
    private User user;

}

Is it possible to get some other user's User bean when I call my MyService Component. Cos MyService is only @Component even though the User is @Scope(session).

Basically, (If I am wrong in my assumption) I think that when you @Autowire a field, its looks into the container as whole and the container is not divided into subcontainers per session.

like image 485
sarmahdi Avatar asked Jan 15 '12 12:01

sarmahdi


1 Answers

When you annotate User with @Scope("session") and then @Autowire that into another non-scoped component, Spring will generate a proxy which sits between MyService and User. This proxy will locate the User from the current session, and will delegate any calls from MyService to the proxy to the session-scoped User.

So it's perfectly safe, the MyService component will only have access to the User from the current session.

If the proxying didn't happen, then the container would fail to start, since you can't directly inject a session-scoped bean into singleton-scoped bean.

like image 135
skaffman Avatar answered Mar 31 '23 04:03

skaffman