SPRING - DI의 장점
- SPRING
- 2018. 2. 5. 14:29
DI의 장점
작은 규모의 프로젝트에서는 스프링의
DI 를 사용 하는것보다 일반적인 방법을 사용해서
개발하는 것이 더욱 빠르고 편합니다.
하지만 규모가 어느정도 커지고 추후에 유지보수가
필요하다면 DI를 이용한 개발이 필요합니다
간단하게 DI사용에따른 장점에관한
예를 만들어 보겠습니다.
먼저 메인클래스를 만들어줍니다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.spring.ex; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; public class MainClass { public static void main(String[] arg){ AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml"); Pencil pencil = ctx.getBean("pencil", Pencil.class); pencil.use(); ctx.close(); } } | cs |
이전과 같이 xml 파일 사용을 명시 해줍니다
다음 10line에서 사용하려는 클래스를
getBean을 이용해 사용합니다
다음 Pencil이름의 인터페이스를 만들어줍니다
1 2 3 4 5 6 7 | package com.spring.ex; public interface Pencil { public void use(); } | cs |
다음 출력을 위한 테스트 클래스들 을 만듭니다
1 2 3 4 5 6 7 8 9 10 11 12 | package com.spring.ex; public class Pencil4B implements Pencil { @Override public void use() { System.out.println("4B입니다"); } } | cs |
--
1 2 3 4 5 6 7 8 9 10 11 12 | package com.spring.ex; public class Pencil6B implements Pencil { @Override public void use() { System.out.println("6B입니다"); } } | cs |
--
1 2 3 4 5 6 7 8 9 10 11 12 | package com.spring.ex; public class Eraser implements Pencil { @Override public void use() { System.out.println("지우개 입니다"); } } | cs |
--
마지막으로 xml만들어줍니다
1 2 3 4 5 6 7 8 | <?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.xsd"> <bean id="pencil" class="com.spring.ex.Eraser"></bean> </beans> | cs |
이때 6line 에서 사용하려는 클래스의 이름을 넣어줘야
메인클래스에서 해당 클래스를 출력합니다
먼저 Eraser 이름의 클래스를 넣어 출력해보겠습니다.
위와같이 콘솔창에 해당 클래스의
내용이 출력됩니다
이제 xml에서 다른 클래스를 사용해보도록 하겠습니다
1 2 3 4 5 6 7 8 | <?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.xsd"> <bean id="pencil" class="com.spring.ex.Pencil6B"></bean> </beans> | cs |
위와같이 Pencil6B 클래스를 넣어주면 아래와같이
Pencil6B클래스의 값이 출력됩니다
'SPRING' 카테고리의 다른 글
SPRING - AOP란? (0) | 2018.02.06 |
---|---|
SPRING - 자바를 이용한 DI 설정 (0) | 2018.02.06 |
SPRING - DI 활용 (0) | 2018.02.05 |
SPRING - DI (Dependency Injection) (0) | 2018.02.05 |
SPRING - 이클립스에서 SPRING 사용하기 (0) | 2018.02.05 |