About the reason and solution of @Autowired injection as a null pointer

Problem background

You need to read the parameters from the yml configuration file, write a config entity class, add GET, SET methods, and report a null pointer when @Autowired injects this configuration class into other classes.

Cause one of the problem

1. Cannot call other classes in a timed task. 2. Cannot new a class.
Then inject the value, because the timed task will start a new process, and the spring value will be injected into the initial class, but this valued class is not used, but a valueless class is called.

Cause two of the problem

Google’s great reply
Insert picture description here
translating human words is: initialization sequence

Member variable initialization -> Constructor -> @Autowired

When calling get, it has not yet entered the life cycle of autowired, it is naturally empty, and the value cannot be obtained, and a null pointer error is reported.

solution

Introduce tools

/**
 * @author [email protected]
 * 此工具类用于从Spring的上下文中去获取到类,解决@autowird注入空指针的问题
 * @version 1.0
 * @date 2020/10/27 16:54
 */
@Component
public class ApplicationContextHelperUtil implements ApplicationContextAware {
    
    
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext( ApplicationContext applicationContext1 ) throws BeansException {
    
    
        applicationContext = applicationContext1;
    }

    public static ApplicationContext getApplicationContext(){
    
    
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
    
    
        return (T) applicationContext.getBean(clazz);
    }
}

At the same time the method is called by

@Autowired
HeartbeatConfig heartbeatConfig;

To

private static HeartbeatConfig heartbeatConfig =(HeartbeatConfig) ApplicationContextHelperUtil.getBean(HeartbeatConfig.class);

Guess you like

Origin blog.csdn.net/wenyichuan/article/details/109315211