关于spring:SpringBootSpring容器工具类SpringContextUtilsjava

7次阅读

共计 2195 个字符,预计需要花费 6 分钟才能阅读完成。

SpringBoot——容器工具类 SpringContextUtils.java

更多精彩内容,欢送关注我的微信公众号:编程 Thinker (code_thinker_666)

<img src=”http://jeff.spring4all.com/FoAxSKtLwp-tLYc4XdMCr9SVT8DU” style=”zoom: 25%;” />

背景

​ 在 SpringBoot 我的项目中,通常会遇到工具类中调用 Spring 容器中的 Bean,因为工具类通常是静态方法,咱们通常不应用主动注入,这时,就须要一种不主动注入便能够从 Spring 容器中拿出 Bean 的工具了,这里我把我日常用的工具类 SpringContextUtils.java,分享给大家,心愿能够帮到你。

工具类

git 地址:https://gitee.com/learning-wo…

源码如下:

import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring 容器工具类
 *
 * @author chentiefeng
 * @date 2020-10-23 11:37
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    /**
     * 上下文对象
     */
    private static final AppContainer APP_CONTAINER = new AppContainer();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {APP_CONTAINER.setApplicationContext(applicationContext);
    }

    /**
     * 获取 ApplicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {return APP_CONTAINER.getApplicationContext();
    }

    /**
     * 通过 clazz, 从 spring 容器中获取 bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {return getApplicationContext().getBean(clazz);
    }

    /**
     * 获取某一类型的 bean 汇合
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> Map<String, T> getBeans(Class<T> clazz) {return getApplicationContext().getBeansOfType(clazz);
    }

    /**
     * 通过 name 和 clazz, 从 spring 容器中获取 bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {return getApplicationContext().getBean(name, clazz);
    }
    /**
    * 动态外部类,用于寄存 ApplicationContext
    */
    @Data
    public static class AppContainer {private ApplicationContext applicationContext;}

    /**
     * 获取配置文件配置项的值
     *
     * @param key 配置项 key
     */
    public static String getEnvironmentProperty(String key) {return getApplicationContext().getEnvironment().getProperty(key);
    }

    /**
     * 获取 spring.profiles.active
     */
    public static String[] getActiveProfile() {return getApplicationContext().getEnvironment().getActiveProfiles();
    }

}

应用示例

/**
 * 用户工具类,用于获取用户信息
 *
 * @author chentiefeng
 * @date 2021/2/8 17:38
 */
public class UserUtils {

    /**
     * 获取以后用户的 ID
     * @return
     */
    public static UUID getCurrentUserId(){UserService userService = SpringContextUtils.getBeans(UserService.class);
        return userService.getCurrentUser().getId();
    }
}

本文由博客一文多发平台 OpenWrite 公布!

正文完
 0