@Autowired注解 注入的是单例还是多例
前言:我在用@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
?
默认情况下,它们是单身人士。如果范围更改为原型,您将获得单独的对象。
posted on 2022-06-20 19:34 ExplorerMan 阅读(1271) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
2019-06-20 MySQL单表数据量过千万,采坑优化记录,完美解决方案
2019-06-20 MySQL到底能支持多大的数据量?
2017-06-20 webpack入门(四)——webpack loader 和plugin
2014-06-20 Tomcat:Several ports are already in use问题
2014-06-20 Java Web HelloWorld!
2014-06-20 手把手图文教你eclipse下如何配置tomcat
2014-06-20 Tomcat安装及配置教程