我是靠谱客的博主 文静冬天,这篇文章主要介绍Springboot普通类如何获取bean实例?,现在分享给大家,希望可以做个参考。

从Spring上下文中获取bean实例:

private JWTConfig jwtConfig=null;
    public JWTConfig getJWTConfig(){
        if(jwtConfig==null){
        	//根据类名获取
            jwtConfig = SpringContextUtil.getBeanByClass(JWTConfig.class);
        }
        return jwtConfig;
    }

Spring上下文工具类:

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获得spring上下文
     * @return ApplicationContext spring上下文
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /***
     * 根据一个bean的id获取配置文件中相应的bean
     */
    public static Object getBean(String beanId) throws BeansException {
        if (applicationContext.containsBean(beanId)) {
            return applicationContext.getBean(beanId);
        }
        return null;
    }

    /***
     * 根据一个bean的类型获取配置文件中相应的bean
     */
    public static <T> T getBeanByClass(Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
}

最后欢迎大家使用帮助记忆网站:助记宝

最后

以上就是文静冬天最近收集整理的关于Springboot普通类如何获取bean实例?的全部内容,更多相关Springboot普通类如何获取bean实例内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(43)

评论列表共有 0 条评论

立即
投稿
返回
顶部