learn/spring

스프링 컨테이너 (Spring Container)

사겅이 2023. 9. 19. 04:11

스프링 컨테이너 (Spring Container)

 

스프링 컨테이너는 Spring에서 빈(Bean)들의 생명주기를 관리하는 Spring Framework의 코어(Core)이다.

The Spring container is the core of the Spring Framework, responsible for managing the lifecycle of beans and facilitating dependency injection.

  • Bean 객체의 생성과 소멸 관리
  • Bean 객체 간의 의존성 주입(Dependency Injection)
  • 설정 정보를 통한 Bean 객체의 설정과 구성
  • Bean을 Singleton으로 관리하므로 여러 곳에서 동일한 Bean 인스턴스를 공유
  • AOP를 통해 관점 지향 프로그래밍을 지원하고, 비즈니스 로직과 횡단 관심사를 분리

 

  • Bean Lifecycle Management: The Spring container handles the creation and destruction of beans. It manages the complete lifecycle of beans, from instantiation to disposal
  • Dependency Injection (DI): Spring uses DI to inject dependencies into beans. This means that instead of objects creating their dependencies, the container injects dependencies into the objects during initialization.
  • Configuration and Setup: Beans in the Spring container are configured and defined using XML or Java annotations. This allows for flexible configuration of bean properties and behaviors.
  • Singleton Management: By default, Spring manages beans as singletons. This means that the container creates a single instance of a bean and shares it among multiple clients, ensuring efficient resource utilization.
  • Aspect-Oriented Programming (AOP): The Spring container supports AOP, enabling the separation of cross-cutting concerns (e.g., logging, security) from business logic. AOP allows for more modular and maintainable code.

출처 : https://www.geeksforgeeks.org/spring-ioc-container/

IoC 컨테이너(IoC Container)

 

 

출처 : https://dog-developers.tistory.com/12

  • DL(Dependency Lookup) - 의존성 조회
    DL은 객체가 직접 의존성을 검색하는 방법을 말하며 객체가 필요한 의존성(예: 서비스, 데이터 소스)을 자체적으로 조회하고 가져옴                                                                                                                                                                    DL은 객체가 직접 의존성을 관리하며, 변경 사항에 취약
  • Dependency Lookup involves objects directly searching for their dependencies. In this approach, an object looks up and obtains its required dependencies, such as services or data sources, on its own                                                    DL allows objects to manage their dependencies directly but can make them more vulnerable to changes
public class   OrderService {
    private PaymentService paymentService;

    public void processOrder () {
        paymentService = (PaymentService) ApplicationContext.getBean( "paymentService" );
        // paymentService를 사용하여 주문 처리
    }
}
  • DI(Dependency Injection) - 의존성 주입
    DI는 의존성이 외부에서 주입되는 방법을 의미하며, 객체는 스스로 의존성을 검색하지 않음                                          DI는 객체 간의 느슨한 결합을 촉진하며 테스트 용이성과 유지보수성을 향상 
  • Dependency Injection is a technique where dependencies are injected from the outside, and objects do not look up dependencies themselves                                                                                                                                                DL involves objects directly searching for dependencies, while DI injects dependencies from the outside, leading to more flexible and maintainable code.
public class   OrderService {
    private PaymentService paymentService;

    // 생성자를 통한 주입
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    public void processOrder () {
        // paymentService를 사용하여 주문 처리
    }
}

BeanFactory와 ApplicationContext

 Bean Factory는 IoC의 기본 기능에 초점을 맞춘 것으로 빈의 생성의존성 주입에 중점을 두고 있습니다. 반면에 Application Context는 별도의 정보와 설정을 통해 빈의 제어를 총괄하며, 스프링 애플리케이션의 다양한 기능을 관리

 

Bean Factory focuses on the core functionality of Inversion of Control (IoC), emphasizing bean creation and dependency injection. On the other hand, the Application Context oversees bean management through additional information and configurations, managing various features of a Spring application

 

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class Hello {

    // 필드 주입을 통한 의존성 주입
    @Autowired
    private MyBean myBean;

    // 생성자를 통한 의존성 주입
    @Autowired
    public Hello(MyBean myBean) {
        this.myBean = myBean;
    }

    // 수정자 메서드를 통한 의존성 주입
    @Autowired
    public void setMyBean(MyBean myBean) {
        this.myBean = myBean;
    }

    public void sayHello() {
        myBean.sayHello();
    }

    public static void main(String[] args) {
        // Spring IoC 컨테이너를 초기화합니다.
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.sayHello();

        // Hello 빈을 가져옵니다.
        Hello hello = context.getBean(Hello.class);

        // 빈을 사용하여 sayHello()를 호출합니다.
        hello.sayHello();
    }
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.hello.container")
public class AppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}
public class MyBean {
    public void sayHello() {
        System.out.println("Hello, Spring IoC 컨테이너!");
    }
}

결과: 

Hello, Spring IoC 컨테이너!
Hello, Spring IoC 컨테이너!

Hello.zip
0.08MB