1

I am getting NullPointerException inside an ApplicationContextAware class and I am not sure why. Why is the applicationContext null on calling getBean(SomeClass.class) method

Following is my BeanProviderUtil class:

@Component
public class BeanProviderUtil implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    public static <T extends Object> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

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

}

On calling function

SomeOtherClass obj = BeanProviderUtil.getBean(SomeOtherClass.class)

I am getting NPE. On debugging, it comes out that applicationContext is not properly initialized by Spring.

Note

Is it because I have enabled lazy bean initialization?

However, I tried disabling lazy initialization by @Lazy(false) as well as from Global application.yml, but it didn't help.

CodeTalker
  • 1,683
  • 2
  • 21
  • 31
  • it's a static variable, and you never assign a value to it. – Stultuske Apr 27 '20 at 08:24
  • How can I autowire application context in a static variable? – CodeTalker Apr 27 '20 at 08:25
  • @Stultuske I am using exact same code as accepted answer of https://stackoverflow.com/questions/36985189/spring-application-context-is-null I need to make the method and variable static. How can I achieve this? – CodeTalker Apr 27 '20 at 08:34
  • @Stultuske even static variables can be Autowired, hence making applicationContext was not the issue. – CodeTalker Apr 28 '20 at 05:18

1 Answers1

1

So I figured out what was going wrong here by Myself. I have set global lazy Initialization and that was the main culprit. Since I was not Autowiring BeanProviderUtil, the bean was never created and hence applicationContext never got initialized.

Setting @Lazy(false) fixes the issue.

Earlier, on disabling @Lazy using @Lazy(false) it was not working because somehow Spring was not recognizing the BeanProviderUtil a component. Adding @ComponentScan to my test class does the trick.

CodeTalker
  • 1,683
  • 2
  • 21
  • 31
  • 1
    Thanks a lot, completely forgot that I put the lazy initialization for all my beans and I was wondering why my context were always null – Hamza Khattabi Sep 08 '22 at 11:45