Spring配置继承和@Import之间的区别

Shi*_*hya 12 java spring spring-java-config

有什么区别

@Configuration
class ConfigA extends ConfigB {
   //Some bean definitions here
}
Run Code Online (Sandbox Code Playgroud)

@Configuration
@Import({ConfigB.class})
class ConfigA {
  //Some bean definitions here
}
Run Code Online (Sandbox Code Playgroud)
  1. 而且如果我们要导入多个配置文件,那么在各种配置中如何进行排序.
  2. 如果导入的文件之间存在依赖关系,会发生什么

And*_*sne 8

有什么区别

@Configuration类ConfigA扩展了ConfigB {//这里的一些bean定义}和

@Configuration @Import({ConfigB.class})类ConfigA {//这里有一些bean定义}

@Import允许您导入多个配置,而扩展会将您限制为一个类,因为java不支持多重继承.

also if we are importing multiple configuration files, how does the ordering happen among the various config.
And what happens if the imported files have dependencies between them
Run Code Online (Sandbox Code Playgroud)

Spring不管配置类中给出的顺序如何管理依赖关系和顺序.请参阅以下示例代码.

public class School {
}

public class Student {
}

public class Notebook {
}

@Configuration
@Import({ConfigB.class, ConfigC.class})
public class ConfigA {

    @Autowired
    private Notebook notebook;

    @Bean
    public Student getStudent() {
        Preconditions.checkNotNull(notebook);
        return new Student();
    }
}

@Configuration
public class ConfigB {

    @Autowired
    private School school;

    @Bean
    public Notebook getNotebook() {
        Preconditions.checkNotNull(school);
        return new Notebook();
    }

}

@Configuration
public class ConfigC {

    @Bean
    public School getSchool() {
        return new School();
    }

}

public class SpringImportApp {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigA.class);

        System.out.println(applicationContext.getBean(Student.class));
        System.out.println(applicationContext.getBean(Notebook.class));
        System.out.println(applicationContext.getBean(School.class));
    }
}
Run Code Online (Sandbox Code Playgroud)

ConfigB在ConfigC之前导入,而ConfigB自动装配由ConfigC(School)定义的bean.由于School实例的自动装配按预期发生,因此spring似乎正在正确处理依赖关系.