Cannot initialize Application context instance in jmix 2.0 application

I wanted to recreate AppBeans class from Cuba Platform to get instance of every class marked with @Component annotation in my jmix 2.0 application and Copied this code below from the JMIX forum:

public class AppBeans {
private static ApplicationContext applicationContext;

private static void setApplicationContext(ApplicationContext applicationContext) {
    AppBeans.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
    return applicationContext;
}

public static <T> T getBean(Class<T> beanClass, Object... args) {
    try {
        return applicationContext.getBean(beanClass, args);
    } catch (BeansException e) {
        return null;
    }
}

@Component
static class ApplicationContextRetriever {

    @EventListener
    public void storeApplicationContext(ContextRefreshedEvent event) {
        AppBeans.setApplicationContext(event.getApplicationContext());
    }
}

}

It works fine in other jmix projects when I run the app but there is a problem.
I have an abstract SmartTenantEntity class which has a variable ‘code’ type of String. And I made Jmix created ‘User’ entity extend SmartTenantEntity.

And the abstract class has a method ‘generateCode’ annotated with @PostContruct annotation of Spring which gets automatically invoked whenever a instance of the abstract class is created by its child classes.

When Application starts, I think,firstly jmix tries to create instance of User class and then my ‘generateCode’ method is invoked. The code inside the method is:

GenCodeServiceBean bean = AppBeans.getBean(GenCodeServiceBean.class);
code = bean.nextCode(this);

At the end, I’m getting ‘NullPointerException’ because of ‘applicationContext’ variable inside AppBeans class is not initialized and ‘storeApplicationContext’ method of ApplicationContextRetriever class is not triggered yet.

So, what would you recommend to resolve this issue?

Thanks,
Otabek

1 Like