프로그래밍/Back end
[Back end] Spring Boot @Autowired null 에러
Reference M1
2022. 11. 22. 10:38
Thread를 통해 Service를 호출하려고 하면 @Autowired null 관련 에러가 발생한다. Thread 클래스가 Bean으로 등록된 클래스가 아니어서 IOC Container를 통해 자동 주입되지 않는다. @Autowired는 Bean으로 등록된 클래스에서만 사용 가능하다.
이럴 때는 Bean을 수동으로 주입하면 해결 가능하다.
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 getApplicationContext() {
return applicationContext;
}
}
BeanUtils
import org.springframework.context.ApplicationContext;
import com.skcc.kw.common.ApplicationContextProvider;
public class BeanUtils {
public static Object getBean(String bean) {
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
return applicationContext.getBean(bean);
}
}
Example
@Service
public class UserService {
...
}
public class UserThread implements Runnable {
// Bean 주입
UserService userService = (UserService) BeanUtils.getBean("userService");
...
}