📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
@Import Annotation Overview
- The @Import annotation indicates one or more @Configuration classes to import.
- @Bean definitions declared in imported @Configuration classes should be accessed by using @Autowired injection. Either the bean itself can be autowired, or the configuration class instance declaring the bean can be autowired.
- The @Import annotation may be declared at the class level or as a meta-annotation.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="common/spring-common.xml"/>
<import resource="dao/spring-dao.xml"/>
<import resource="beans/spring-beans.xml"/>
</beans>
Spring @Import Annotation Example
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}
Load Multiple Configuration Class Files Example
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
@Configuration
public class ConfigC {
@Bean
public C c() {
return new C();
}
}
@Configuration
@Import(value = {ConfigA.class, ConfigB.class, ConfigC.class})
public class ConfigD {
@Bean
public D d() {
return new D();
}
}
Comments
Post a Comment
Leave Comment