Spring Boot - @Component, 의존성 주입, IOC

hanjae_99·2024년 1월 16일

Udemy

목록 보기
8/9
post-thumbnail

@Component

Component 어노테이션을 추가하여 클래스의 인스턴스를 스프링이 관리하게끔 할 수 있다.
ComponentScan 을 통해 특정 클래스가 컴포넌트로 추가되어있다면
해당 클래스의 인스턴스인 Spring Bean 이 생성되고 스프링에 의해 관리된다.

package com.in28minutes.learnspringframework.game;

import org.springframework.stereotype.Component;

@Component
public class PackmanGame implements GamingConsole{

    @Override
    public void up() {
        System.out.println("Packman Up!");
    }

    @Override
    public void down() {
        System.out.println("Packman Down!");
    }

    @Override
    public void left() {
        System.out.println("Packman move Left!");
    }

    @Override
    public void right() {
        System.out.println("Packman move Right!");
    }
}

@ComponentScan

스프링에게 사용할 컴포넌트의 위치를 알려주어야 검색이 가능.

@Configuration
@ComponentScan("com.in28minutes.learnspringframework.game")
public class GamingAppLauncherApplication {
	...
}

특정 패키지명을 입력하여 해당 패키지와 하위 패키지에서 탐색이 가능하며,
패키지명 입력을 생략할 시 현재 작성된 클래스의 패키지에서부터 탐색 시작.

의존성과 의존성 주입

하나의 객체가 생성되거나 활용될 때 필요한 객체나 값을 의존성이라한다.

package com.in28minutes.learnspringframework.examples.c1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class BusinessCalculationService {

    private DataService dataService;

    public BusinessCalculationService(DataService dataService){
        super();
        this.dataService = dataService;
    }

    public int findMax(){
        return Arrays.stream(dataService.retrieveData()).max().orElse(0);
    }
}

위 코드에서 BusinessCalculationService 클래스의 생성자에서 DataService 타입의
dataService 가 의존성으로 활용되고 있다.

스프링은 ComponentScan 을 통해 Spring Beans 들을 식별하고, 각각의 의존성 관계를 파악해
자동으로 와이어링 시켜준다 => 의존성 주입

이러한 의존성을 스프링이 주입시키는 방식으로는 크게
1. 필드주입
2. setter 주입
3. 생성자 주입
으로 나눌 수 있다.

1. 필드주입

@Component
class YourBusinessClass{

	@Autowired
    Dependency1 dependency1;

	@Autowired
    Dependency2 dependency2;

    @Override
    public String toString() {
        return "Using " + dependency1 + " and " + dependency2;
    }
}

2. setter 주입

@Component
class YourBusinessClass{

    Dependency1 dependency1;

    Dependency2 dependency2;
    
    @Autowired
    public void setDependency1(Dependency1 dependency1) {
        System.out.println("Setter Injection dependency1");
        this.dependency1 = dependency1;
    }

    @Autowired
    public void setDependency2(Dependency2 dependency2) {
        System.out.println("Setter Injection dependency2");
        this.dependency2 = dependency2;
    }

    @Override
    public String toString() {
        return "Using " + dependency1 + " and " + dependency2;
    }
}

3. 생성자 주입

@Component
class YourBusinessClass{

    Dependency1 dependency1;

    Dependency2 dependency2;

	//@Autowired //생성자 주입 시 생략 가능
    public YourBusinessClass(Dependency1 dependency1, Dependency2 dependency2) {
        this.dependency1 = dependency1;
        this.dependency2 = dependency2;
        System.out.println("Constructor Injection");
    }

    @Override
    public String toString() {
        return "Using " + dependency1 + " and " + dependency2;
    }
}

위 세가지 방법 중 생성자 주입이 가장 추천되는 의존성 주입 방식이다.
모든 초기화가 생성자 메소드 하나에서 진행되기 때문이다.

IOC ?

Inversion Of Control, 즉 어디선가 들어본 그 단어인 '제어의 역전' 을 의미한다.
말그대로 제어권이 역전되었다는 것을 뜻하며,
기존에 프로그래머가 자바코드로 직접 객체를 생성하고 주입시켜온것과 반대로
Spring 을 통해 객체를 관리하도록 하고 의존성을 주입해 Autowiring 을 구현하는 과정을 통해
객체의 제어 권한이 프로그래머 -> 스프링으로 넘어감을 말한다.

profile
단 하나밖에 없는 톱니바퀴

0개의 댓글