spring initializes beans in different order: SpringUtils.getBean(SpringUtils.java:50) null null null pointer exception,

Keywords: Programming Java Spring Lambda snapshot

spring initializes bean s in different environments in different order.

For the same code, there is no error in the local startup, and there was no error in the test environment before, but now there is an error in the test environment


Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-11-25 09:23:59,573 |-ERROR org.springframework.boot.SpringApplication:858 - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'globalInitializationTask' defined in URL [jar:file:/data/app/spring/aggr-web-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/com/newpearl/aggr/web/init/GlobalInitializationTask.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
	at com.newpearl.aggr.web.AggrApplication.main(AggrApplication.java:34)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
	at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
	at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
	at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.lang.NullPointerException: null
	at com.newpearl.aggr.web.config.SpringUtils.getBean(SpringUtils.java:50)
	at com.newpearl.aggr.web.schedule.AbstractScheduleJob.<init>(AbstractScheduleJob.java:25)
	at com.newpearl.aggr.web.schedule.ScheduleOtherTaskJob.<init>(ScheduleOtherTaskJob.java:9)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at java.lang.Class.newInstance(Class.java:442)
	at com.dangdang.ddframe.job.lite.api.JobScheduler.createJobDetail(JobScheduler.java:122)
	at com.dangdang.ddframe.job.lite.api.JobScheduler.init(JobScheduler.java:107)
	at com.newpearl.aggr.web.schedule.JobContainer.addJob(JobContainer.java:64)
	at com.newpearl.aggr.web.schedule.ShardingTaskBuilder.lambda$initShardingTask$0(ShardingTaskBuilder.java:59)
	at java.util.HashMap.forEach(HashMap.java:1289)
	at com.newpearl.aggr.web.schedule.ShardingTaskBuilder.initShardingTask(ShardingTaskBuilder.java:55)
	at com.newpearl.aggr.web.init.GlobalInitializationTask.init(GlobalInitializationTask.java:46)
	at com.newpearl.aggr.web.init.GlobalInitializationTask.afterPropertiesSet(GlobalInitializationTask.java:36)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
	... 24 common frames omitted

You can see that the final error is

 private CollectTaskService collectTaskService = SpringUtils.getBean(CollectTaskService.class);

It's wrong here. It's empty Is getBean null?

springUtils Source code
package com.newpearl.aggr.web.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Functions:
 *
 * @author xiaocheng
 * @version 1.0
 * @Date 2017 18:13, July 3, 2007
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    /**
     * Get applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Get Bean through name
     * @param name
     * @return bean Real column
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * Get Bean through class
     * @param clazz
     * @param <T> Return type
     * @return  bean Real column
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * Return the specified Bean through name and Clazz
     * @param name  Name
     * @param clazz type
     * @param <T>   Return type
     * @return  bean Real column
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

In other words, springUtils reported an error Not initialized? How can it not be initialized?

It was originally executed during the bean initialization call

package com.newpearl.aggr.web.init;

import com.newpearl.aggr.web.config.SpringUtils;
import com.newpearl.aggr.web.es.ElasticsearchRestClient;
import com.newpearl.aggr.web.schedule.JobContainer;
import com.newpearl.aggr.web.schedule.ShardingTaskBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Global initialization at service startup
 *
 * @author WuJM
 * @version 1.0
 * @date 2019-06-28 11:38
 */
@Component
public class GlobalInitializationTask implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(GlobalInitializationTask.class);

    @Autowired
    private ElasticsearchRestClient client;

    @Autowired
    private ExecutionResultPool executionResultPool;
    @Autowired
    private ShardingTaskBuilder shardingTaskBuilder;
    @Autowired
    private JobContainer jobContainer;
    // Pre initialization
    @Autowired
    private SpringUtils springUtils;

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    /**
     * Unified initialization
     */
    public void init() {
        client.init();
        executionResultPool.init();
        jobContainer.initJobContainer();
        shardingTaskBuilder.initShardingTask();
    }

}

It is executed in the spring afterpropertieset method.

It is estimated that at this time, springUtils did not complete initialization, which resulted in the situation of null.

It can be added as above

@Autowired
    private SpringUtils springUtils;

It depends on springUtils. When spring loads, the bean of springUtils will be initialized first, and then the bean

 

Previously, it was thought that the initialization order of bean s was fixed, and spring utils, in particular, would take precedence. In fact, the order is uncertain The BUG above was exposed, but it didn't appear before

Posted by robinjohn on Mon, 25 Nov 2019 13:22:50 -0800