Jmix AppBeans

Jmix是否也有AppBeans,或者等效替换的类呢?

Jmix 没有提供能通过静态方法获取 bean 的工具类。一般情况下,bean 都可以通过 @Autowire 注入,或者通过 ApplicationContext 查找 bean。

如果你需要一个能使用静态方法的工具类,可以按照下面的方法自己创建一个,在监听到 ContextRefreshedEvent 事件时,设置静态的 ApplicationContext

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());
        }
    }
}
1 个赞

Thanks a lot!