記錄

Spring) @Autowired의 활용 (기본) 본문

Web/Spring framework

Spring) @Autowired의 활용 (기본)

surhommejk 2018. 4. 28. 16:32

.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Annotation 기반으로 DI 작업(Java 제공 : Annotation, SpringFramework 제공:Annotation )
@Autowired (자동 주입 > By Type)
목적 : 의존관계를 자동설정할 때 사용하며 [타입]을 이용하여 의존하는 [객체를 삽입]해 준다.
그러므로 [해당 타입의 bean객체]가 존재(IOC)하지 않거나 또는
[2개 이상 존재할 경우 스프링]은 예외를 발생시키게 된다.

설정 위치 : 생성자, 필드, 메소드(굳이 setter메소드가 아니여도 된다)

**@Autowired 적용되지 않는 경우 (By Type)
1. injection 되는 같은 타입의 bean IOC컨테이너 없는 경우 (exception 발생)

2. injection 되는 [타입] 여러개가 있는 경우 (exception 발생)
<bean id="xx" class="DI_Annotation_01.Recorder"></bean>   
<bean id="yy" class="DI_Annotation_01.Recorder"></bean>
3.예외적으로 같은 타입의 bean 이 여러개 있다 하더라도
public void RecordMethod(Recorder rec) > parameter 이름이
bean id 값 하고 같으면 알아서 injection
-->

    <!-- annotation을 사용하기 위한 전제 조건 -->
    <!-- 1. @Autowired 적용을 위한 타입 객체가 생성되어 있어야 함 -->
    <!-- 2. .xml에 <context:annotation-config />가 선언되어 있어야 함-->

    <!-- annotation을 사용하기 위해서 annotation을 담당해주는 객체를 생성 -->
    <!-- AutowiredAnnotationBeanPostProcessor라는 bean 객체를 만드는 행위이다 -->
<context:annotation-config />
    <bean id="viewer" class="DI_Annotation_01.MonitorViewer"></bean>
    <bean id="recorder" class="DI_Annotation_01.Recorder"></bean>
    <!-- 여기서 bean의 id가 'recorder'일 필요는 없다. @Autowired는 type으로 찾아서
injection해주기 때문에 recorder든 뭐든 bean의 id는 중요치 않다
bean으로 만들어 졌는지의 여부가 중요하다. 만들어 졌다면 type으로 찾아서
@Autowired가 명시된 곳에 injection을 해주게 된다 -->
    
</beans>







.java

public class MonitorViewer {
    
    private Recorder recorder;
    
    public Recorder getRecorder() {
        return recorder;
    }
    

// @Autowired가 선언됨으로써
// 해당 메소드에서 의존하고 있는 객체(구동을 위해 필요한 객체)를
// type으로 찾아서 이와 일치하는 객체를 bean 에서 찾아서 이곳에 injection하게 된다
    @Autowired
    public void setRecorder(Recorder recorder) {
                                
        this.recorder = recorder;
    }
}


public class Recorder {

}


public class Program {

    public static void main(String[] args) {
        
        /*
        JAVA 코드 실행
        MonitorViewer viewer = new MonitorViewer();
        
        Recorder recorder = new Recorder();
        viewer.setRecorder(recorder);
            >>> 위 두 줄을 @Autowired가 알아서 처리해주는 것이다
            >>> bean에서 가져와서 injection 해주는 것!!!
        
        System.out.println(viewer.getRecorder());
        */
        
        ApplicationContext context =
                new GenericXmlApplicationContext("classpath:DI_Annotation_01/DI_Annotation_01.xml");
        MonitorViewer viewer = context.getBean("viewer",MonitorViewer.class);
        System.out.println(viewer.getRecorder());
    }

}



<정리>


@Autowired는 xml에서 따로 property 설정을 해줄 필요가 없이 setter 함수에 @Autowired를 선언해 줌으로써 의존 관계의 객체를 bean에서 type으로 찾아와 자동으로 injection해주는 것이다.


이를 위해서는 

1. xml에서 bean으로 객체를 생성해 주어야 하며, 

2. 이를 돕기 위한 AutowiredAnnotationBeanPostProcessor라는 bean 객체를

만들어야 한다. AutowiredAnnotationBeanPostProcessor라는 bean 객체를 만드는 행위는

간단히 <context:annotation-config />로 대체 될 수 있다.






cf) @Autowired가 적용되지 않기 위해서는?

아래와 같이 required = false 처리를 해주면 자동으로 injection이 되지 않는다


    @Autowired(required = false) //Default > true (무조건 injection)
    public void setRecorder(Recorder recorder) {
        this.recorder = recorder;
        System.out.println("setter 주입 성공");
    }


Comments