Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 ApplicationContextHolder 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");
ApplicationContextHolder.context = context;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
log.debug("ApplicationContext is refreshed");
refreshed = true;
}
public static boolean hasApplicationContext() {
return (refreshed && context != null);
}
public static ApplicationContext getApplicationContext() {
return refreshed ? context : null;
}
public static boolean isRefreshed() {
return refreshed;
}
public static <T> T getBean(Class<T> clazz) {
if (!hasApplicationContext()) {
return null;
}
return context.getBean(clazz);
}
public static <T> T getBean(String qualifier, Class<T> clazz) {
if (!hasApplicationContext()) {
return null;
}
return context.getBean(qualifier, clazz);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
if (!hasApplicationContext()) {
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