zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
    
    不积跬步无以至千里
  • 相关阅读:
    Library 的打包
    Webpack 的高级概念
    前端文件下载的几种方式
    Webpack 的核心概念
    vue框架目录结构
    前端工程化的理解
    this.$nextTick
    某面试题
    React Fiber是什么
    Ant Design 在回显数据的时候报错, Error: must set key for <rc-animate> children
  • 原文地址:https://www.cnblogs.com/xiaogblog/p/15439018.html
Copyright © 2011-2022 走看看