Spring配置继承与@Import的区别

21

什么是两者之间的区别?

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

10

如何区分下面两种代码:

@Configuration class ConfigA extends 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));
    }
}

在自动装配ConfigC定义的School bean时,ConfigB先于ConfigC被导入。由于预期的School实例自动装配成功,因此Spring似乎正确地处理了依赖关系。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接