[Spring Boot] Singleton and Prototype

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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:

 

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 { }

 

以上是关于[Spring Boot] Singleton and Prototype的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot实战 Spring常用配置

Spring Boot教程4——@Scope注解

解决Spring中singleton的Bean依赖于prototype的Bean的问题

Spring中bean的scope详解

从头认识Spring-1.5 Bean的作用域

singleton和prototype的区别