#12.스프링DI(생성자주입,XML기반예제)
생성자 주입(Constructor Injection) – XML 기반
[Emp.java]
package
edu.ojc.constructor1;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
interface Emp {
public abstract void
gotoOffice();
public abstract void getoffWork();
}
[Programmer.java]
package
edu.ojc.constructor1;
class Programmer implements Emp
{
public void gotoOffice()
{
System.out.println("프로그래머 출근 합니다.");
}
public void getoffWork()
{
System.out.println("프로그래머 퇴근 합니다.");
}
}
[Designer.java]
package
edu.ojc.constructor1;
class Designer implements Emp
{
public void gotoOffice()
{
System.out.println("디자이너 출근 합니다.");
}
public void getoffWork()
{
System.out.println("디자이너 퇴근 합니다.");
}
}
[Develop.java]
package
edu.ojc.constructor1;
public class Develope
{
Emp emp;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
public Develope(Emp emp)
{
this.emp =
emp;
}
void coding()
{
emp.gotoOffice();
System.out.println("개발합니다...");
emp.getoffWork();
}
}
[Src/main/resources/ojc3.xml] – C
네임스페이스를 이용한 세터주입
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="programmer"
class="edu.ojc.constructor1.Programmer" />
<bean id="designer"
class="edu.ojc.constructor1.Designer" />
<bean id="develope"
class="edu.ojc.constructor1.Develope" c:emp-ref="programmer" />
<!--
<bean
id="develope"
class="edu.ojc.constructor1.Develope">
<constructor-arg ref="programmer"/>
</bean>
-->
</beans>
[TestMain.java]
package
edu.ojc.constructor1;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain
{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("ojc3.xml");
Develope dev =
(Develope)context.getBean("develope");
dev.coding();
}
}
댓글 없음:
댓글 쓰기