How to Use the @Import Annotation in Spring Framework

The @Import annotation allows you to specify which configurations your Spring application should load.

You can think of this annotation as your Java class’s import statements. In this case, it’s going to import only classes with the @Configuration annotation. It’s not the exact concept, but you get the idea.

By using the @Import, you explicitly import configurations. This annotation is useful when you need specific configurations from a package that is not scanned by default for your application, and you don’t want to load all configurations in that package.

You can also use it to group some configurations and load that specific group.

Let’s see an example:

Let’s create some configuration classes that we can import using @Import:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource dataSource() {
        return new DataSource("url", "username", "password");
    }
}

@Configuration
public class ServiceConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

However, importing all configurations can be exhausting. We can create groups (like categories), to group these configurations and use @Import to achieve this.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({DataSourceConfig.class, ServiceConfig.class})
public class AppConfig {
}

Then when we are configuring our application, we can import the configuration groups using the @Import annotation.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import(AppConfig.class)
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Now you know how to configure your Spring applications using the @Import annotation.

If you like this topic, make sure to follow me. I’ll be explaining more about Spring annotations! Stay tuned!

Willian Moya (@WillianFMoya) / X (twitter.com)

Willian Ferreira Moya | LinkedIn


Posted

in

,

by