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 annotation in Spring allows you to load bean definitions from one or more another @Configuration files or Components. You might not want to configure all the beans in one configuration file.
In Spring, the inheritance is supported in bean configuration for a bean to share common values, properties or configurations. A child bean or inherited bean can inherit its parent bean configurations, properties and some attributes. In additional, the child beans are allow to override the inherited value.
One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined.
Yes, in large projects, having multiple Spring configurations increase maintainability and modularity. You can also upload one XML file that will contain all configs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With