如何在控制器中使用会话作用域组件 [英] How to use Session Scoped Component in Controller

查看:134
本文介绍了如何在控制器中使用会话作用域组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Count.java:

Count.java:

@Component
@Scope(value = "session",proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Count {
    Integer i;
    public Count() {
        this.i = 0;
    }

控制器:

@Controller
public class GreetingController {
    @Autowired private Count count;
    @RequestMapping("/greeting")
    public String greetingForm(Model model) {
        if(count.i == null) i == 0;
        else i++;
        model.addAttribute("count",String.valueOf(count.i));
        return "greeting";
    }
}

但是,每当我运行此控制器(/问候)时,即使关闭浏览器,它也始终会增加i,那么如何在Singleton Controller中使用此会话范围组件?

But every i run this controller (/greeting), it always increase the i even when I close the browser, so how can i use this Session Scoped Component in Singleton Controller?

推荐答案

代理仅拦截方法调用.在您的情况下,会发生以下情况:

The proxy only intercepts method calls. In your case the following happens:

@Autowired private Count count;

创建一个看起来像count实例的代理,因此也有一个i字段.但是由于代理不是真实的东西,因此不会调用Count构造函数,并且i仍未初始化.这就是为什么您总是得到null.

Creates a proxy that looks like an instance of count and therefore also has an i field. But since the proxy is not the real thing, the Count constructor is not called and iremains uninitialized. That's why you always get null.

现在让我们介绍一个吸气剂:

Now let's introduce a getter:

class Count {
  ...
  public Integer getI() {
    return i;
  }

当调用getI()时,代理首先检查当前会话中是否存在Count bean的实例.如果不存在,则创建一个.这也意味着Count构造函数被调用,并且i现在被初始化.然后,代理将调用委派给Bean的getI(),该调用将返回i的值.

When you invoke getI() the proxy first checks if there is an instance of the Count bean for the current session. If there is none, one is created. This also means that the Count constructor is called and i is now initalized. Then the proxy delegates the call to the bean's getI() that will return the value of i.

这篇关于如何在控制器中使用会话作用域组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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