Spring Framework - What is Import annotation?

We will start with What @Import annotation is and compare Java based configuration to xml based equivalent for Import.

1. What is @Import annotation?

@Import annotation is equivalent to <import/> element in Spring XML configuration. It helps in splitting the single Java based configuration file into small, modular, maintainable and component based configuration.

We will extend our previous post example to showcase @Import annotation use.

@Configuration
@Import(value = { DBConfig.class, WelcomeGbConfig.class })
public class HelloGbAppConfig {

}

In above code snippet, we are importing two different configuration files viz. DBConfig and WelcomeGbConfig in application level configuration file HelloGbAppConfig.

The above code is equivalent to Spring XML based configuration below.

<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-2.5.xsd"
>


<import resource="config/welcomegbconfig.xml"/>
<import resource="config/dbconfig.xml"/>

</beans>

You can see the full example code for Java based configuration on Github.



Tags: Spring Framework, Spring Core, Spring Context, Spring @Import annotation

← Back home