Difference Between Spring Configuration Inheritance and @Import

What's the difference between

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

and

 @Configuration @Import({ConfigB.class}) class ConfigA { //Some bean definitions here } 
  • And also, if we import several configuration files, how is ordering between different configurations.
  • And what happens if the imported files have dependencies between them.
+6
source share
1 answer

What's the difference between

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

@Configuration @Import ({ConfigB.class}) class ConfigA {// Some bean definitions here}

@Import will allow you to import multiple configurations, and the extension will limit you to one class, since java does not support multiple inheritance.

 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 manages dependencies and order independently, regardless of the order specified in the configuration class. See the code example below.

 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 is imported before ConfigC, while ConfigB outsource the bean specified in ConfigC (School). Since the autowiring instance of School happens as expected, spring seems to handle dependencies correctly.

+8
source

Source: https://habr.com/ru/post/979362/


All Articles