zoukankan      html  css  js  c++  java
  • 可以随时拿取spring容器中Bean的工具类

    前言

    • 在Spring帮我们管理bean后,编写一些工具类的时候需要从容器中拿到一些对象来做一些操作,比如字典缓存工具类,在没有找到字典缓存时,需要dao对象从数据库load一次,再次存入缓存中。此时需要在util工具类中拿到ioc容器中的dao对象。

    原理

    • spring容器在加载的时候会把ApplicationContext注入到实现了ApplicationContextAware的类中,拿到applicationContext后,可以通过getBean来拿到ioc容器中管理的对象

    • 通过实现DisposableBean接口,在容器消亡时,清除注入的applicationContext.

    代码

    package com.hyq.util;
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.DisposableBean;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.stereotype.Service;
    
    
    @Service
    @Lazy(false)
    /**
     * 获取bean的工具类(通过注入applicationCotnext)
     * @author hyq
     *
     */
    public class SpringUtils implements ApplicationContextAware,DisposableBean
    {
        public static  ApplicationContext applicationContext = null;
    
        @SuppressWarnings("unchecked")
        public static <T> T getBean(String beanName){
            isInjected();
            return (T) applicationContext.getBean(beanName);
        }
    
        public static <T> T getBean(Class<T> requiredType){
            isInjected();
            return applicationContext.getBean(requiredType);
        }
    
    
        @Override
        public void destroy() throws Exception {    
            System.out.println("springUtils工具类清除注入的applicationContext");
            SpringUtils.applicationContext = null;
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext)
                throws BeansException {
            System.out.println("springUtils工具类注入的applicationContext");
            SpringUtils.applicationContext = applicationContext;
        }
    
        /**
         * 判断是否注入
         * @return
         */
        public static void isInjected(){
            if(SpringUtils.applicationContext == null){
                throw new RuntimeException("springUtils applicationContext is not injected!");
            }
        }
    
        public static void main(String[] args) {
            System.out.println(applicationContext);
        }
    
    
    }
    
  • 相关阅读:
    mysql_fullindex全文索引
    MySQL8.0.12安装主从复制读写分离
    备库不能应用事务&Slave_SQL_Running No
    MySQL8.0.19_Group_Replication分布式集群部署
    MySQL8.0.12_InnoDB_Cluster
    oracle12c备份恢复策略
    CentOS7.X静默安装Oracle12C
    binlog恢复数据
    windows安装多个mysql&Docker安装MySQL5.7
    论自我要求
  • 原文地址:https://www.cnblogs.com/jpfss/p/10286240.html
Copyright © 2011-2022 走看看