• 【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了。

  • 相关阅读:
    洛谷 P1591 阶乘数码
    洛谷 P2008 大朋友的数字
    洛谷 P1716 双调序列
    洛谷 P2309 loidc,卖卖萌
    洛谷 P1324 矩形分割
    洛谷 P2690 接苹果
    洛谷 P1239 计数器
    hdu_4352_XHXJ's LIS(数位DP+状态压缩)
    hdu_5648_DZY Loves Math
    hdu_5179_beautiful number(数位DP)
  • 原文地址:https://www.cnblogs.com/zengweiming/p/5168456.html
Copyright © 2020-2023  润新知