zl程序教程

您现在的位置是:首页 >  后端

当前栏目

可以随时拿取spring容器中Bean的工具类

Spring工具容器 可以 bean 随时
2023-09-27 14:24:48 时间

前言

  • 在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);
    }


}