Spring异常: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

来源:互联网 发布:linux tomcat 日志查看 编辑:程序博客网 时间:2024/05/20 18:53

这两天自己搭spingmvc,总是报错,找不到自动注册的bean

Could not autowire field: private lf.service.UserService lf.controllers.UserController.userService; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [lf.service.UserService] 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)}

建一个单元测试,看看能不能跑起来,如果能跑起来,说明是web配置错误,如果不能说明类写的有问题。
[java] view plain copy
  1.   
类检查方面:
1.是否在加了@Controller  @Repository @Service 注解
[java] view plain copy
  1. @Controller  
  2. @RequestMapping(value = "/user")  
  3. public class UserController {  
[java] view plain copy
  1. @Service  
  2. public class UserServiceImpl implements UserService{  
[java] view plain copy
  1. @Repository  
  2. public interface UserDao {  

2.spring-mvc的配置中 是否自动注册了controller类
[java] view plain copy
  1. <mvc:annotation-driven />  
  2. <context:component-scan base-package="lf.controllers"/>  
3.spring的配置中,是否注册了用到的类
[java] view plain copy
  1. <context:annotation-config/>  
  2.      <context:component-scan base-package="lf">  
  3.             <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  4.      </context:component-scan>  
4.如果用了mybatis,看看配置的路径是否正确
[java] view plain copy
  1. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  2.     <property name="dataSource" ref="dataSource"/>  
  3.     <property name="mapperLocations" value="classpath:mapper/*.xml"/>  
[java] view plain copy
  1. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  2.        <property name="basePackage" value="lf.dao"/>  
  3.        <!--<property name="sqlSessionFactoryBeanName" value="lazySqlSessionFactory"/>-->  
  4.    </bean>  
 
mapper的namespace是否正确
[java] view plain copy
  1. <mapper namespace="lf.dao.UserDao">  
  2.     <resultMap id="BaseResultMap" type="lf.model.User">  
  3.         <id property="id" column="id"/>  
如果还跑不起来,就可能是web.xml里面丢了listener
[java] view plain copy
  1. <listener>  
  2.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  3. </listener>  

我的目录如下


阅读全文
0 0
原创粉丝点击