zoukankan      html  css  js  c++  java
  • [Spring Boot] Singleton and Prototype

    When we use Bean to do autowired, it actually use singleton, so even we create multi instanses, they are the same:

    @SpringBootApplication
    public class In28minutesApplication {
    
        public static void main(String[] args) {
            // Application Context
            ApplicationContext applicationContext =
                    SpringApplication.run(In28minutesApplication.class, args);
            //BinarySearchImpl binarySearch = new BinarySearchImpl(new QuickSortAlgo());
            BinarySearchImpl binarySearch = applicationContext.getBean(BinarySearchImpl.class);
            BinarySearchImpl binarySearch1 = applicationContext.getBean(BinarySearchImpl.class);
            int result = binarySearch.binarySearch(new int[] {1,2,3,4}, 3);
            System.out.println(binarySearch);
            System.out.println(binarySearch1);
    
        }
    }

    It print out:

    com.example.in28minutes.BinarySearchImpl@704deff2
    com.example.in28minutes.BinarySearchImpl@704deff2

    We can also tell Spring boot to use Singleton or using proptype:

    @Component
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) // by default
    public class BinarySearchImpl { }
    
    // the same as
    
    @Component
    public class BinarySearchImpl { }

    But if we switch to Prototype, it will use differnet address in memory:

    @Component
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public class BinarySearchImpl { }
    com.example.in28minutes.BinarySearchImpl@4eaf3684
    com.example.in28minutes.BinarySearchImpl@40317ba2
  • 相关阅读:
    shell-用户权限操作
    Python 库列表
    【random】模块运用,随机数实例
    Python 原生文件读写
    Python 运用pymysql+pandas 完成连接 MySQL 数据库读
    MySQL命名、设计及使用规范
    测试for循环计算耗时
    正则表达式速查表
    MySQL8.0.21下载安装详细教程
    MySQL 修改目录重置
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10658830.html
Copyright © 2011-2022 走看看