Skip to content

Instantly share code, notes, and snippets.

@yulewei
Last active August 14, 2022 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yulewei/1c0c842975d3f6abe823ceda87185e2a to your computer and use it in GitHub Desktop.
Save yulewei/1c0c842975d3f6abe823ceda87185e2a to your computer and use it in GitHub Desktop.
Utility bean for getting Spring beans from static context
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* Utility bean for getting Spring beans from static context
*/
@Slf4j
@Component
public class SpringContextHolder implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
private static ApplicationContext context;
private static volatile boolean refreshed;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
log.debug("ApplicationContext is initialized");
SpringContextHolder.context = context;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
log.debug("ApplicationContext is refreshed");
refreshed = true;
}
public static boolean hasContext() {
return (refreshed && context != null);
}
public static ApplicationContext getContext() {
return refreshed ? context : null;
}
public static boolean isRefreshed() {
return refreshed;
}
public static <T> T getBean(Class<T> clazz) {
if (!hasContext()) {
return null;
}
return context.getBean(clazz);
}
public static <T> T getBean(String qualifier, Class<T> clazz) {
if (!hasContext()) {
return null;
}
return context.getBean(qualifier, clazz);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
if (!hasContext()) {
return null;
}
return (T) context.getBean(name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment