Reputation: 1089
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
}
Upvotes: 20
Views: 15982
Reputation: 6180
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 would allow you to import multiple configurations while extending will restrict you to one class since java doesn't 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 the dependencies and the order by its own irrespective of the order given in the configuration class. See the below sample code.
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 is autowiring the bean defined by ConfigC (School). Since the autowiring of School instance happens as expected, spring seems to be handling the dependencies correctly.
Upvotes: 10