有什么区别
@Configuration
class ConfigA extends ConfigB {
//Some bean definitions here
}
和
@Configuration
@Import({ConfigB.class})
class ConfigA {
//Some bean definitions here
}
最佳答案
what is the difference between
@Configuration class ConfigA extends ConfigB { //Some bean definitions here } and
@Configuration @Import({ConfigB.class}) class ConfigA { //Some bean definitions here }
@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 正在 Autowiring 由 ConfigC (School) 定义的 bean。由于 School 实例的 Autowiring 按预期进行,因此 spring 似乎正确处理了依赖关系。
https://stackoverflow.com/questions/27388678/
相关文章:
spring - Spring JUnit 测试中的自动模拟实例化
spring - jar 如何在使用它的 Web 应用程序中传播漏洞?
java - 使用spring boot(安全)和keycloak启用角色身份验证?
java - Spring 验证与 Hibernate 验证
java - Spring Integration Kafka Consumer Listener
java - Spring Boot + Spring Data Multi-Tenancy
java - Spring MVC 3.2 - 错误页面的内容协商?
java - 单个 hibernate session 中的多个事务(使用 Spring)