SpringContextHolder

A way to solve spring boot some object can not use

Posted by MichaelChen on 2020-11-30
Estimated Reading Time 1 Minutes
Words 240 In Total
Viewed Times

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

  • use SpringContextHolder

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 !