看spring容器依赖注入的时候,说的spring容器默认注入的都是单例对象,也就是spring容器里面存的都是单例对象,即一个对象只会存在一个。然后就突然想到一个常见的面试题:平时用的Controller是单例还是多例?
相信很多人都知道是单例,所以我们就来证明一下!
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date: 2021/8/4 15:06
*/
@RestController
@RequestMapping("/prototype")
//@Scope(value = "prototype")
public class PrototypeController {
@GetMapping("/test")
private void test1(){
System.out.println(this);
}
}
多例测试在Controller上加一个注解:@Scope(value = “prototype”),看代码:
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date: 2021/8/4 15:06
*/
@RestController
@RequestMapping("/prototype")
@Scope(value = "prototype")
public class PrototypeController {
@GetMapping("/test")
private void test1(){
System.out.println(this);
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date: 2021/8/4 15:06
*/
@RestController
@RequestMapping("/prototype")
public class PrototypeController {
private Integer x = 5;
@GetMapping("/test")
private void test1(){
System.out.println(++x);
System.out.println(this);
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Date: 2021/8/4 15:06
*/
@RestController
@RequestMapping("/prototype")
@Scope(value = "prototype")
public class PrototypeController {
private Integer x = 5;
@GetMapping("/test")
private void test1(){
System.out.println(++x);
System.out.println(this);
}
}
SpringMVC的controller默认是单例的,使用的时候切记不要在里面定义一些非线程安全成员变量或者其他对象,大家都会共享这个变量。也可以通过上锁解决!