• spring中bean获取工具


    如何通过非注入方式获取spring bean

    package com.example.helper;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    import java.util.Collection;
    import java.util.Map;
    /**
     * bean工具
     * @author xiaog
     * @Date 2021-04-06
     */
    @Component
    public class BeanHelper implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            System.out.println("init applicationContext");
            BeanHelper.applicationContext = applicationContext;
        }
    
        /**
         * 通过beanName返回bean
         * @param beanName
         * @return
         */
        public static Object getBean(String beanName) {
            return applicationContext != null ? applicationContext.getBean(beanName) : null;
        }
    
        /**
         * 通过bean class返回bean
         * @param clazz
         * @param <T>
         * @return
         */
        public static<T> T getBean(Class<T> clazz) {
            return applicationContext != null ? applicationContext.getBean(clazz) : null;
        }
    
        public static <T> T getBean(String beanName, Class<T> clazz) {
            return applicationContext != null ? applicationContext.getBean(beanName,clazz) : null;
        }
    
        public static <T> Collection<T> getBeans(Class<T> clazz) {
            return getBeansMap(clazz).values();
        }
    
        public static <T> Map<String,T> getBeansMap(Class<T> clazz) {
            return applicationContext != null ? applicationContext.getBeansOfType(clazz) : null;
        }
    
    }
    
    不积跬步无以至千里
  • 相关阅读:
    es删除索引
    真人快打11技能键位
    点到线段的距离
    行列快乐值
    按钮变色
    取数求和
    机器分配
    田忌赛马 问题
    雷达
    最小字典序
  • 原文地址:https://www.cnblogs.com/xiaogblog/p/15439018.html
Copyright © 2020-2023  润新知