hyeonga_code

Spring_의존성 주입_어노테이션 기반 설정 본문

Spring

Spring_의존성 주입_어노테이션 기반 설정

hyeonga 2023. 12. 17. 06:59
반응형


- applicationContext.xml 파일의 Namespace에서 context에 체크하여 저장합니다.

- Annotation
    - 컴포턴트 스캔 설정
        - <context : componenet-scan /> 정의
            - 빈을 등록하지 않고 자돋으로 생성하기 위해 사용합니다.
        - 클래스 선언부에 적용
            - @Repository
            - @Componenet
            - @Service
            - @Controller
        - 같이 등록해야 하는 것
            - RequiredAnnotationBeanPostProcessor
            - AutowiredAnnotationBeanPostProcessor
            - CommonAnnotationBeanPostProcessor
            - ConfigurationClassPostProcessor
    - 스프링 빈의 이름 규칙 
        - 클래스 첫 글자를 소문자로 변환한 클래스 이름입니다.
        - 특정 이름을 사용하고 싶은 경우 어노테이션의 속성에 작성합니다.
    - 기본 빈의 범위는 singleton입니다.
        - 변경하고 싶은 경우 @Scope 어노테이션으로 변경합니다.
            @Scope(value="prototype"), proxyMode=ScopedProxyMode.TARGET_CLASS)
    - aop:scoped-proxy 태그와 동일하게 프록시 객체를 생성하고 싶은 경우 proxyMode 속성의 값으로 ScopedProxyMode 열거형 값을 할당합니다.
        - 열거값
            - NO : 프록시를 생성하지 않습니다.
            - INTERFACES : 인턷페이스에 대해 프록시를 생성합니다.
            - TARGET_CLASS : 클래스에 대해 프록시를 생성합니다.
            - DEFAULT : ㄱ리본값을 사용합니다. NO

- sts.spring.annotation > Speaker.java 인터페이스 생성하기
=====

1
2
3
4
5
6
7
package sts.spring.annotation;
 
public interface Speaker {
    void volumeUp();
    void volumeDown();
}
 



- sts.spring.annotation > AppleSpeaker.java 클래스 생성하기
=====

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package sts.spring.annotation;
 
public class AppleSpeaker implements Speaker {
    
    public AppleSpeaker() {
        System.out.println("+++  Create AppleSpeaker  +++");
    }
    
    @Override
    public void volumeUp() {
        System.out.println("+  AppleSpeaker : volumeUp  +");
    }
 
    @Override
    public void volumeDown() {
        System.out.println("+ AppleSpeaker : volumeDown +");
    }
}
 




- sts.spring.annotation > LgTV.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package sts.spring.annotation;
 
import org.springframework.stereotype.Component;
 
@Component("tv")
public class LgTV implements TV{
 
    private Speaker sp;
    
    // 가격 변수를 선언합니다.
    private int price;
    
    public LgTV() {
        System.out.println("[     Create LgTV     ]");
    }
    
    public LgTV(Speaker sp) {
        System.out.println("Create LgTV : Injection");
        this.sp = sp;
    }    
    
    // 생성자 추가
    public LgTV(Speaker sp, int price) {
        System.out.println("Create LgTV : MultiMapping Injection");
        this.sp = sp;
        this.price = price;
    }
 
    // getter/setter 메소드 추가
    public Speaker getSpeaker() {
        return sp;
    }
    
    public void setSpeaker(Speaker sp) {
        this.sp = sp;
    }
    
    
    @Override
    public void powerOn() {
        System.out.println("LgTV powerOn\n   - price : " + price + "\n");
    }
    
    @Override
    public void powerOff() {
        System.out.println("LgTV powerOff");
    }
    
    @Override
    public void volumeUp() {
        sp.volumeUp();
    }
    
    @Override
    public void volumeDown() {
        sp.volumeDown();
    }
}
 


- applicationContext.xml 파일 수정하기
=====

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:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    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.3.xsd">
    
    <!-- Annotation : Namespaces 에서 context 체크합니다. -->
    <bean id="lgTV" class="sts.spring.annotation.LgTV" c:sp-ref="apple" c:price="3000"/>
    <bean id="apple" class="sts.spring.annotation.AppleSpeaker" />
</beans>
 



- sts.spring.annotation > TVUser.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
30
31
32
33
34
package sts.spring.annotation;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class TVUser {
    public static void main(String[] args) {
        
        // Spring 컨테이너를 구동합니다.
        AbstractApplicationContext fac 
= new GenericXmlApplicationContext("applicationContext.xml");

        // Spring 컨테이너에 등록한 객체를 요청합니다.        
        TV lgTV = (TV) fac.getBean("lgTV");
        
        lgTV.powerOn();
        lgTV.volumeUp();
        lgTV.volumeDown();
        lgTV.powerOff();
        
        // Spring 컨테이너를 종료합니다.
        fac.close();
            /*
                +++  Create AppleSpeaker  +++
                Create LgTV : MultiMapping Injection
                LgTV powerOn
                   - price : 3000
                
                +  AppleSpeaker : volumeUp  +
                + AppleSpeaker : volumeDown +
                LgTV powerOff
             */
    }
}

 





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

    - type 속성
        - annotation : 클래스에 지정한 어노테이션이 적용되었는지에 대한 여부
        - 속성에는 org.example.SomeAnnotation 과 같이 이름을 작성합니다.
    - assignable
        - 클래스가 지정한 타입으로 할당 가능한지에 대한 여부
        - 속성에는 org.example.SomeClass와 같이 타입 이름을 작성합니다.
    - regex
        - 클래스가 지정한 정규 표현식에 매칭되는 지에대한 여부
        - 속성에는 org\.example\.Default.*과 같이 정규 표현식을 작성합니다.
    - aspectj
        - 클래스 이름이 AspectJ의 표현식에 매칭되는 지에 대한 여부
        - 속성에는 org.example..Service+ 와 같이 AspectJ 표현식을 입력합니다.

- 의존성 주입 설정
        @Autowired : 멤버 변수 위에 설정하여 해당 타입의 객체를 찾아 자동으로 할당합니다.
        @Qualifier : 특정 객체의 이름을 이용하여 의존성을 주입할 때 사용합니다.
        @Inject : Autowired와 동일한 기능을 제공합니다.
        @Resource : Autowired와 Qualifier의 기능을 결합한 어노테이션입니다.


- sts.spring.annotation > LgTV.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package sts.spring.annotation;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
 
@Component("tv")
public class LgTV implements TV{
    
    @Autowired
    @Qualifier("sony")
    private Speaker sp;
    
    // 가격 변수를 선언합니다.
    private int price = 4500;
    
    public LgTV() {
        System.out.println("[     Create LgTV     ]");
    }
    
    public LgTV(Speaker sp) {
        System.out.println("Create LgTV : Injection");
        this.sp = sp;
    }    
    
    // 생성자 추가
    public LgTV(Speaker sp, int price) {
        System.out.println("Create LgTV : MultiMapping Injection");
        this.sp = sp;
        this.price = price;
    }
 
    // getter/setter 메소드 추가
    public Speaker getSpeaker() {
        return sp;
    }
    
    public void setSpeaker(Speaker sp) {
        this.sp = sp;
    }
    
    @Override
    public void powerOn() {
        System.out.println("LgTV powerOn\n   - price : " + price + "\n");
    }
    
    @Override
    public void powerOff() {
        System.out.println("LgTV powerOff");
    }
    
    @Override
    public void volumeUp() {
        sp.volumeUp();
    }
    
    @Override
    public void volumeDown() {
        sp.volumeDown();
    }
}
 



- applicationContext.xml context san 설정하기
====

1
2
3
4
5
6
7
8
9
10
11
12
<?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"
    xmlns:p="http://www.springframework.org/schema/p"
    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.3.xsd">
 
    <context:component-scan base-package="sts.spring.annotation" />
</beans>
 





- sts.spring.annotation > TVUser.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
30
31
32
33
34
package sts.spring.annotation;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class TVUser {
    public static void main(String[] args) {
        
        // Spring 컨테이너를 구동합니다.
        AbstractApplicationContext fac = new GenericXmlApplicationContext("applicationContext.xml");
        
        // Spring 컨테이너에 등록한 객체를 요청합니다.        
        TV lgTV = (TV) fac.getBean("tv");
        
        lgTV.powerOn();
        lgTV.volumeUp();
        lgTV.volumeDown();
        lgTV.powerOff();
        
        // Spring 컨테이너를 종료합니다.
        fac.close();
            /*
                +++  Create AppleSpeaker  +++
                Create LgTV : MultiMapping Injection
                LgTV powerOn
                   - price : 3000
                
                +  AppleSpeaker : volumeUp  +
                + AppleSpeaker : volumeDown +
                LgTV powerOff
             */
    }
}
 




- Qualifier
        - 동일한 타입의 빈 객체들 중 특정 빈을 사용하도록 설정할 수 있습니다.
       




























반응형