使用注解失败的原因及解决方法

启动项目报错:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userSer'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.hans.service.UserService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

出现这种错误,一般有两种情况。

第一种是Service接口的实现类没有添加@Service("xxx")注解,这个很好解决,没有加上就完了。

第二种是配置文件中包的扫描问题,这个也很简单,找到配置文件中的相关配置。

第一种修改方式

    在spring-mybatis的相关配置中配置

<!-- 自动扫描 -->  
    <context:component-scan base-package="com.hans"/>  
这个地方 base-package 中的值可以为com.hans,也可以是com.hans.* ,效果是一样的。

第二种修改方式

    在springmvc相关配置文件中配置

修改之前

<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 (注册@Component,@Controller,@Service,@Repository等注解标记的组件)-->  
    <context:component-scan base-package="com.hans.controller" />  

修改之后

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 (注册@Component,@Controller,@Service,@Repository等注解标记的组件)-->  
    <context:component-scan base-package="com.hans.controller,com.hans.entity,com.hans.service" />  

讲到这里日常吐槽一下,有些项目中还在使用new对象,能用配置解决的问题最好,有工具不用简直是暴殄天物。

解决方法如上,添加entity的包自动扫描,实体类加上@Component("xxx"),要用的时候@Autowired即可,简单便捷。

个人感觉new对象的方式起码是自断一臂,spring的ioc白做了,虽然咱们公司的项目就是这样玩的,哈哈哈,尴尬尴尬,项目太大,没人搞,姑且先用着,左手一个new对象,右手一个new对象,酸爽。

猜你喜欢

转载自blog.csdn.net/qq_29410905/article/details/80251747