2016년 11월 16일 수요일

[자바교육,스프링교육(Spring Framework/Boot)추천_탑크리에듀]#11.스프링DI(세터주입,어노테이션기반예제)

#11.스프링DI(세터주입,어노테이션기반예제)

세터 주입(Setter Injection) – 어노테이션 기반

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

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

[Designer.java]
package edu.ojc.setter2;
import org.springframework.stereotype.Service;

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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class Develope {
           Emp emp;
           @Autowired
           @Qualifier("programmer")
           public void setEmp(Emp emp) {
                     this.emp = emp;
           }
           void coding() {
           emp.gotoOffice();
                     System.out.println("개발합니다...");
                     emp.getoffWork();
           }
}

[Src/main/resources/ojc2.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
           <context:component-scan base-package="edu.ojc.setter2"/>
</beans>

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

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();
}
}

댓글 없음:

댓글 쓰기