Spring Bean工具类

SpringUtils工具类

import cn.caijiajia.framework.util.EnvUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.OrderUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * SpringUtils
 *
 * @author kancy
 * @date 2022/3/7 14:31
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static Object getBean(String beanName){
       return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> beanClass){
        return applicationContext.getBean(beanName, beanClass);
    }

    public static <T> T getBean(Class<T> beanClass){
        return applicationContext.getBean(beanClass);
    }

    public static <T> Map<String, T> getBeanMap(Class<T> beanClass){
        return applicationContext.getBeansOfType(beanClass);
    }

    public static <T> List<T> getBeans(Class<T> beanClass){
        Map<String, T> beansOfType = applicationContext.getBeansOfType(beanClass);
        if (CollectionUtils.isEmpty(beansOfType)){
            return Collections.emptyList();
        }
        ArrayList<T> beanList = new ArrayList<>(beansOfType.values());
        beanList.sort(Comparator.comparingInt(o -> OrderUtils.getOrder(o.getClass())));
        return beanList;
    }

    public static void publishEvent(Object event){
        applicationContext.publishEvent(event);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }

    public static String getApplicationName() {
        return applicationContext.getApplicationName();
    }

    public static String getEnv() {
        return EnvUtil.getEnv().name();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
}

posted @ 2022-08-27 22:33  kancy  阅读(168)  评论(0编辑  收藏  举报