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

  • 相关阅读:
    [loj6271]生成树求和
    [cf1209E]Rotate Columns
    [cf1491H]Yuezheng Ling and Dynamic Tree
    [atARC064F]Rotated Palindromes
    [cf1491G]Switch and Flip
    [cf1491F]Magnets
    [atARC063F]Snuke's Coloring 2
    [atARC062F]Painting Graphs with AtCoDeer
    [atARC061F]Card Game for Three
    [atARC112E]Rvom and Rsrev
  • 原文地址:https://www.cnblogs.com/zengweiming/p/5168456.html
Copyright © 2011-2022 走看看