본문 바로가기
Spring/TroubleShooting

Bean 수동 주입 방법 (@Autowired로 빈 주입 실패 시)

by Mecodata 2024. 1. 4.

사용 이유 (문제 상황)

- JpaRepository 객체를 상위 패키지가 동일한 서로 다른 두 개의 클래스에 각각 @Autowired를 통해 Bean을 주입 받도록 설정

- 한 클래스에서는 정상적으로 주입되어 쿼리 메소드가 정상적으로 실행되었지만 다른 클래스에서는 Bean이 주입되지 않아 객체가 null로 조회되어 NullPointerException이 발생

 

해결 방법

- 다음과 같이 ApplicationContextProvider와 BeanUtils 정의 후 ApplicationContext의 getBean() 통해 파라미터로 입력한 객체의 빈을 받아와 객체에 직접 Bean을 주입

private CarRepository carRepo; 
CarRepo = BeanUtils.getBean(CarRepository.class);

ApplicationContextProvider

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		applicationContext = ctx;
	}
	
	public static ApplicationContext getApplicatoinContext() {
		return applicationContext;
	}
	
}

BeanUtil

import org.springframework.context.ApplicationContext;

public class BeanUtil {
	
    // 제너릭(<>) 메소드는 기본적으로 <T> T로 타입을 설정
	public static <T> T getBean(Class<T> classType) {
		ApplicationContext applicationContext = ApplicationContextProvider.getApplicatoinContext();
		return applicationContext.getBean(classType);
	}
	
}

ApplicationContext

- Spring에서 Bean의 생성, 관리, 검색 등을 담당하는 Spring Container의 핵심 인터페이스이자 일종의 DI 컨테이너

- Bean들 간의 의존성 주입 및 라이프사이클을 관리함

- Bean의 생성과 관계설정 등의 제어를 담당하는 최상위 인터페이스인 BeanFactory를 상속

 

ApplicationContextAware

- Spring ApplicationContext에 대한 참조를 얻을 수 있도록 Spring에서 제공하는 인터페이스

- setApplicationContext(ApplicationContext) 메소드에 대한 재정의(Override) 필수

 

 

 

 

댓글