gpt4 book ai didi

java - Spring配置继承和@Import的区别

转载 作者:IT老高 更新时间:2023-10-28 13:43:51 25 4
gpt4 key购买 nike

有什么区别

@Configuration
class ConfigA extends ConfigB {
//Some bean definitions here
}

@Configuration
@Import({ConfigB.class})
class ConfigA {
//Some bean definitions here
}
  1. 如果我们要导入多个配置文件,那么各个配置之间的排序是如何发生的。
  2. 如果导入的文件之间存在依赖关系会怎样

最佳答案

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 似乎正确处理了依赖关系。

关于java - Spring配置继承和@Import的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27388678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com