码迷,mamicode.com
首页 > 编程语言 > 详细

[Spring Boot] Singleton and Prototype

时间:2019-04-05 15:40:20      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:config   []   address   run   app   sam   arc   get   text   

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

 

[Spring Boot] Singleton and Prototype

标签:config   []   address   run   app   sam   arc   get   text   

原文地址:https://www.cnblogs.com/Answer1215/p/10658830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!