'Programing/Spring'에 해당되는 글 21건

  1. [Spring] 의존관계 주입

[Spring] 의존관계 주입

의존관계 주입


1. 참조 Bean 주입하기



(1) 소스상에서 보는 bean 참조를 주입하는 모습

1) beans.xml

<?xml version="1.0" encoding="UTF-8" ?>

<beans xmlns="http://www.springframework.org/schema/beans"

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-3.0.xsd">

    <bean id="messageBean" class="sample1.MessageBeanImpl" >

        <constructor-arg>

            <value>Spring</value>

        </constructor-arg>

        <property name="greeting">

            <value>Hello, </value>

        </property>     

        <property name="outputter">

            <ref local="outputter" />

        </property>

    </bean>

    <bean id="outputter" class="sample1.FileOutputter">

        <property name="filePath">

            <value>out.txt</value>

        </property>

    </bean>

</beans>


2)  MessageBeanImpl.java

import java.io.IOException;

public class MessageBeanImpl implements MessageBean {

    

    private String name;

    private String greeting;

    private Outputter outputter;


    public MessageBeanImpl(String name) {

        this.name = name;

    }

        

    public void setGreeting(String greeting) {

        this.greeting = greeting;

    }

    

    public void sayHello() {

        String message = greeting + name + "!";

        System.out.println(message);

        try {

            outputter.output(message);

        } catch(IOException e) {

            e.printStackTrace();

        }

    }

    

    public void setOutputter(Outputter outputter) { 

        this.outputter = outputter;

    }

    // id=outputter 참조변수가 id=messageBean의 property=outputter의 매개변수로 온 형태--> 의존성 주입

}


2. @Autowired 방식으로 주입


의존관계를 설정하는 또다른 방법이 바로 @Autowired이다.

@Autowired 어노테이션을 사용하면 Autowiring은 'byType', 즉, Bean의 타입을 사용해서 연결하는 방법으로 실행된다. 그리고 설정 파일 beans.xml에 <context-annotation-config/> 요소를 추가한다.

MessageBeanImpl 클래스의 outputter 프로퍼티는 @Autowired 어노테이션에 의해 자동의로 스프링이 의존관계를 설정하기 때문에 설정 파일에서 제거한다.

덧붙이면, @Autowired를 어노테이션을 적용하려면, BeanFactory가 아니라 ApplicationContext를 사용해야 한다.

--> @Autowired를 사용할 경우 바뀌는 부분을 표시해보겠다.


(1) @Autowired 방식

1) beans.xml

<?xml version="1.0" encoding="UTF-8" ?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

              http://www.springframework.org/schema/context

              http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/> 

   <bean id="messageBean" class="sample1.MessageBeanImpl" >

        <constructor-arg>

            <value>Spring</value>

        </constructor-arg>

        <property name="greeting">

            <value>Hello, </value>

        </property>        

        <property name="outputter">

            <ref local="outputter" />

        </property>

    </bean>

    <bean id="outputter" class="sample1.FileOutputter">

        <property name="filePath">

            <value>out.txt</value>

        </property>

    </bean>

</beans>



2) MessageBeanImpl.java

import java.io.IOException;

public class MessageBeanImpl implements MessageBean {

    

    private String name;

    private String greeting;

    private Outputter outputter;

    @Autowired

    private Outputter outputter;

    // MessageBeanImpl 클래스가 이름이 outputter인 프로퍼티를 갖고 있다면 이름(id)이 outputter인 빈 객체가 프로퍼티의 값으로 전달된다.

    // 이렇게 하면 설정(setter) 메서드를 기술할 필요가 없다. 스프링이 필드에 직접 주입한다.

    // 즉, <property>에 주입할 필요 없이 필드의 데이터 타입을 체크하여 일치하는 외부의 Bean 주입받아 사용할 수 있다. 

    public MessageBeanImpl(String name) {

        this.name = name;

    }

        

    public void setGreeting(String greeting) {

        this.greeting = greeting;

    }


   @Autowired

   public void setOuputter(Outputter outputter){

        this.outputter = outputter;

   }

    

    public void sayHello() {

        String message = greeting + name + "!";

        System.out.println(message);

        try {

            outputter.output(message);

        } catch(IOException e) {

            e.printStackTrace();

        }

    }

    

    public void setOutputter(Outputter outputter) {

        this.outputter = outputter;

    }

}




'Programing > Spring' 카테고리의 다른 글

[Spring] iBatis 1  (0) 2014.12.16
[Spring] web.xml 기본 설정  (1) 2014.12.13
[spring] 스프링 MVC 인터페이스 구현 클래스  (0) 2014.12.13
[Spring] 스프링 MVC 패턴 개요  (0) 2014.12.13
[Spring] AOP 용어 설명  (0) 2014.12.13