写在前面的话
当Spring整合SpringMVC时,SpringMVC的springmvc.xml配置文件和Spring的bean.xml配置文件在我们单独使用时,都是直接扫描整个包,但是整合到一起的时候,两个配置文件都同时扫描,就会加载两次bean,会造成很多奇怪的错误。
例如:【No qualifying bean of type ‘org.springframework.jdbc.core.JdbcTemplate’ available: expected at least 1 bean which qualifies as autowire candidate】
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productDaoImpl': Unsatisfied dependency expressed through field 'jdbcTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
解决办法:springmvc.xml中只扫描controller,Spring的bean.xml中排除controller,其他的都扫描。
解决办法
springmvc.xml:
<!-- 只扫描Controller --> <context:component-scan base-package="com.keafmd.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
bean.xml:
<!-- 排除controller,其他的都扫描--> <context:component-scan base-package="com.keafmd"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
以上就是Spring整合SpringMVC时避免Spring加载两次bean的配置方法的全部内容