The initialization order of, Spring bean and ordinary java classes in Java programs

for example, I have a Spring bean in my program as follows, which will be used by a custom Util normal class (which is full of static methods).

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException {
    this.context = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}

so if the Spring Bean is definitely not initialized after the Util class is initialized, how does spring solve a problem like this? For example, the Util class"s call to Spring Bean"s SpringContextUtil.getActiveProfile () triggers the initialization of the bean? Or because the bean is not initialized, the SpringContextUtil class is loaded, and then because applicationContext is not injected, Null pointer Exception?

Mar.28,2021

initialize all bean when applicationcontext can init. Don't worry about depend

Menu