A null pointer exception is reported when using the SpringAppContextUtil tool class to get the Spring application context object when writing test code today.
Later, we found that a static variable of ApplicationContext type was declared in the tool class at the beginning, but because the static variable cannot be managed by the Spring container, the context object cannot be used in the direct static call. Because the tool class is in the jar package, it can't be changed, so I wrote a tool class. First, remove the static keyword in the setter method, add @ Autowired annotation to the setter method, and add @ Component annotation to realize the specific bean injection.
package cn.single; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * Get Bean through name * @param name * @return */ public static Object getBean(String name){ return getApplicationContext().getBean(name); } /** * Get Bean through class * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } /** * Return the specified Bean through name and Clazz * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } @Autowired public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * Get applicationContext * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } }