[스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술] 04. 스프링 빈과 의존관계

Turtle·2024년 6월 8일
0
post-thumbnail

📖IoC

IoC(Inversion of Control)의 약자로 "제어의 역전"이라 하며 프로그램의 실행 흐름이나 객체의 생명 주기를 개발자가 제어하는 것이 아닌 외부에서 관리해주는 것을 말한다.

출처 - Spring documentation(Spring Bean)

The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.

org.springframework.context.ApplicationContext 인터페이스가 스프링 IoC 컨테이너를 대표하며 빈의 인스턴스화, 구성 및 조립을 담당한다.

스프링 빈으로 등록하는 방법에는 3가지가 존재한다.

XML(고전적인 방식으로 현재 실무에서는 사용되지 않는 추세)
Annotation
Java Config

클라이언트에서 스프링 빈을 요구할 때 IoC 컨테이너에서 같은 참조 값을 가진 빈을 반환해준다.
IoC 컨테이너에서 빈은 싱글톤 패턴으로 관리되는데 이 때, 싱글톤 패턴이란 디자인 패턴 중의 하나로 객체의 인스턴스가 오직 1개만 생성되는 것을 보장하는 디자인 패턴을 말한다.
싱글톤 패턴을 사용할 때는 몇 가지 주의할 점이 있다.

❗주의점

객체의 상태를 유지하게 설계하면 안 된다.
특정 클라이언트에 의존적이거나 값을 변경할 수 있는 필드가 있으면 안 된다.
가급적 읽기만 가능해야 한다.

@Scope어노테이션을 프로토타입으로 지정해두면 프로토타입 빈을 생성할 수 있다.

  • 클라이언트들이 스프링 빈을 요구할 때마다 컨테이너에서 빈을 생성하고 의존성을 주입하고 만들어진 프로토타입 빈을 반환한다.

❓싱글톤 빈 vs 프로토타입 빈

싱글톤 빈과 프로토타입 빈의 차이점 → 빈의 생명 주기(Bean Life Cycle)

싱글톤 빈에서의 생명주기

스프링 IoC 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입 → 초기화 콜백 메서드 호출 → 사용 → 소멸 전 콜백 메서드 호출 → 스프링 종료

프로토타입 빈에서의 생명주기

스프링 IoC 컨테이너 생성 → 스프링 빈 생성 → 의존관계 주입 → 초기화 콜백 메서드 호출 → 사용

📚스프링 빈을 등록하는 방법 - 컴포넌트 스캔과 자동 의존관계 설정

@ComponentScan
@Autowired
@Controller
@Service
@Repository

📚자바 설정 파일로 스프링 빈 등록하기

package hello.hello_spring;

import hello.hello_spring.controller.MemberController;
import hello.hello_spring.repository.MemoryMemberRepository;
import hello.hello_spring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {

    @Bean
    public MemberService memberService() {
        return new MemberService(memoryMemberRepository());
    }

    @Bean
    public MemoryMemberRepository memoryMemberRepository() {
        return new MemoryMemberRepository();
    }

    @Bean
    public MemberController memberController() {
        return new MemberController(memberService());
    }
}

🔒출처

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
우아한 테크코스 - 10분 테크톡

0개의 댓글