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

2022-09-02 10:53:01

两者之间有什么区别

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

@Configuration
@Import({ConfigB.class})
class ConfigA {
  //Some bean definitions here
}
  1. 此外,如果我们要导入多个配置文件,那么在各种配置之间如何进行排序。
  2. 如果导入的文件之间有依赖关系,会发生什么情况

答案 1

两者之间有什么区别

@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

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(学校)定义的 Bean。由于学校实例的自动布线按预期发生,因此 spring 似乎正在正确处理依赖项。


答案 2

推荐