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

2 Likes

Thanks Konstantin, it works!