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:
[email protected] [email protected]
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 { }
[email protected] [email protected]
原文地址:https://www.cnblogs.com/Answer1215/p/10658830.html
时间: 2024-10-14 00:56:51