@Import in springboot

  • Used to import multiple @Configuration files’s in a single @Configuration file
  • This way you need not add all the configuration into a single file instead you can group them

Example :

Student Class :

package otherdemo;

public class Student {
	private String name;
	public Student(String name) {		
		this.name = name;	
	}
	public String getName() {		
		return name;	
	}
}

StudentConfig

package otherdemo;

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

@Configuration
public class StudentConfiguration {
	@Bean("Student")//important to name the bean else bean name is getStudent
	public Student getStudent() {		
		return new Student("Tyson");	
	}
}

Teacher Class

package otherdemo;

public class Teacher {
	String name;
	public Teacher(String name) {		
		this.name = name;	
	}
	public String getName() {		
		return name;	
	}
}

Teacher Config

package otherdemo;

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

@Configuration
public class TeacherConfiguration {
	@Bean("Teacher")//important to name the bean else bean name is getTeacher
	public Teacher getTeacher() {		
		return new Teacher("Justin");	
	}
}

MasterConfiguaration

package otherdemo;

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

@Configuration
@Import({TeacherConfiguration.class,StudentConfiguration.class})
public class MasterConfiguaration {
}

Main Class

package otherdemo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
	public static void main(String[] args) {
		ApplicationContext app = new AnnotationConfigApplicationContext(MasterConfiguaration.class);
		Student obj1 = (Student) app.getBean("Student");
		System.out.println("\n\n\n"+obj1.getName());
	}
}

Leave a Comment