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

有什么区别

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

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)

spring - 如何在运行时将新用户添加到 Spring Security

java - 使用具有不同 AuthenticationProviders 的多个 WebSecur