手动获取容器对象时,报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了。