Programming/Spring

Java Config 사용 Bean 설정

khj1999 2025. 2. 6. 20:46

1. 빈(Bean) 설정 방법

① @Configuration과 @Bean을 활용한 Java Config 설정

  • @Configuration: 설정 클래스를 정의하는 데 사용됨.
  • @Bean: 스프링 컨테이너가 관리하는 빈을 등록하는 데 사용됨.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

② @ComponentScan을 이용한 자동 빈 등록

  • @ComponentScan: 특정 패키지를 스캔하여 @Component, @Service, @Repository, @Controller 등을 자동으로 빈으로 등록함.
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.example.service")  // 특정 패키지 내 컴포넌트 자동 등록
public class AppConfig {
}

  • @Component를 사용한 빈 등록:
import org.springframework.stereotype.Component;

@Component
public class MyService {
    public void sayHello() {
        System.out.println("Hello, Spring!");
    }
}

2. AnnotationConfigApplicationContext를 사용한 빈 접근

AnnotationConfigApplicationContext를 이용하면 Java Config 클래스를 기반으로 컨텍스트를 생성하고 빈을 가져올 수 있다.

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        // ApplicationContext 생성 (Java Config 기반)
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // 빈 가져오기
        MyService myService = context.getBean(MyService.class);
        myService.sayHello();  // 출력: Hello, Spring!
    }
}