• @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.fb2f.fb3

    默认情况下,它们是单身人士。如果范围更改为原型,您将获得单独的对象。

     
  • 相关阅读:
    洛谷 P2486 [SDOI2011]染色 树链剖分
    js 随机打乱数组
    js 中concat()和slice()方法介绍
    encodeURIComponent() 函数的使用
    mysql中LOCATE和CASE WHEN...THEN...ELSE...END结合用法
    Java多态的理解
    JQuery UI完成自动匹配的的下拉列表步骤
    marquee 标签的使用介绍
    orcale数据恢复
    sql中replace的用法
  • 原文地址:https://www.cnblogs.com/ExMan/p/16394460.html
Copyright © 2020-2023  润新知