前言:我在用@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";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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++);
}
}
1
2
3
4
5
6
7
8
9
10
11
控制台输出:用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”)的作用
————————————————
版权声明:本文为CSDN博主「奋斗百天我要考山东交通职业学院」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_49078070/article/details/124017087
我正在维护一个旧应用程序,但不熟悉 Spring Framework。我正在研究一个目前看起来像这样的课程:
public class Foo {
@Resource(name = "fb")
private FooBar fb;
@Resource
private FooBar2 fb2;
@Autowired
private FooBar3 fb3 = null;
...
}
和一个如下所示的 XML 文件:
<beans xmlns="http://www.springframework.org/schema/beans" ... >
<context:annotation-config/>
...
<bean id="fb3" class="FooBar3"/>
...
</beans>
在其他一些方法中,类 Foo 被实例化:
void carryOutSomeFoobarring() {
Foo f = new Foo();
...(use f)...
}
如果从两个不同的线程同时调用 CarryOutSomeFoobarring,当然会有两个单独的局部变量 Foo 实例f
。但是两个字段实例会f.fb
引用同一个注入FooBar
对象吗?怎么样f.fb2
和f.fb3
?
默认情况下,它们是单身人士。如果范围更改为原型,您将获得单独的对象。