본문 바로가기
개발기초지식

[면접질문] 면접질문대비 / Spring Bean이란 무엇인가? 생명주기는?

by 수바니 2025. 5. 29.

1. ✅ Spring  Bean이란?

Spring Bean은 Spring IoC 컨테이너에 의해 관리되는 자바 객체를 의미

스프링 프레임워크에서는 객체를 직접 생성하지 않고, 스프링 컨테이너가 관리하는 객체를 주입받아 사용

 

특징

1. 스프링이 직접 생성하고 관리

2. 객체 생명주기를 스프링이 제어 ( 생성 -> 초기화 -> 소멸)

3. 주로 @Component, @Service, @Repository, @Controller 등의 어노테이션으로 등록하게 됨

 

즉,  Bean으로 등록하게되면 Spring 컨테이너가 해당 객체의 생명주기를 관리하게 되고, 객체를 생성하고 필요할 때 주입하고, 소멸까지 관리하게 된다. Spring이 객체를 대신 생성하고, 직접 new하지 않아도 사용이 가능

객체를 명시적으로 생성하지 않아도, @Autowired나 생성자 주입방식으로 Bean을 알아서 찾아줌

 

2. 🔄 Spring Bean 생명주기 (Lifecycle)

객체 생성 -> 의존성 주입 -> 초기화 -> 사용 -> 소멸

상세단계 설명
1. 객체 생성 스프링이 빈 객체를 인스턴스화 함 (new)
기본 생성자 혹은 생성자 주입 사용
2. 의존성 주입 (Dependency Injection) 필요한 의존 객체를 스프링이 자동으로 주입
@Autowired, @Inject, @Value 등 사용
3. 초기화 (Initialization) 초기화 콜백 메서드 호출
@PostConstruct 또는 InitializingBean의 afterPropertiesSet() 사용가능
4. 사용 (Use) 실제 비지니스  로직 수행 단계
5. 소멸 (Destruction) 컨테이너 종료 시 @ProDestroy 메서드 호출
또는 DisposableBean의 destory()메서드 사용

 

3. 🧭 스프링에서 Bean은 어떤 기준으로 찾을까?

3-1) 스프링은 어떻게 Bean을 찾는가?

스프링이 Bean을 찾는 기준은 크게 두 단계로 나뉜다.

 

✅ 1단계 : 빈 등록 ( 등록 기준 )

먼저, 스프링 컨테이너에 등록된 Bean만 찾을 수 있음

등록 기준은 다음과 같다.

등록 방식 설명 예시
클래스 스캔 @Component, @Service, @Repository, @Controller 어노테이션이 붙은 클래스 @ComponentScan으로 탐색
수동 등록 @Configuration 클래스 내의 @Bean 메서드 @Bean
public MyService myService() {
 ...

}
XML 설정 옛 방식으로 XML <bean> 태그로등록 <bean id = "myBean"
 class="com.example.MyClass" />

 

즉, 빈으로 등록되지 않으면 아무리 클래스가 있어도 찾지 않는다.

 

✅ 1단계 : 빈 검색 ( 탐색 기준 )

빈이 등록된 이후, 실제로 DI 등을 통해 찾을 때는 다음 기준이 사용

기준 설명 예시
타입 기준 (기본) 주입 대상의 타입 (class / interface) 기준으로 찾음 @Autowired
private MyService service;
이름 기준 (중복시) 동일 타입 빈이 여러 개일 경우, 이름 기준으로 구분 @Qualifier("myServiceImpl")
Primary 빈 우선 @Primary 가 선언된 빈이 우선 선택됨 @Primary 선언된 클래스 사용
Lazy vs Eager 기본은 빈을 앱 시작시 미리 로딩(Eager), @Lazy는 지연로딩  

 

💡 Bean 탐색 동작 예시

@Component
public class HelloServiceImpl implements HelloService { }

@Service("namedService")
public class NamedService implements HelloService { }

@Configuration
public class AppConfig {
    @Bean
    public HelloService customHelloService() {
        return new CustomHelloServiceImpl();
    }
}
@Autowired
private HelloService helloService;

 

이럴경우, HelloService 타입의 구현체가 3개 있기 때문에 에러발생

해결방안

@Qualifier("namedService")

또는 @Primary 어노테이션 사용

혹은 @Autowired(required = false) + 조건 분기 처리

 

🧭 @ComponentScan 범위가 핵심이다!

스프링이 어떤 클래스를 스캔해서 Bean으로 등록할지는 @ComponentScan 의 패키지 기준으로 결정

@SpringBootApplication // 이 안에 @ComponentScan 있음
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 

이 경우 Application 클래스가 있는 패키지 하위만 스캔함

따라서 Bean이 안 만들어질 경우, 패키지 구조를 확인

 

📌 정리: Bean을 찾는 기준

단계 기준 설명
등록기준 어노테이션, 수동등록 @Component, @Bean, XML 등
탐색기준 타입 기준 @Autowired HelloService
이름기준 중복 타입시
@Qualifier("beanName")
 
우선순위 @Primary 빈이 우선  
범위 기준 @ComponentScan 대상 패키지