之间有什么区别
@Configuration
class ConfigA extends ConfigB {
//Some bean definitions here
}
和
@Configuration
@Import({ConfigB.class})
class ConfigA {
//Some bean definitions here
}
答案 0 :(得分:8)
之间有什么区别
@Configuration类ConfigA扩展ConfigB {//某些bean 这里的定义}和
@Configuration @Import({ConfigB.class})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
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));
}
}
ConfigB在ConfigC之前导入,而ConfigB自动装配由ConfigC(School)定义的bean。由于School实例的自动装配按预期发生,因此spring似乎正在正确处理依赖关系。