#13.스프링DI(생성자주입,어노테이션기반예제)
생성자 주입(Constructor Injection) – 어노테이션 기반
[Emp.java]
package
edu.ojc.constructor2;
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
interface Emp {
public abstract void
gotoOffice();
public abstract void getoffWork();
}
[Programmer.java]
package
edu.ojc.constructor2;
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.constructor2;
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.constructor2;
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
public
Develope(@Qualifier(value="programmer") Emp emp)
{
this.emp =
emp;
}
void coding()
{
emp.gotoOffice();
System.out.println("개발합니다...");
emp.getoffWork();
}
}
[Src/main/resources/ojc4.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.constructor2"/>
</beans>
[TestMain.java]
package
edu.ojc.constructor2;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain
{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("ojc4.xml");
Develope dev =
(Develop)context.getBean("develope");
dev.coding();
}
}
댓글 없음:
댓글 쓰기