The @Import
annotation is used to import one or more configuration classes into the current configuration class or configuration file. This annotation is particularly useful when you want to modularize your configuration and reuse existing configuration classes in different parts of your Spring Boot application.
Let’s create a simple example to demonstrate the usage of @Import
annotation.
Step 1: Create Configuration Classes
First, let’s create a couple of configuration classes that we want to import.
Step 2: Create Main Configuration Class
Now, let’s create a main configuration class where we’ll use the @Import
annotation to import the DatabaseConfig
and SecurityConfig
classes.
In this example, AppConfig
is the main configuration class, and it imports DatabaseConfig
and SecurityConfig
using the @Import
annotation.
Step 3: Use the Main Configuration Class in the Application
Now, you can use AppConfig
as the main configuration class when starting your Spring Boot application.
Here, @SpringBootApplication
is used to enable the Spring Boot features, and the @Import(AppConfig.class)
annotation is used to import the configuration from AppConfig
.
Step 4: Test the Application
You can now run your Spring Boot application and test if the configurations from DatabaseConfig
and SecurityConfig
are properly imported and applied.
This is a basic example, and in a real-world scenario, you might have more complex configurations that you want to modularize and reuse across different parts of your application. The @Import
annotation provides a clean way to achieve this modularization in your Spring Boot projects.