2016년 11월 11일 금요일

[자바강의,스프링/SpringBoot,Framework강의추천_탑크리에듀]#10.스프링DI(세터주입,XML기반예제)

#10.스프링DI(세터주입,XML기반예제)

세터 주입(Setter Injection) – XML 기반

n  세터주입은 클래스 사이의 의존관계를 연결시키기 위해 setter 메소드를 이용하는 방법이다.

[Emp.java]
package edu.ojc.setter1;
interface Emp {
 public abstract void gotoOffice();
 public abstract void getoffWork();
}

[Programmer.java]
package edu.ojc.setter1;
class Programmer implements Emp {
public void gotoOffice() {
           System.out.println("프로그래머 출근 합니다.");
}
public void  getoffWork() {
           System.out.println("프로그래머 퇴근 합니다.");
}
}

[Designer.java]
package edu.ojc.setter1;

class Designer implements Emp {
public void gotoOffice() {
           System.out.println("디자이너 출근 합니다.");
}
public void  getoffWork() {
           System.out.println("디자이너 퇴근 합니다.");
}
}

[Develop.java]
package edu.ojc.setter1;

public class Develope {
           Emp emp;

           public void setEmp(Emp emp) {
                     this.emp = emp;
           }
           void coding() {
           emp.gotoOffice();
                     System.out.println("개발합니다...");
                     emp.getoffWork();
           }
}

[Src/main/resources/ojc1.xml] – p 네임스페이스를 이용한 세터주입
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="programmer" class="edu.ojc.setter1.Programmer" />
<bean id="designer" class="edu.ojc.setter1.Designer" />
<bean id="develope" class="edu.ojc.setter1.Develope" p:emp-ref="programmer" />
<!-- 
//아래처럼 Property 태그를 이용해도 된다.
<bean id="develope" class="edu.ojc.setter1.Develope">
<property  name="emp“><ref bean="programmer"/></property>
</bean>
<bean id="develope" class="edu.ojc.setter1.Develope">
<property name="emp" ref="programmer"/> </bean>
 -->
</beans>

[TestMain.java]
package edu.ojc.setter1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
public static void main(String[] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("ojc1.xml");

      Develope dev = (Develop)context.getBean("develope");
      dev.coding();
}
}

댓글 없음:

댓글 쓰기