GOORM-DEEP DIVE 백엔드 3회차 회고 DAY11

Cori1304·2025년 3월 12일
0

GOORM-DEEPDIVE

목록 보기
10/19

글을 쓰게된 배경

부트캠프에서 처음으로 java수업을 받고 있기에 기록하는게 좋다고 생각했고, 수업이 있는 날이면 매일 글을 쓰려고 합니다. 쵀대한 몰랐거나 필요하다고 생각되는 내용 위주로 기록할 예정입니다. (제가 게을러서 이러한 시도를 성공한 적이 없기에 이번 부트캠프 목표 중 1가지입니다. 할 수 있도록 화이팅!!)

라이브러리 vs 프레임워크

🟢 라이브러리

  • 특정 기능을 수행하는 독립적인 코드 모음
  • 개발자가 직접 가져와서 필요할 때 호출해서 사용함
  • 코드 실행 흐름을 개발자가 직접 관리
import org.apache.commons.lang3.StringUtils;

public class LibraryExample {
    public static void main(String[] args) {
        String text = "  hello world  ";

        // StringUtils.trim() 라이브러리 호출
        System.out.println(StringUtils.trim(text)); // "hello world"
    }
}

🟢 프레임워크 (Framework)

  • 설계 방식과 구조를 제공하는 개발 도구
  • 코드의 흐름을 프레임워크가 관리 (제어의 역전, IoC 적용)
  • 개발자는 프레임워크가 정한 방식대로 코드를 작성
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {
    private final HelloService helloService;

    @Autowired
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @GetMapping("/hello")
    public String hello() {
        return helloService.sayHello();
    }
}

DI (Dependency Injection)

☀️ DI 사용 장점

  • 클라이언트 코드를 변경하지 않고 클라이어트가 호출하는 대상의 타입 인스턴스를 변경할 수 있다.
  • 정적인 클래스 의존 관계를 변경하지 않고, 동적인 객체 인스턴스 의존관계를 쉽게 변경할 수 있다.

정적인 클래스 의존 관계

  • 코드를 작성하는 순간 결정됨
  • 컴파일 시점에 확인 가능
  • 주로 클래스, 인터페이스, 메서드 호출, import 구문 등을 통해 나타남
class Engine {
    void start() {
        System.out.println("Engine started");
    }
}
// Car class
class Car {
    private Engine engine = new Engine(); // Engine에 의존
// 내부 메서드
    void drive() {
        engine.start();
        System.out.println("Car is moving");
    }
}

#### DI 사용 X
``` java
lass BeanGrinder {
    void grind() {
        System.out.println("Grinding beans...");
    }
}

class CoffeeMachine {
    private BeanGrinder grinder = new BeanGrinder(); // 직접 객체 생성 // 코드 수정 필요한 부분

    void brew() {
        grinder.grind();
        System.out.println("Brewing coffee...");
    }
}

class ElectricGrinder extends BeanGrinder {
    void grind() {
        System.out.println("Grinding beans electrically...");
    }
}

DI 사용 코드

interface Grinder {
    void grind();
}

class BeanGrinder implements Grinder {
    public void grind() {
        System.out.println("Grinding beans...");
    }
}

class ElectricGrinder implements Grinder {
    public void grind() {
        System.out.println("Grinding beans electrically...");
    }
}
class CoffeeMachine {
    private Grinder grinder;

    public CoffeeMachine(Grinder grinder) { // 생성자로 의존성 주입
        this.grinder = grinder;
    }

    void brew() {
        grinder.grind();
        System.out.println("Brewing coffee...");
    }
}

IoC 컨테이너

IoC컨테이너 또는 DI 컨테이너라고 부른다.

IoC (Inversion of Contoller, 제어의 역전)

원래는 개발자가 직접 객체를 생성하고 관리한ㄷ. 하지만, Spring 같은 프레임워크가 대신 객체를 생성하고 주입해 주는 즉 제어를 개발자가 아닌 프로그램이 해주는 것을 뜻 한다. (구현부와 실행부로 나눠져서 실행되기도 한다. )

예제

appConfig라는 제어 흐름에 대한 모든 권한을 가진 class를 만들어서 설명하겠다.

public class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

public class Car {
    private final Engine engine;

    // 생성자를 통해 Engine을 주입받음
    public Car(Engine engine) {
        this.engine = engine;
    }

    public void drive() {
        engine.start();
        System.out.println("Car is moving");
    }
}

public class AppConfig {

    public Engine createEngine() {
        return new Engine(); // Engine 객체 생성
    }

    public Car createCar() {
        return new Car(createEngine()); // Engine을 Car에 주입
    }
}

public class Main {
    public static void main(String[] args) {
        // AppConfig를 통해 객체 생성 및 주입
        AppConfig appConfig = new AppConfig();

        // Car 객체를 AppConfig에서 가져옴 (IoC 적용)
        Car car = appConfig.createCar();
        car.drive(); // "Engine started" -> "Car is moving"
    }
}


배운점

  1. DI를 왜 사용하는지 몰랐다. 좋다고 해서 사용했지만 오늘 계속 DI가 없는 코드를 java로 만들면서 왜 필요한지 이해했다.
  2. 라이브러리와 프레임워크 차이를 고민한 적이 없었는데 이론적으로 구별할 수 있어서 재미있었다.
profile
개발 공부 기록

0개의 댓글

관련 채용 정보