你来,我们一起精进!你不来,我和你的竞争对手一起精进!
先说答案。
❝Controller 默认是单例的,不要使用非静态的成员变量,否则会发生数据逻辑混乱。正因为单例所以不是线程安全的。 ❞
我们下面来简单的验证下:
package com.xttblog.springbootdemo.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 业余草,公众号
*/
@Controller
public class ScopeTestController {
private int num = 0;
@RequestMapping("/testScope")
public void testScope() {
System.out.println(++num);
}
@RequestMapping("/testScope2")
public void testScope2() {
System.out.println(++num);
}
}
我们首先访问 http://localhost:8080/testScope,得到的答案是1。
然后我们再访问 http://localhost:8080/testScope2,得到的答案是 2。
得到的不同的值,这是线程不安全的。
接下来我们再来给controller增加作用多例 @Scope("prototype")。
package com.xttblog.springbootdemo.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author 业余草,公众号
*/
@Controller
@Scope("prototype")
public class ScopeTestController {
private int num = 0;
@RequestMapping("/testScope")
public void testScope() {
System.out.println(++num);
}
@RequestMapping("/testScope2")
public void testScope2() {
System.out.println(++num);
}
}
我们依旧首先访问 http://localhost:8080/testScope,得到的答案是 1。
然后我们再访问 http://localhost:8080/testScope2,得到的答案还是 1。
相信大家不难发现:
❝单例是不安全的,会导致属性重复使用。 ❞
spring bean 作用域有以下 5 个:
(下面是在web项目下才用到的)
以上,知识点虽然简单。但是,我在面试工作 3 年的程序员的时候,大多数人还回答不出来。虽然,面试者可能在中间件方面有所实战,但是越简单的知识点,了解的人反而不多!