개키우는개발자 : )

DI 애플리케이션 작성(1) 본문

JAVA/Spring Framework

DI 애플리케이션 작성(1)

DOGvelopers 2019. 2. 6. 16:50
반응형

Spring Framework DI 애플리케이션 작성(1)



학습 목표


  • POJO 클래스 작성
  • 설정 메타정보 XML 작성
  • DI 테스트 클래스 작성


프로젝트 파일 목록프로젝트 파일 목록



1.POJO 클래스 작성하기


Project 생성 -> config 폴더 생성 , myspring.di.xml 패키지 생성


src/test/java 는 default 폴더로 생성되있고 myspring.di.xml.test 패키지 생성



1-1 POJO 클래스 다이어그램


POJO 클래스 다이어그램POJO 클래스 다이어그램



1-2 Hello.java


myyspring.di.xml 패키지 생성후 패키지 안에 Hello.java 생성

맴버 변수 선언후 Alt + Shiift + S -> Generate and Setters 를 클릭한후 맴버변수 체크 후 Generate 클릭 하시면

getter , setter 메서드가 생성됩니다. getter 메서드는 사용하지 않아서 지워줬습니다.

(setname,setprinter + ctrl + space 눌러도 자동완성 기능 가능합니다.)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package myspring.di.xml;
 
public class Hello {
    
    //멤버변수 name 
    private String name;
    //멤버변수 Printer 타입 printer
    private Printer printer;
    //멤버변수 컬렉션 타입 names;
    private List<String> names;
 
    public void setName(String name) {
        this.name = name;
    }
    
    public void setPrinter(Printer printer) {
        this.printer = printer;
    }
    
    //String 타입의 Hello 문자열과 + 멤버변수 name 값을 리턴
    public String sayHellow() {
        return "Hello " + name;
    }
    
    //Printer 인터페이스의 print 메서드를 호출해주는 메서드
    public void print() {
        this.printer.print(sayHellow());
    }
    
}
 
cs


1-3 Printer Interface


1
2
3
4
5
6
7
8
package myspring.di.xml;
 
public interface Printer {
  //print 메서드 생성
    public void print(String message);  
}
 

cs


1-4 StringPrinter.java


Printer Interface 를 구현하는 클래스 작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package myspring.di.xml;
 
public class StringPrinter implements Printer {
    
 
    private StringBuffer buffer = new StringBuffer();
    
    public void print(String message) {
        buffer.append(message);
    }
    
    public String toString() {
        return buffer.toString();
    }
 
}
 
cs


1-5 ConsolePrinter.java


콘솔창에 입력되는 기능 구현


1
2
3
4
5
6
7
8
9
10
package myspring.di.xml;
 
public class ConsolePrinter implements Printer {
 
    public void print(String message) {
        System.out.println(message);
    }
 
}
 
cs




2.설정 메타정보 XML 작성



2-1 Bean Configuration(빈 설정) XML 작성


기존 파일 생성하듯이 new 해주신후 config 폴더 하위에 beans.xml 으로 생성해줍니다.


Bean Configuration(빈 설정) XML 작성Bean Configuration(빈 설정) XML 작성


Bean Configuration(빈 설정) XML 작성Bean Configuration(빈 설정) XML 작성


Bean Configuration(빈 설정) XML 작성Bean Configuration(빈 설정) XML 작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
    <bean id="hello" class="myspring.di.xml.Hello">
        <property name="name" value="Spring Study" />
        <!-- setPrinter(Printer) -->
        <property name="printer" ref="printer" />
    </bean>
 
    <bean id="printer" class="myspring.di.xml.StringPrinter"/>
    <bean id="consolePrinter" class="myspring.di.xml.ConsolePrinter"/>
</beans>
 
cs


작성후 Beans Graph 입니다 . 저는 다른 예제가 있어서 그래프에 다른 빈들도 보이네요 ㅋ


Beans Graph Beans Graph



3.DI 테스트 클래스 작성


3-1 HelloBeanTest.java


- getBean 가져오는 방식은 2가지 방법이 있습니다. id 값을 주거나 id값과 함께 class 타입을 지정할수있음
id 값만 주었을 경우 (Hello) 타입으로 캐스팅해야합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package myspring.di.xml.test;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
import myspring.di.xml.Hello;
import myspring.di.xml.Printer;
 
public class HelloBeanTest {
    public static void main(String[] args) {
        
        //1. IoC 컨테이너 생성
        ApplicationContext context = 
                //설정파일을 인자로 설정
                new GenericXmlApplicationContext("config/beans.xml");
        
        //2. Hello Bean 가져오기( bean id = hello )
        Hello hello = (Hello) context.getBean("hello");
        System.out.println("hello bean = "+ hello.sayHellow());
        hello.print();
        //3. SpringPrinter Bean 가져오기
        Printer printer = (Printer) context.getBean("printer");
        System.out.println("printer bean = "+ printer.toString());
        
        //IoC 컨테이너가 SingleTon 형태로 관리하는지 Test (true)
        Hello hello2 = context.getBean("hello",Hello.class);
        System.out.println(hello == hello2);
    }
    
}
 
cs



Ctrl + F11 (run as) 단축키 사용하시면 결과 값이 나옵니다.


1
2
3
hello bean = Hello Spring Study
printer bean = Hello Spring Study
true
cs


이상으로 DI 애플리케이션 POJO 클래스 방식의 예제를 알아봤습니다.


완성된 프로젝트 코드를 다운받으실수 있습니다.

https://dog-developers.tistory.com/30

반응형

'JAVA > Spring Framework' 카테고리의 다른 글

DI 애플리케이션 작성(3)  (0) 2019.02.07
DI 애플리케이션 작성(2)  (0) 2019.02.06
IoC 컨테이너와 DI(Dependency Injection)  (2) 2019.02.06
프로젝트 시작하기  (0) 2019.01.30
Spring Framework 의 개요  (0) 2019.01.30
Comments