개키우는개발자 : )

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

JAVA/Spring Framework

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

DOGvelopers 2019. 2. 7. 13:40
반응형

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



학습 목표


  • Bean 등록 메타정보 구성 전략에 대한 이해
  • Bean 등록 및 의존관계 설정 Annotation에 대한 이해
  • 프로퍼티(Property) 파일을 이용한 설정 방법에 대한 이해

프로젝트 목록프로젝트 목록



1.Bean 등록 메타정보 구성 전략에 대한 이해


1-1 전략 : XML 단독 사용


- 모든 Bean을 명시적으로 XML에 등록하는 방법이다.


- 생성되는 모든 Bean을 XML에서 확인할 수 있다는 장점이 있으나 Bean의 개수가 많아지면 XML 파일을 관리하기가 번거로울 수 있다.


- 여러 개발자가 같은 설정파일을 공유해서 개발하다 보면 설정파일을 동시에 수정하다가 충돌이 일어나는 경우도 적지 않다.


- DI에 필요한 적절한 setter 메서드 또는 constructor가 코드 내에 반드시 존재해야 한다.


- 개발 중에는 어노테이션 설정방법을 사용했지만, 운영 중에는 관리의 편의성을 위해 XML설정으로 변경하는 전략을 쓸 수도 있다.


1-2 전략 : XML과 빈 스캐닝(Bean Scanning)의 혼용


- Bean으로 사용될 클래스에 특별한 어노테이션(Annotaion)을 부여해주면 이런 클래스를 자동으로 찾아서 Bean으로 등록한다.


- 특정 어노테이션이 붙은 클래스를 자동으로 찾아서 Bean으로 등록해주는 방식을 빈 스캐닝(Bean Scanning)을 통한 자동인식 Bean 등록기능이라고 한다.


- 어노테이션을 부여하고 자동 스캔으로 빈을 등록하면 XML 문서 생성과 관리에 따른 수고를 덜어주고 개발 속도를 향상시킬 수 있다.


- 애플리케이션에 등록될 Bean이 어떤 것들이 있고, Bean들 간의 의존관계가 어떻게 되는지를 한눈에 파악할 수 없다는 단점이 있다.



2.Bean 등록 및 의존관계 설정 Annotation에 대한 이해


2-1 Bean 등록 Annotaion


- @Component : 컴포넌트를 나타내는 일반적인 스테레오 타입으로 <bean> 태그와 동일한 역할을 함.


- @Repository : 퍼시스턴스(persistence) 레이어, 영속성을 가지는 속성(파일, 데이터베이스)을 가진 클래스


- @Service : 서비스 레이어, 비즈니스 로직을 가진 클래스


- @Controller : 프리젠테이션 레이어, 웹 어플리케이션에서 웹 요청과 응답을 처리하는 클래스


- @Repository, @Service, @Controller는 더 특정한 유즈케이스에 대한 @Component의 구체화된 형태이다.


2-2 Bean 의존관계 주입 Annotation


@Autowired, @Resource 어노테이션은 의존하는 객체를 자동으로 주입해 주는 어노테이션이다.


@Autowired

- 정밀한 의존관계 주입 (Dependency Injection)이 필요한 경우에 유용하다.

- @Autowired는 프로퍼티, setter 메서드, 생성자, 일반메서드에 적용 가능하다.

- 의존하는 객체를 주입할 때 주로 Type을 이용하게 된다.

- @Autowired는 <property>, <constructor-arg> 태그와 동일한 역할을 한다.


@Resource

- 어플리케이션에서 필요로 하는 자원을 자동 연결할 때 사용된다.

- @Resource는 프로퍼티, setter 메서드에 적용 가능하다.

- 의존하는 객체를 주입할 때 주로 Name을 이용하게 된다.


@Value

- 단순한 값을 주입할 때 사용되는 어노테이션이다.

- @Value("Spring")은 <property .. value="String" />와 동일한 역할을 한다.


@Qualifier

- @Qualifier 는 @Autowired 어노테이션과 같이 사용되어 진다.

- @Autowired는 타입으로 찾아서 주입하므로, 동일한 타입의 Bean 객체가 여러 개 존재할 때 특정 Bean을 찾기위해서는 @Qualifier를 같이 사용해야 한다.


2-3 Component Scan을 지원하는 태그


<context:component-scan> 태그


- @Component를 통해 자동으로 Bean을 등록하고, @Autowired로 의존관계를 주입받는 어노테이션을 클래스에서 선언하여 사용했을 경우에는 해당 클래스가 위치한 특정 패키지를 Scan하기 위한 설정을 XML에 해주어야 한다.


<context:component-scan base-package="myspring.di.annot" />


<context:include-filter> 태그와 <context:exclude-filter> 태그를 같이 사용하면 자동 스캔 대상에 포함시킬 클래스와 포함시키지 않을 클래스를 구체적으로 명시할 수 있다.


2-4 어노테이션을 사용한 POJO 클래스 작성


어노테이션을 사용한 POJO 클래스 작성어노테이션을 사용한 POJO 클래스 작성



New -> package -> myspring.di.annot 패키지를 생성합니다.


New -> package -> myspring.di.annotNew -> package -> myspring.di.annot 생성


myspring.di.annot 입력myspring.di.annot 입력


myspring.di.annot 패키지 하위에 Printer interface 파일을 생성합니다.


1
2
3
4
5
package myspring.di.annot;
 
public interface Printer {
    public void print(String message);
}
cs


myspring.di.annot 패키지 하위에 StringPrinter.java 파일을 생성후 Printer Interface를

implements한 후 @Component 어노테이션을 선언합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package myspring.di.annot;
 
import org.springframework.stereotype.Component;
 
@Component("stringPrinter")
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


myspring.di.annot 패키지 하위에 ConsolePrinter.java 파일을 생성후 Printer Interface를

implements한 후 @Component 어노테이션을 선언합니다.


1
2
3
4
5
6
7
8
9
10
11
12
package myspring.di.annot;
 
import org.springframework.stereotype.Component;
 
@Component("ConsolePrinter")
public class ConsolePrinter implements Printer {
 
    public void print(String message) {
        System.out.println(message);
    }
 
}
cs


myspring.di.annot 패키지 하위에 Hello.java 클래스를 작성해보겠습니다.


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
package myspring.di.annot;
 
import javax.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component
public class Hello {
    
    @Value("Spring Study")
    private String name;
    
    @Autowired
    @Qualifier("stringPrinter")
    private Printer printer;    
 
    public String sayHellow() {
        return "Hello " + name;
    }
 
    public void print() {
        this.printer.print(sayHellow());
    }
    
}
 
cs



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


annot.xml

New -> spring -> Spring Bean Configuration File -> config 폴더 하위에 annot.xml 을 생성합니다.


New -> spring -> Spring Bean Configuration FileNew -> spring -> Spring Bean Configuration File 선택


annot.xml 생성annot.xml 생성


생성된 annot.xml 의 Namespaces beans 와 context를 체크 후 default 값인 3.2 버전을 선택합니다.


beans,context 체크beans,context 체크


설정 후 annot.xml 을 작성합니다

.myspring.di.annot 하위에 있는 어노테이션들을 스캔하기 위해 context:component-scan 값을 설정해야 합니다.


1
2
3
4
5
6
7
8
9
10
<?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">
 
    <!-- 어노테이션이 선언된 클래스들을 스캔하기 위한 설정 -->
    <context:component-scan base-package="myspring.di.annot" />
</beans>
cs



2-6 DI  annot 테스트 클라이언트 작성


New -> package -> src/test/java 하위에 myspring.di.annot.test 패키지 생성


패키지 생성패키지 생성


myspring.di.annot.test 패키지myspring.di.annot.test 패키지


myspring.di.annot.test 패키지 하위에 HelloBeanAnnotTest.java 파일을 생성합니다.


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
package myspring.di.annot.test;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import myspring.di.annot.Hello;
 
import static org.junit.Assert.*;
 
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:config/annot.xml")
public class HelloBeanAnnotTest {
    
    @Autowired
    private ApplicationContext context;
    
    @Test
    public void annotTest() {
        Hello hello = context.getBean("hello",Hello.class);
        assertEquals("Hello Spring Study",hello.sayHellow());
        System.out.println(hello.sayHellow());
    }
    
}
cs


Ctrl + F11 or 우클릭 -> run as -> JUnit test


테스트 성공테스트 성공


출력 값 


1
Hello Spring Study
cs


3.프로퍼티(Property) 파일을 이용한 설정 방법에 대한 이해


3-1 Properties 파일 및 Bean 설정 파일 작성


- config폴더 하위 value.properties 에 작성 합니다.


1
2
3
4
5
6
7
8
myname=Spring Study
myprinter=printer
value1=AOP
value2=Spring
value3=DI
 
printer1 = stringPrinter
printer2 = consolePrinter
cs


annot.xml 에 properties 파일을 사용하기 위한 <context:property-placeholder> 태그를 이용해 경로를 연결합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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">
 
    <!-- 어노테이션이 선언된 클래스들을 스캔하기 위한 설정 -->
    <context:component-scan base-package="myspring.di.annot" />
    
    <!-- properties 사용 경로 -->
    <context:property-placeholder location="classpath:config/value.properties"/>
</beans>
 
cs


3-2 어노테이션을 사용한 POJO 클래스 수정


myspring.di.annot 패키지 하위에 있는 Hello.java 클래스를 properties 파일을 치환하는 방식으로 수정하겠습니다. @Resource 어노테이션이 자동생성 되지 않으면 import javax.annotation.*;를 import 해주세요


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package myspring.di.annot;
 
import java.util.List;
import javax.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component
public class Hello {
    
    //${myname} == Spring Study
    @Value("${myname}")
    private String name;
    
/*    @Autowired
    @Qualifier("stringPrinter")*/
    //name 속성을 사용하기위해 Resource 어노테이션 사용
    @Resource(name="${printer1}")
    private Printer printer;
    private List<String> names;
    
    public Hello() {}
    
    public Hello(String name, Printer printer) {
        super();
        this.name = name;
        this.printer = printer;
    }
 
    public List<String> getNames() {
        return names;
    }
 
    public void setNames(List<String> names) {
        this.names = names;
    }
 
    public String sayHellow() {
        return "Hello " + name;
    }
 
    public void print() {
        this.printer.print(sayHellow());
    }
    
}
 
cs


프로퍼티 치환자를 사용하여 테스트를 다시한번 해보겠습니다.


myspring.di.annot.test 패키지 하위에 HelloBeanAnnotTest.java 파일을 다시한번 실행시켜줍니다.


Ctrl + F11 or 우클릭 -> run as -> JUnit test 하면 값이 제대로 실행되는걸 확인하실 수 있습니다.


치환자 테스트 성공치환자 테스트 성공


콘솔 출력값


1
Hello Spring Study
cs


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

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

반응형

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

Spring Framework JDBC 개요  (0) 2019.02.07
사용자관리 프로젝트  (0) 2019.02.07
DI 애플리케이션 작성(3)  (0) 2019.02.07
DI 애플리케이션 작성(2)  (0) 2019.02.06
DI 애플리케이션 작성(1)  (0) 2019.02.06
Comments