스프링 with AI

GPT와 함께하는 Spring 06

ohji52 2025. 9. 1. 20:26

📌 스프링 기본기 (Spring Framework Core)

1. IoC / DI (제일 핵심!)

✅ IoC (Inversion of Control, 제어의 역전)

  • 원래는 객체를 개발자가 new로 직접 생성하고 관리
  • 스프링은 객체 생성 & 의존성 관리까지 대신 해줌 → 스프링 컨테이너(ApplicationContext) 가 담당
  • 즉, 객체 관리의 제어권이 개발자 → 프레임워크로 넘어감

✅ DI (Dependency Injection, 의존성 주입)

  • 클래스가 사용할 객체를 스스로 만들지 않고, 외부에서 주입받음
  • 주입 방식: 생성자 주입(권장), 세터 주입, 필드 주입
@Component //컴포넌트로 컨테이너가 자동으로 빈으로 등록
class ServiceA {
    void print() { System.out.println("Service A 동작"); }
}

@Component
class ServiceB { //serviceA에 의존하는 컴포넌트
    private final ServiceA serviceA;

    // 생성자 주입
    @Autowired
    public ServiceB(ServiceA serviceA) {
        this.serviceA = serviceA;
    }

    public void run() {
        serviceA.print();
    }
}

 

2. AOP (Aspect Oriented Programming, 관점 지향 프로그래밍)

  • 핵심 로직과 **공통 관심사(횡단 관심사)**를 분리
  • 공통 관심사 예시: 로깅, 트랜잭션, 보안, 성능 모니터링 등
@Aspect
@Component
public class LogAspect {
    @Before("execution(* com.example.service.*.*(..))") // 타깃 메서드 실행 전에 실행
    public void logBefore() {
        System.out.println("메서드 실행 전 로깅!");
    }
}

 

👉 요약:

  • @Aspect + @Component → 스프링이 이 클래스를 AOP용 빈으로 관리.
  • @Before → 지정된 패키지(service)의 모든 메서드 실행 직전에 logBefore()가 동작.
  • 결과적으로 서비스 계층 메서드가 실행되면 콘솔에 "메서드 실행 전 로깅!"이 찍힘.

3. 스프링 빈(Bean) 생명주기 & 스코프

✅ 생명주기

  1. 객체 생성 (new)
  2. 의존성 주입 (DI)
  3. 초기화 메서드 실행 (@PostConstruct)
  4. 사용
  5. 소멸 메서드 실행 (@PreDestroy)
@Component
class ExampleBean {
    @PostConstruct
    public void init() { System.out.println("초기화"); }

    @PreDestroy
    public void destroy() { System.out.println("소멸"); }
}

✅ 스코프

  • 싱글톤(Singleton) (기본값, 컨테이너당 1개만 생성)
  • 프로토타입(Prototype) (주입될 때마다 새로 생성)
  • 웹 환경: Request, Session, Application

4. 스프링 환경설정 방식

  1. XML 기반 (applicationContext.xml)
  2. Java Config 기반 (@Configuration, @Bean)
  3. Annotation 기반 (@Component, @Service, @Repository, @Controller)
@Configuration // config 방식
class AppConfig {
    @Bean
    public ServiceA serviceA() {
        return new ServiceA();
    }
}


@Component // annotation 방식
class ServiceA {}

'스프링 with AI' 카테고리의 다른 글

Gemini와 함께하는 Spring 08  (0) 2025.09.08
Gemini와 함께하는 Spring 07  (0) 2025.09.02
GPT와 함께하는 Spring 05  (0) 2025.09.01
GPT와 함께하는 Spring 04  (0) 2025.09.01
GPT와 함께하는 Spring 03  (0) 2025.08.24