如何在 Controller 中使用 Session Scoped Component
How to use Session Scoped Component in Controller
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";
}
}
但是每次我 运行 这个控制器 (/greeting),即使我关闭浏览器,它总是会增加 i,所以我如何在 Singleton Controller 中使用这个 Session Scoped Component?
代理只拦截方法调用。在您的情况下,会发生以下情况:
@Autowired private Count count;
创建一个看起来像 count 实例的代理,因此也有一个 i
字段。但是由于代理不是真实的东西,所以 Count
构造函数没有被调用并且 i
保持未初始化状态。这就是为什么你总是得到 null
.
现在介绍一个getter:
class Count {
...
public Integer getI() {
return i;
}
当您调用 getI()
时,代理首先检查当前会话是否存在 Count
bean 的实例。如果有 none,则创建一个。这也意味着 Count
构造函数被调用并且 i
现在被初始化。然后代理将调用委托给 bean 的 getI()
,这将 return i
.
的值
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";
}
}
但是每次我 运行 这个控制器 (/greeting),即使我关闭浏览器,它总是会增加 i,所以我如何在 Singleton Controller 中使用这个 Session Scoped Component?
代理只拦截方法调用。在您的情况下,会发生以下情况:
@Autowired private Count count;
创建一个看起来像 count 实例的代理,因此也有一个 i
字段。但是由于代理不是真实的东西,所以 Count
构造函数没有被调用并且 i
保持未初始化状态。这就是为什么你总是得到 null
.
现在介绍一个getter:
class Count {
...
public Integer getI() {
return i;
}
当您调用 getI()
时,代理首先检查当前会话是否存在 Count
bean 的实例。如果有 none,则创建一个。这也意味着 Count
构造函数被调用并且 i
现在被初始化。然后代理将调用委托给 bean 的 getI()
,这将 return i
.