Is there any alternatives to AppBeans

Hi there,
I want to use AppBeans.get(BeanClass.class) as we use in CUBA,
Is there any alternatives in JMIX?

Thanks

Jmix doesn’t provide a way to get beans using a static method of a utility class. Normally beans are available through injection with @Autowire, lookup with ApplicationContext or automatic injection into specific methods known to the framework, like @InstanceName-annotated methods.

If you need a utility class holding the ApplicationContext in a static variable, you can easily create it in your project, for example:

package com.company.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

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) {
        return applicationContext.getBean(beanClass);
    }

    @Component
    static class ApplicationContextRetriever {

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

Regards,
Konstantin

4 Likes

Thanks Konstantin, it works!

This works - in most cases. During application startup though, however, there is a NullPointerException thrown because the ApplicationContext is null at that point. HOWEVER, the old deprecated CUBA AppBeans implementation works just fine during app startup. Any advice?

Try to prioritize the listener using org.springframework.core.annotation.Order annotation:

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

Yup, that makes it work - may want to update the documentation with mention of same!

1 Like