Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save ufuk/5264e0a3c222ed8fc71dca9e6d821959 to your computer and use it in GitHub Desktop.
Save ufuk/5264e0a3c222ed8fc71dca9e6d821959 to your computer and use it in GitHub Desktop.
Utility bean for getting Spring beans from static context.
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);
}
}
@salprima
Copy link

This gist save my day! Thank you so much.

@augustodossantosti
Copy link

It's a good solution, the only problem is that sonar indicates an error because the static field is wrote from a instance method.

@tuxianchao
Copy link

thanks

@Grytcyna
Copy link

Thanks!

@javaHelper
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment