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);
        }
    
    
    }
    
  • 相关阅读:
    【FPGA篇章四】FPGA状态机:三段式以及书写方法
    【FPGA篇章三】FPGA常用语句:Verilog基本语法要素
    【FPGA篇章二】FPGA开发流程:详述每一环节的物理含义和实现目标
    【FPGA篇章一】FPGA工作原理:详细介绍FPGA实现编程逻辑的机理
    学习python随笔记
    Spring中的@Bean注解、@Configuration注解、@Value
    什么是Maven项目
    SpringBoot(四)thymeleaf+MyBatis+MySql
    SpringBoot(三)thymeleaf+JPA+MySql
    SpringBoot(二)thymeleaf模板的引入
  • 原文地址:https://www.cnblogs.com/jpfss/p/10286240.html
Copyright © 2011-2022 走看看