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

时间:2014-12-09 20:56:16

标签: java spring spring-java-config

之间有什么区别
@Configuration
class ConfigA extends ConfigB {
   //Some bean definitions here
}

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

1 个答案:

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