spring 注入失败报错

报错代码片段:

Error creating bean with name 'itemServiceImpl': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException:
 Could not autowire field: private com.taotao.search.mapper.ItemMapper com.taotao.search.service.ItemServiceImpl.itemMapper;
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
 No qualifying bean of type [com.taotao.search.mapper.ItemMapper] found for dependency:
 expected at least 1 bean which qualifies as autowire candidate for this dependency.
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

 网上的方法都试过了,注解加了,mapper.xml的namespace什么的也检查了好几遍,都找不到错。

因为项目里放了一个*.*.mapper包和*.*.dao包,一度以为这两个包可能有冲突,仔细想想应该也不是这个原因。

经过再三的检查,偶然发现applicationContext-dao的配置文件里没有扫描mapper的包。添上之后问题解决。

附上工程目录和配置文件:

spring 注入失败报错_第1张图片 

applicationContext-dao.xml




	
	
	
	
	
		
		
		
		
		
		
	
	
	
		
		
		
		
	
	
		
		
	

注意配置文件里的最后一个,里面配置上扫描dao包和mapper包


        
        

applicationContent-service.xml




	
	
	
	
 		
	

注意配置文件里包扫描器中扫描service包。


    

springmvc.xml



    
        
    
    
    
        

这个配置文件是配置controller包的扫描,因为父子容器的关系,controller包的扫描要和dao包、service包的扫描分开。

web.xml

最后是web.xml。配置spring扫描上面dao包、service包的配置文件。配置springmvc扫描上面controller包的配置文件。



	taotao-search
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
	
	
		contextConfigLocation
		classpath:spring/applicationContext-*.xml
	
	
		org.springframework.web.context.ContextLoaderListener
	

	
	
		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			utf-8
		
		
	
	
		CharacterEncodingFilter
		*
	


	
	
		taotao-search
		org.springframework.web.servlet.DispatcherServlet
		
		
			contextConfigLocation
			classpath:spring/springmvc.xml
		
		1
	
	
		taotao-search
		/search/*
	
	
	
	    log4jConfigLocation
	    classpath:log4j.properties
	
	
	
	
	    org.springframework.web.util.Log4jConfigListener
	

总结:

*dao.xml文件配置数据库连接层的包扫描。一般是*.*.dao或*.*.mapper,多个包时用“,”分隔。

*service.xml文件配置服务层的包的扫描。一般是*.*.service包,多个时用“,”分隔。

springmvc.xml文件配置视图层的包的扫描。一般是*.*.controller包。

springmvc.xml为什么不用*.controller命名?

可能是因为springmvc.xml属于springmvc容器,dao.xml和service.xml属于spring容器吧!

web.xml文件则配置spring和springmvc分别扫描哪些配置文件

 

你可能感兴趣的:(报错学习)