Forked from baybatu/getting-spring-bean-from-unmanaged-area.java
Last active
December 17, 2022 14:16
-
-
Save ufuk/5264e0a3c222ed8fc71dca9e6d821959 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 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); | |
} | |
} |
This gist save my day! Thank you so much.
It's a good solution, the only problem is that sonar indicates an error because the static field is wrote from a instance method.
thanks
Thanks!
Can you please guide on https://stackoverflow.com/questions/44577628/how-to-get-method-name-in-spring-filter
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks like a very simple solution to a common problem, but it brings lots of trouble when used in a non-trivial appliation, for the following reasons:
There are "solutions" to fix each of these issues, but each one adds new more complex problems. I started building such a class and finally abandoned due to the growing complexity.
Best is to rely on singleton objects in the context of an application, just like the ServletContext, or the TestContext, and to stick to it.