1. 程式人生 > 其它 >Spring自動注入之多方法的選擇

Spring自動注入之多方法的選擇

技術標籤:springspring

假如一個類存在多個構造方法,Spring會選擇哪個方法來例項化呢?使用預設的構造方法或者通過Autowire(required=true)來指定的構造方法,那麼以下情形呢?在這裡在三個構造方法上添加了@Autowired(required = false)註解。你認為在Spring例項化BeanConfig型別bean的時候會呼叫哪個構造方法呢?

@Configuration
public class BeanConfig {

    public BeanConfig() {
        System.out.println("BeanConfig=====================0======================="
); } @Autowired(required = false) public BeanConfig(BeanFactory beanFactory) { System.out.println("BeanConfig=====================1======================="); } @Autowired(required = false) public BeanConfig(BeanFactory beanFactory, ApplicationContext applicationContext)
{ System.out.println("BeanConfig=====================2======================="); } @Autowired(required = false) public BeanConfig(BeanFactory beanFactory, ApplicationContext applicationContext, ResourceLoader resourceLoader) { System.out.println("BeanConfig=====================3======================="
); } }

如果針對一個bean定義了多個工廠方法,在例項化的時候又會選擇哪個呢?比如下面的這個例子:定義一個名稱為為serviceLocator的bean,但是對應了四個工廠方法,每個工廠方法的引數個數不一樣。

@Bean
public DefaultServiceLocator serviceLocator() {
    System.out.println("serviceLocator=====================0=======================");
    return new DefaultServiceLocator();
}


@Bean
public DefaultServiceLocator serviceLocator(BeanFactory beanFactory) {
    System.out.println("serviceLocator=====================1=======================");
    return new DefaultServiceLocator();
}

@Bean
public DefaultServiceLocator serviceLocator(BeanFactory beanFactory, ApplicationContext applicationContext) {
    System.out.println("serviceLocator=====================2=======================");
    return new DefaultServiceLocator();
}

@Bean
public DefaultServiceLocator serviceLocator(BeanFactory beanFactory, ApplicationContext applicationContext, ResourceLoader resourceLoader) {
    System.out.println("serviceLocator=====================3=======================");
    return new DefaultServiceLocator();
}

你認為Spring在例項化serviceLocator這個Bean的時候會使用哪個構造方法呢?

Finally, a single class may hold multiple @Bean methods for the same bean, as an arrangement of multiple factory methods to use depending on available dependencies at runtime. This is the same algorithm as for choosing the “greediest” constructor or factory method in other configuration scenarios: The variant with the largest number of satisfiable dependencies is picked at construction time, analogous to how the container selects between multiple @Autowired constructors。