Last active
August 14, 2022 05:19
-
-
Save yulewei/1c0c842975d3f6abe823ceda87185e2a to your computer and use it in GitHub Desktop.
Utility bean for getting Spring beans from static context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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