Session scoped bean as class attribute of Spring M

2019-02-14 23:28发布

问题:

I have a User class:

@Component
@Scope("session")
public class User {
    private String username;
}

And a Controller class:

@Controller
public class UserManager {
    @Autowired
    private User user;

    @ModelAttribute("user")
    private User createUser() {
        return user;
    }

    @RequestMapping(value = "/user")
    public String getUser(HttpServletRequest request) {
        Random r = new Random();
        user.setUsername(new Double(r.nextDouble()).toString());
        request.getSession().invalidate();
        request.getSession(true);
        return "user";
    }
}

I invalidate the session so that the next time i got to /users, I get another user. I'm expecting a different user because of user's session scope, but I get the same user. I checked in debug mode and it is the same object id in memory. My bean is declared as so:

    <bean id="user" class="org.synchronica.domain.User">
        <aop:scoped-proxy/>
    </bean>

I'm new to spring, so I'm obviously doing something wrong. I want one instance of User for each session. How?

回答1:

This is the expected behavior. When you tag a bean with <aop:scoped-proxy/> a proxy is created for it. If there is an interface for the bean a java dynamic proxy is created else a CGLIB based proxy is created - in your case since your User class does not have a parent class/interface a CGLIB based proxy will be created for you.

Now the catch is that this proxy is what will be injected into all your classes, that is the reason why you are seeing only 1 instance(of the proxy essentially), the proxy knows how to manage the scope though - As long as you go through the methods of your class, so in your case if you go through getter and setter calls to get to the properties of your User class, you should see values appropriate to the session reflected.