zoukankan      html  css  js  c++  java
  • Spring获取bean的工具类

    package com.tech.jin.util;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    /**
     * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
     * 
     */
    public class SpringUtil implements ApplicationContextAware {
        private static ApplicationContext applicationContext;
    
        /**
         * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
         */
        public void setApplicationContext(ApplicationContext applicationContext) {
            SpringUtil.applicationContext = applicationContext; // NOSONAR
        }
    
        /**
         * 取得存储在静态变量中的ApplicationContext.
         */
        public static ApplicationContext getApplicationContext() {
            checkApplicationContext();
            return applicationContext;
        }
    
        /**
         * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
         */
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String name) {
            checkApplicationContext();
            return (T) applicationContext.getBean(name);
        }
    
        /**
         * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
         */
        @SuppressWarnings("unchecked")
        public static <T> T getBean(Class<T> clazz) {
            checkApplicationContext();
            return (T) applicationContext.getBeansOfType(clazz);
        }
    
        /**
         * 清除applicationContext静态变量.
         */
        public static void cleanApplicationContext() {
            applicationContext = null;
        }
    
        private static void checkApplicationContext() {
            if (applicationContext == null) {
                throw new IllegalStateException(
                        "applicaitonContext未注入,请在applicationContext.xml中定义本SpringUtil--------<bean class='xxxx.SpringUtil' />");
            }
        }
    }

    另外,还需要在applicationContext.xml中定义SpringUtil--------<bean class='xxxx.SpringUtil' />

  • 相关阅读:
    流程控制语句-while循环
    流程控制语句-for循环
    流程控制语句-switch选择语句
    多重判断if..else嵌套语句
    深入 Laravel 内核之IOC容器
    深入 Laravel 内核之工厂模式
    Swoole 中使用 WebSocket 异步服务器、WebSocket 协程服务器
    Swoole 中使用 HTTP 异步服务器、HTTP 协程服务器
    Swoole 中使用 TCP 异步服务器、TCP 协程服务器、TCP 同步客户端、TCP 协程客户端
    UI视图面试相关(上)
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/6256878.html
Copyright © 2011-2022 走看看