TIL

IOC와 DI란 ??

Big Iron 2023. 3. 12. 19:02

Spring을 공부하며 ioc와 di 그리고 bean에대해 많이 들어봤을 것이다.
처음에는 뭔지도 모르고 사용하기도 했다. 그래서 오늘은 간단하게라도 개념을 짚어보고자 한다.


1. Bean

  • Ioc가 관리하는 자바 객체

@component, @service, @repository, @controller 같은 주석을 통해 구성 및 정의.
사용 방법은 아래 확인.


2. IOC (Inversion Of Control)

  • 제어의 역전객체를 제어하고 관리하는 역할이 개발자로부터 스프링 컨테이너에 역전 된다는 뜻이다.
  • 기존에는 구현 객체가 스스로 필요한 서버 구현 객체를 생성하고 연결했지만, 스프링 컨테이너를 사용하면 프로그램에 대한 제어 흐름에 대한 권한은 모두 스프링 컨테이너가 가지게 된다. 아래 예시를 들어보겠다.
----- Ioc 사용 이전 -----
  public class UserService {
      private UserRepository userRepository;

      public UserService() {
          this.userRepository = new UserRepository(); // creating UserRepository object directly
      }

      public User getUserById(long id) {
          return userRepository.getUserById(id); // using UserRepository object directly
      }

      // other methods that use userRepository
  }
----- Ioc 사용 -----
  @Service
  public class UserService {
      private UserRepository userRepository;

      @Autowired
      public UserService(UserRepository userRepository) {
          this.userRepository = userRepository; // userRepository is injected by Spring
      }

      public User getUserById(long id) {
          return userRepository.getUserById(id); // using injected userRepository
      }

      // other methods that use userRepository
  }

@Service로 UserService 클래스에 주석을 달았는데, 이는 이 클래스가 IoC 컨테이너에 의해 관리되어야 함을 Spring에 나타낸다.


3. Di (Dependency Injection) - 의존성 주입

  • (autowired) 인스턴스를 직접 만들지 않고도 클래스 사용 가능.
  @Service  
  public class UserService {  

      @Autowired  
      private UserRepository userRepository;  

      // ...  
  }

@Autowired 주석을 사용하여 UserService 클래스에 주입. 이런 식으로 UserService 클래스는 인스턴스를 직접 만들지 않고도 UserRepository 클래스 사용 가능.