Spring @Import Annotation Example - RameshMF/spring-boot-developers-guide GitHub Wiki

In this article, we will discuss how to use Spring @Import annotation with examples.

@Import Annotation Overview

  • @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.

  • @Import annotation may be declared at the class level or as a meta-annotation.

If XML or other non-@Configuration bean definition resources need to be imported, use the @ImportResource annotation instead.

In Spring XML-based configuration we use element to load multiple Spring bean configuration files. Example:

<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

Spring provides the alternative @Import annotation which allows for loading @Bean definitions from another configuration class.

@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();
    }
}

Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be supplied explicitly:

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

@Import annotation also can be used to load @Bean's from multiple configuration class files.

@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();
    }
}
⚠️ **GitHub.com Fallback** ⚠️