First, consider the utility class (most javadoc was removed simply as an example):
public class ApplicationContextUtils { private static ApplicationContext context = null; public static ApplicationContext getContext() { if (!isInitialized()) { throw new IllegalStateException( "Context not initialized yet! (Has the " + "ApplicationContextProviderBean definition been configured " + "properly and has the web application finished " + "loading before you invoked this method?)"); } return context; } public static boolean isInitialized() { return context == null; } @SuppressWarnings("unchecked") public static <T> T getBean(final String name, final Class<T> requiredType) { if (requiredType == null) { throw new IllegalArgumentException("requiredType is null"); } return (T) getContext().getBean(name, requiredType); } static synchronized void setContext(final ApplicationContext theContext) { if (theContext == null) { throw new IllegalArgumentException("theContext is null"); } if (context != null) { throw new IllegalStateException( "ApplicationContext already initialized: it cannot be done twice!"); } context = theContext; } private ApplicationContextUtils() { throw new AssertionError();
Finally, there is the following helper Spring managed bean that actually calls the setContext method:
public final class ApplicationContextProviderBean implements ApplicationContextAware { public void setApplicationContext( final ApplicationContext applicationContext) throws BeansException { ApplicationContextUtils.setContext(applicationContext); } }
Spring will call the setApplicationContext method once after starting the application. Assuming nincompoop was not previously called ApplicationContextUtils.setContext (), which should block the context link in the utility class, allowing getContext () calls to succeed (this means that isInitialized () returns true).
I just want to know if this class violates any principles of good coding practice regarding thread safety in particular (but other nonsense can be found).
Thank you for helping me become a better programmer, StackOverflow!
Regards, LES
PS I did not deal with why I need this utility class. Itβs enough that I really had a legitimate need to access it from a static context anywhere in the application (after loading the Spring context).
java spring multithreading static thread-safety
les2
source share