Skip to content

Instantly share code, notes, and snippets.

@switchover
Created May 8, 2019 23:55
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 switchover/523e563a21ca204f35146d0b53e69466 to your computer and use it in GitHub Desktop.
Save switchover/523e563a21ca204f35146d0b53e69466 to your computer and use it in GitHub Desktop.
[Spring] Utility class example for getting Spring beans using Generic Methods
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
synchronized (this) {
if (ApplicationContextHolder.applicationContext == null) {
ApplicationContextHolder.applicationContext = applicationContext;
}
}
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String qualifier, Class<T> clazz) {
return applicationContext.getBean(qualifier, clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment