会话范围bean作为Spring MVC Controller的类属性 [英] Session scoped bean as class attribute of Spring MVC Controller

查看:129
本文介绍了会话范围bean作为Spring MVC Controller的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户类:

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

和一个Controller类:

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";
    }
}

我使会话​​无效,以便下次我得到到/ users,我得到另一个用户。由于用户的会话范围,我期待不同的用户,但我得到了相同的用户。我检查了调试模式,它在内存中是相同的对象ID。我的bean被声明为:

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>

我刚开始春天,所以我显然做错了什么。我希望每个会话都有一个User实例。如何?

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

推荐答案

这是预期的行为。使用< aop:scoped-proxy /> 标记bean时,会为其创建代理。如果存在bean的接口,则创建java动态代理,否则创建基于CGLIB的代理 - 在您的情况下,因为您的User类没有父类/接口,所以将为您创建基于CGLIB的代理。

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.

现在的问题是,这个代理将被注入到你的所有类中,这就是为什么你只看到1个实例(基本上是代理)的原因,代理知道如何管理范围 - 只要你经历了类的方法,所以在你的情况下,如果你通过getter和setter调用来获取User类的属性,你应该看到适合于会议反映出来。

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.

这篇关于会话范围bean作为Spring MVC Controller的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆