記錄

Spring) @Resource의 활용 본문

Web/Spring framework

Spring) @Resource의 활용

surhommejk 2018. 4. 28. 17:01


<?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">
<!--
    
@Resource (by name)으로 주입
목적 : 어플리케이션에서 필요로 하는 자원을 자동 연결(의존하는 빈 객체 전달)할 때 사용
@Autowired 와 같은 기능을 하며
@Autowired와 차이점은
@Autowired는 타입으로(by type),
@Resource는 이름으로(by name)으로 연결
설정위치 : 프로퍼티, setter메소드
추가설정 : CommonAnnotationBeanPostProcessor 클래스를 빈으로 등록시켜줘야 한다.
해당 설정 대신에 <context:annotation-config> 태그를 사용해도 된다.
옵션 : name

@Resource 쓰는 경우는 여러객체가 만들어질때 다른 생성자를 사용하는 경우
-->

<context:annotation-config />
    <bean id="monitorViewer" class="DI_Annotation_04.MonitorViewer"></bean>
    <bean id="xx" class="DI_Annotation_04.Recorder"></bean>
    <bean id="yy" class="DI_Annotation_04.Recorder"></bean>
    <bean id="zz" class="DI_Annotation_04.Recorder"></bean>
    <bean id="pp" class="DI_Annotation_04.Recorder"></bean>
    <bean id="kk" class="DI_Annotation_04.Recorder"></bean
</beans>


public class Recorder {

}


public class MonitorViewer {
    
    private Recorder recorder;

    public Recorder getRecorder() {
        return recorder;
    }

    @Resource(name="yy") //id 값 또는 name 을 명시해서 특정 객체 주입
    public void setRecorder(Recorder recorder) {
        this.recorder = recorder;
        System.out.println("setter 주입 성공");
    }
}


public class Program {

    public static void main(String[] args) {
        /*
        JAVA 코드 방식
        MonitorViewer viewer = new MonitorViewer();
        Recorder recorder = new Recorder();
        viewer.setRecorder(recorder);
        viewer.getRecorder();
        */
        ApplicationContext context =
                new GenericXmlApplicationContext("classpath:DI_Annotation_04/DI_Annotation_04.xml");
        MonitorViewer viewer = context.getBean("monitorViewer", MonitorViewer.class);
        System.out.println(viewer.getRecorder());
    }
}


Comments