zoukankan      html  css  js  c++  java
  • 从spring容器中取出注入的bean

    从spring容器中取出注入的bean 工具类,代码如下:

    package com.hyzn.fw.util;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    /** 
     * @ClassName: SpringBeanUtil
     * @Description: TODO  Spring获取bean的工具类,可用于在线程里面获取bean 
     *                  需要在 类上 标注 @Component ,否则没有将此工具类 注入到spring容器中
     * @author xbq
     * @version 1.0
     * @date 2017-2-21 下午2:30:38
     */
    @Component
    public class SpringBeanUtil implements ApplicationContextAware{
        
        private static ApplicationContext applicationContext = null;  
          
        // 获取ApplicationContext对象
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
            SpringBeanUtil.applicationContext = applicationContext;  
        }  
      
        /**
         * @Title: getBeanByName
         * @Description: TODO  通过bean的名字来获取Spring容器中的bean
         * @param beanName
         * @return
         * @return: Object
         */
        public static Object getBeanByName(String beanName) {  
            if (applicationContext == null){  
                return null;  
            }  
            return applicationContext.getBean(beanName);  
        }  
      
        public static <T> T getBean(Class<T> type) {  
            return applicationContext.getBean(type);  
        }  
    }
  • 相关阅读:
    11.2~11.8 每周总结
    11.30~11.6 每周总结
    架构之美 图书笔记 03
    每周总结 10.26-11.1
    每周总结 10.19-10.25
    每周总结 10.12-10.18
    [Tips] centos下docker服务开机自启动
    [Notes] Linux内网穿透
    [Tips] python 文件读写
    [Tips] python 文件读写
  • 原文地址:https://www.cnblogs.com/xbq8080/p/6593348.html
Copyright © 2011-2022 走看看