📌 @Configuration
스프링 IOC Container
에게 해당 클래스를 Bean 구성 클래스임을 알려준다.
📌 @Component
vs @Bean
@Component
와 @Bean
은 둘 다 Spring(IOC) Container
에 빈을 등록하도록 하는 메타 데이터를 기입하는 어노테이션이다.
두 어노테이션의 용도는 서로 다르다.
📌 @Bean
@Bean
어노테이션의 경우 개발자가 직접 제어가 불가능한 외부 라이브러리등을 빈으로 만드려고 할 때 사용된다.
@Configuration
public class ApplicationConfig {
@Bean
public ArrayList<String> array() {
return new ArrayList<String>();
}
}
ArrayList
같은 라이브러리등을 빈으로 등록하기 위해서 별도로 해당 라이브러리 객체를 반환하는 메서드를 만들고 @Bean
을 붙여주면 된다.
@Configuration
public class ApplicationConfig {
@Bean (name = "myArray")
public ArrayList<String> array() {
return new ArrayList<String>();
}
}
@Bean
은 name
의 값을 이용하면 자신이 원하는 id
로 빈을 등록할 수 있다.
name
을 지정해주지 않고 default
으로 하면 메소드이름이 빈 이름으로 된다.
참고로 default
값을 써주는게 일반적이다.
@Configuration
public class ApplicationConfig {
@Bean
public ArrayList<Integer> array() {
return new ArrayList<Integer>();
}
@Bean
public Student student() {
return new Student(array());
}
}
Student
객체의 경우 생성자에서 ArrayList를 주입 받도록 코드를 작성했다.
이 때, 빈 객체인 array()
를 호출함으로써 의존성을 주입했다.
📌 @Component
@Component
은 개발자가 직접 작성한 클래스를 Bean으로 등록하기 위한 어노테이션이다.
@Component
public class Student {
public Student() {
System.out.println("hi");
}
}
Student
클래스는 개발자가 사용하기 위해 직접 작성한 클래스다.
이러한 클래스를 빈으로 등록하기 위해 상단에 @Component
어노테이션을 썼다.
@Component (value = "myStudent")
public class Student {
public Student() {
System.out.println("hi");
}
}
@Component
에 value
값을 지정해주면 빈 id
로 사용된다.
📌 @Autowired
@Component
를 사용한 빈의 의존성 주입은 @Autowired
을 이용하여 할 수 있다.
@Component
public class Pencil {
...
}
@Component(value = "myStudent")
public class Student{
@Autowired
private Pencil pencil;
public Student() {
System.out.println("hi");
}
}
Student
가 Pencil
에 대한 의존성을 가지고 있는 경우 @Autowired
를 이용하여 의존성을 자동으로 주입할 수 있다. 이 때 당연히 Pencil
도 @Component
를 가지고 있어야 한다. 그래야 IoC Container
에 빈으로 등록되기 때문이다.
@Autowired
경우 형(타입)을 통해 해당 자리에 들어올 객체를 판별하여 주입한다. 따라서 해당 자리에 들어올 수 있는 객체가 여러개인 경우, 즉 다형성을 띄고 있는 객체 타입에 @Autowired
를 사용한 경우 @Qualifier("Bean이름")
을 이용하여 해당 자리에 주입될 빈을 명시적으로 해주어야 한다.
Goods
라는 인터페이스를 Computer
와 Book
이 구현하고 있으므로 Person
클래스의 goods
참조변수에 위치할 수 있는 빈은 Book
, Computer
두 가지다. 그래서 @Qualifier("Bean이름")
을 통해서 해당 자리에 위치할 빈을 명시했다.
🔍 사용법
✔ @Bean
public class Student {
public Student() {
System.out.println("hi");
}
}
의존성 주입 대상 class를 생성했다. 생성자가 호출될 때 콘솔창에 hi
를 출력한다.
@Configuration
public class AppConfig {
@Bean
public Student student() {
return new Student();
}
}
Student
를 Bean으로 등록하기 위해 AppConfig
클래스를 임의로 만들고 @Configuration
을 부여했다. 그 후 Student
객체를 반환하는 Method를 작성하고 @Bean
을 부여했다.
public class Main {
public static void main(String[] args) {
ApplicationContect ac = new AnnotationConfigApplicationContext(AppConfig.class);
Student student = ac.getBean("student", Student.class);
}
}
어노테이션을 기반으로 빈을 등록했으므로 AnnotationConfigApplicationContext
객체를 생성하고 매개변수로 @Configuration
을 부여한 AppConfig
클래스를 넘겨준다. 그 후 getBean()
을 이용하여 사용하면 된다.
✔ @Component
@Component
가 부여된 클래스들은 자동으로 IoC 컨테이너에 빈으로 등록된다. IoC 컨테이너에게 이러한 어노테이션이 부여된 클래스를 자동으ㅇ로 빈으로 등록하라고 하기 위해서 XML파일에 따로 설정이 필요하다.