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.