前言:我在用@Autowired注解时候一直 好奇 他是每次给我的对象是同一个 还是 每次new一个新的给我 看了一些文档后发现**@Autowired是单例模式 因为它:在注入之前,对象已经实例化,**这个结论与我上篇文章单双例的结合相吻合@Scope(“prototype“) 注入单例 多例
1.StudentServiece开启多例
@RestController
public class StudentController {
private static int demo = 0; //静态的
private int index = 0; //非静态
@Autowired
StudentService studentService;
@RequestMapping("/test")
public String test() {
System.out.println(demo++ + " | " + index++);
studentService.fang();
return "ok";
}
}
StudentServiece注入容器是多例形式
@Service
@Scope(value = "prototype")
public class StudentService {
private static int ggg = 0; //静态的
private int www = 0; //非静态
public void fang(){
System.out.println(" "+ggg++ + " | " + www++);
}
}
控制台输出:用postman连续访问三次接口
看出 studentService一直是同一个对象
2.StudentController StudentServiece同时开启多例
StudentController 类上也加上@Scope(value = “prototype”)注解
控制台输出:用postman连续访问三次接口
controller的数字和serviece注入的输出都是 多例模式 是多个对象调用方法 Controller中 非静态变量一直为0
是因为Controller层的@Scope(value = “prototype”) Serviece中 非静态变量一直为0
是因为Controller和Serviece共同@Scope(value = “prototype”)的作用