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