SpringContextHolder Problem
When using @ServerEndpoint()
or @EnableScheduling
and other Annotations classes use @AutoWired
to initialize other classes throw NullPointException
在@ServerEndpoint()
和 @EnableScheduling
或者其他注解的表示类中,运用 @AutoWired
注解初始化其他类对象时抛出空指针异常。
Analysis
@ServerEndpoint()
or @EnableScheduling
and other Annotations have run before @AutoWire
@ServerEndpoint()
or @EnableScheduling
注解和其他注解比@AutoWire
注入早,导致@AutoWire
注入的对象并没有初始化
Solution
code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.hziee.hospital.domain.context;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException { SpringContextHolder.applicationContext = applicationContext; } public static void setContext (ApplicationContext applicationContext) { if (SpringContextHolder.applicationContext == null ) { SpringContextHolder.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext () { assertApplicationContext(); return applicationContext; } @SuppressWarnings ("unchecked" ) public static <T> T getBean (String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } public static <T> T getBean (Class<T> requiredType) { assertApplicationContext(); return applicationContext.getBean(requiredType); } private static void assertApplicationContext () { if (SpringContextHolder.applicationContext == null ) { throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!" ); } } }
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !