반응형

1. @Configuration 

@Configuration은 스프링 IOC Container에게 해당 클래스를 Bean 구성 Class임을 알려주는 것입니다.

 

2. @Bean

@Bean의 경우 개발자가 직접 제어가 불가능한 외부 라이브러리등을 Bean으로 만들려고 할 때 사용됩니다.

@Configuration
public class ApplicationConfig{
	@Bean
    	public ArrayList<String> array(){
        	return new ArrayList<String>();
     }      
}

  @Bean 을 이용하여 Bean을 생성한 예제 입니다. 위와 같이 ArrayList같은 라이브러리등을 Bean으로 등록하기 위해서는 별도로 해당 라이브러리 객체를 반환하는 Method를 만들고 @Bean 을 적어주면 됩니다. 위의 경우 @Bean에 아무런 값을 지정하지 않았으므로 Method 이름을 CamelCase로 변경한 것이 Bean id로 등록된다.

(ex. 메소드 이름이 arrayList()인 경우 arrayList 가 Bean id)

 

@Configuration
public class ApplicationConfig{
	@Bean(name="myarray")
    public ArrayList<String> array(){
    	return new ArrayList<String>();
    }
}

 위와 같이 @Bean 에 name이라는 값을 이용하면 자신이 원하는 id로 Bean을 등록할 수 있습니다. 어노테이션 안에 값을 입력하지 않을 경우 메소드의 이름을 CamelCase로 변경한 것이 Bean의 id가 됩니다.

@Configuration
public class ApplicationConfig{

	
    @Bean
    public ArayList<Integer> array(){
    	return new ArrayList<Integer>();
    }
    
    @Bean
    public Student student() {
    	return new Student(array());
    }
}

  의존관계가 필요할 때에는 어떻게 해결할 수 있을까요? Student 객체의 경우 새성자에서 ArrayList를 주입 받도록 코드를 짜놓았다면 이럴때에는 Bean으로 선언된 array()메소드를 호출함으로써 의존성을 주입할 수 있습니다.

 

3. @Component

@Component 어노테이션의 경우 개발자가 직접 작성한 Class를 Bean으로 등록하기 위한 어노테이션입니다.

@Component
public class Student{
	public Student(){
    System.out.println("hello");
    }
}

  Student Class는 개발자가 사용하기 위해서 직접 작성한 Class 입니다. 이러한 클래스를 Bean으로 등록하기 위해 상단에 @Component 어노테이션을 사용한 것을 볼 수 있습니다.

@Component(value="mystudent")
public class Student{
	public Student(){
    	System.out.println("hi");
    }
}

@Component 역시 아무런 추가 정보가 없다면 Class의 이름을 Camelcase로 변경한 것이 Bean id로 사용된다. 하지만 @Bean과 다르게 @Component 는 name이 아닌 value를 이용해 Bean의 이름을 지정한다.

 

 

4. @Autowired

@Component
	public class Pencil{
    ...
}

@Component(value="mystudent")
public class Student {
	@Autowired
    private Pencil pencil;
    
    public Student(){
    	System.out.println("hi");
    }
}

 

  @Component를 사용한 Bean의 의존성 주입은 @Autowired 어노테이션을 이용하여 할 수 있다. 위와 같이 Student가 Pencil에 대한 의존성을 가지고 있는 경우 @AutoWired 를 이용하여 의존성을 자동으로 주입할 수 잇다. 이때 당연히도 Pencil도 @Component 어노테이션을 가지고 있어야 한다. 그래야만 IOE Container에 Bean으로 등록되기 때문이다.

 

  @AutoWired의 경우 타입을 통해 해당 자리에 들어올 객체를 판별하여 주입해 준다. 따라서 해당 자리에 들어올 수 있는 객체가 여러개인 경우, 즉 다형성을 띄고 있는 객체타입에 @Autowired를 사용한 경우에는 @Qualifier("Bean이름")을 이용하여 해당 자리에 주입될 Bean을 명시해 주어야 한다.

 

  위의 그림에서 Goods라는 인터페이스를 Computer와 Book이 구현하고 있으므로 Person클래스의 goods 참조변수에 위치할 수 있는 Bean이 Book, Computer 두가지 이다. 때문에 @Qualifier("Bean이름")을 통해 해당 자리에 위치할 빈을 명시하였다.

 

 

5. @Bean 사용방법

public class Student{
	public Student() {
    	System.out.println("hi");
    }
}

  우선 의존성 주입 대상 Class를 생성한다. 생성자가 호출될 때 콘솔창에 "hi"를 출력하도록 했다.

@Configuration
public class ApplicationConfig {
	@Bean
    public Student student(){
    	return new Student();
    }
}

student를 Bean으로 등록하기 위해 Config Class를 임의로 만들고 @Configuration 어노테이션을 부여했다. 그 후 Student 객체를 반환하는 Method를 작성하고 @Bean 어노테이션을 부여한다.

public class Main{
	public static void main(String[] args){
    	ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        	Student student = context.getBean("student", student.class);
        }
   }

Annotation을 기반으로 Bean을 등록했으므로 AnnotationConfigApplicationContext 객체를 생성하고 매개변수로 @Configuration 어노테이션을 부여한 ApplicationConfig 클래스를 넘겨준다. 그 후 getBean을 이용하여 사용하면 된다.

 

6. @Component 사용방법

@Component 이 부여된 Class 들은 자동으로 IOC Container에 Bean으로 등록이 되는데 IOC Container에게 이러한 어노테이션이 부여된 Class를 자동으로 Bean으로 등록하라고 하기 위해서 XML파일에 따로 설정이 필요하다.

 

 

우선 XML파일을 연 뒤 하단에 Namespaces탭을 클릭하고 context를 체크한 다음 저장을 한다.

그러면 다시 Source 탭으로 돌아와 <context:component-scan base-package="com.java.ex">

</context:component-scan> 코드를 추가해 주면 준비는 완료 된다.

 

 

@Component 어노테이션을 부여한 Student 클래스이다.

 

 

Main 클래스에서는 기존 xml을 이용하여 의존성을 주입하듯이 객체를 생성하면 된다.

 

 

출처: https://galid1.tistory.com/494

 

반응형
블로그 이미지

꽃꽂이하는개발자

,