티스토리 뷰
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");
...
}
'프로그래밍 > Back end' 카테고리의 다른 글
[Back end] Spring Boot Quartz Scheduler (0) | 2023.05.18 |
---|---|
[Back end] Java ExecutorService (0) | 2022.11.21 |
[Back end] Java Tutorial Map and HashMap (0) | 2022.03.25 |
[Back end] Java Tutorial ArrayList VS LinkedList (0) | 2022.03.20 |
[Back end] Java Tutorial Array VS ArrayList (0) | 2022.03.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
TAG
- javascript
- 경력관리
- effective java
- Eclipse
- 제주도 3박4일 일정
- 프로그래머스
- 리액트 16
- 정렬 알고리즘
- 제주도 여행
- 자바스크립트
- 성능분석
- spring
- sort algorithm
- Collection
- 회고
- Linux 명령어
- React
- 오라클 내장 함수
- 프로그래머
- Maven
- Tomcat
- 소프트웨어공학
- SQL
- Java
- 오라클
- 리액트
- 자바
- 리눅스 명령어
- 이직
- 개발환경
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함