Sunday, 5 May 2019

@Import Annotation in Spring Framework

@Import is the one such annotation used for consolidating all the configurations defined in various configuration files using @Configuration annotation. It is much similar to how we import the different XML configuration files to a single file. @Import annotation will used for the same purpose. This tutorial explains how to use @Import for Importing JavaConfig Files in Spring Projects.


If you look at the below sample code, I have created two configuration files and then imported them to the main configuration file. At the end, I need to create contaxt using only the main configuration file. If you have any questions, please write it in the comments section.

Car.java

package aid.net.basic;

public interface Car {
 public void print();
}

Toyota.java

package aid.net.basic;

import org.springframework.stereotype.Component;

@Component
public class Toyota implements Car{
 public void print(){
  System.out.println("I am Toyota");
 }
}

Volkswagen.java
package aid.net.basic;

import org.springframework.stereotype.Component;

@Component
public class Volkswagen implements Car{
 public void print(){
  System.out.println("I am Volkswagen");
 }
}


JavaConfigA.java


package aid.net.basic;

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

@Configuration
public class JavaConfigA {
 @Bean(name="volkswagen")
 public Car getVolkswagen(){
  return new Volkswagen();
 }
}

JavaConfigB.java

package aid.net.basic;

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

@Configuration
public class JavaConfigB {
 @Bean(name="toyota")
 public Car getToyota(){
  return new Toyota();
 }
}


ParentConfig.java

package aid.net.basic;

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

@Configuration
@Import({JavaConfigA.class,JavaConfigB.class})
public class ParentConfig {
 //Any other bean definitions
}

ContextLoader.java

package aid.net.basic;

import org.springframework.context.annotation.
    AnnotationConfigApplicationContext;

public class ContextLoader {
 public static void main (String args[]){
  AnnotationConfigApplicationContext context =
  new AnnotationConfigApplicationContext(ParentConfig.class);
  Car car = (Toyota)context.getBean("toyota");
  car.print();
  car = (Volkswagen)context.getBean("volkswagen");
  car.print();
  context.close();
 }
}

If you run the above example,the printed output will be,


Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...