zoukankan      html  css  js  c++  java
  • 【Spring】手动获取spring容器对象时,报no qualifying bean of type is defined

    手动获取容器对象时,报no qualifying bean of type is defined,

    经过调查,发现手动获取的时候,该类所在的包必须经过spring容器初始化。

    1.SpringConfigHolder 代码,添加@Component进行ioc

    package com.xxxxxxx.utils.holder;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    /**
     * spring工具类,通过ApplicationContext.getBean获取注册的bean
     * 
     */
    @Component
    public class SpringConfigHolder implements ApplicationContextAware {
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringConfigHolder.applicationContext = applicationContext;
        }
    
        /**
         * 获取spring的bean
         * */
        public static <T> T getBean(Class<T> clazz) {
            return applicationContext.getBean(clazz);
        }
    
    }

    2.配置springmvc-servlet.xml,自动扫描指定包进行ioc

    <context:component-scan base-package="com.xxxxxxx.utils.holder" />

    3.这样在通过SpringConfigHolder.getBean(XXXX.class)的时候就不会出现no qualifying bean of type is defined了。

  • 相关阅读:
    JS 反射机制及 Reflect 详解
    React Hooks
    深入理解 React setState
    React 函数组件和类组件的区别
    tsconfig.json 编译器配置大全
    React TS 解决不声明变量类型时的报错问题
    JSX onClick 和 HTML onclick 的区别
    深入理解 ES6 Generator
    JS 算法与数据结构之队列
    深入理解 ES6 Proxy
  • 原文地址:https://www.cnblogs.com/zengweiming/p/5168456.html
Copyright © 2011-2022 走看看