这两天自己搭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配置错误,如果不能说明类写的有问题。
类检查方面:
1.是否在加了@Controller @Repository @Service 注解
- @Controller
- @RequestMapping(value = "/user")
- public class UserController {
- @Service
- public class UserServiceImpl implements UserService{
- @Repository
- public interface UserDao {
2.spring-mvc的配置中 是否自动注册了controller类
- <mvc:annotation-driven />
- <context:component-scan base-package="lf.controllers"/>
3.spring的配置中,是否注册了用到的类
- <context:annotation-config/>
- <context:component-scan base-package="lf">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
4.如果用了mybatis,看看配置的路径是否正确
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <property name="mapperLocations" value="classpath:mapper/*.xml"/>
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="lf.dao"/>
- <!--<property name="sqlSessionFactoryBeanName" value="lazySqlSessionFactory"/>-->
- </bean>
mapper的namespace是否正确
- <mapper namespace="lf.dao.UserDao">
- <resultMap id="BaseResultMap" type="lf.model.User">
- <id property="id" column="id"/>
如果还跑不起来,就可能是web.xml里面丢了listener
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
我的目录如下