ApplicationContextProvier 구현
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Nullable
public static <T> T getBean(String beanName, Class<T> requireType) {
if (Objects.isNull(applicationContext)) {
return null;
}
return applicationContext.getBean(beanName, requireType);
}
@Override
public void setApplicationContext(@Nullable ApplicationContext applicationContext)
throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
}Bean 가져오기
Bean name에 주의
혹시 모르니 null 체크는 해주는게 좋을듯
String branchServiceBeanName = "branchService";
BranchService branchService = ApplicationContextProvider
.getBean(
branchServiceBeanName,
BranchService.class
);
if (Objects.nonNull(branchService)) {
branchService.sayHello();
}References
ApplicationContextProvier를 좀 편하게 쓸 수 있게 변경하였다.
사용하는 쪽에서 null 체크 하지 않아도 된다.
해당 클래스의 유일한 Bean일 경우 beanName을 입력하지 않아도 된다.
import java.util.Objects;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@NonNull
public static <T> T getBean(String beanName, Class<T> requiredType) throws BeansException {
Objects.requireNonNull(applicationContext,
"applicationContext is null. " + beanName + ", " + requiredType.getName());
T bean = null;
try {
bean = applicationContext.getBean(beanName, requiredType);
} catch (BeansException beansException) {
log.error("getBean Error " + beanName + ", " + requiredType.getName());
}
Objects.requireNonNull(bean, "bean is null " + beanName + ", " + requiredType.getName());
return bean;
}
@NonNull
public static <T> T getBean(Class<T> requiredType) throws BeansException {
Objects.requireNonNull(applicationContext,
"applicationContext is null. " + requiredType.getName());
T bean = null;
try {
bean = applicationContext.getBean(requiredType);
} catch (BeansException beansException) {
log.error("getBean Error " + requiredType.getName());
}
Objects.requireNonNull(bean, "bean is null " + requiredType.getName());
return bean;
}
@Override
public void setApplicationContext(@Nullable ApplicationContext applicationContext)
throws BeansException {
ApplicationContextProvider.applicationContext = applicationContext;
}
}