報錯:Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
阿新 • • 發佈:2019-02-16
這兩天自己搭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的配置中,是否註冊了用到的類
4.如果用了mybatis,看看配置的路徑是否正確<context:annotation-config/> <context:component-scan base-package="lf"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
mapper的namespace是否正確<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="lf.dao"/> <!--<property name="sqlSessionFactoryBeanName" value="lazySqlSessionFactory"/>--> </bean>
<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>
我的目錄如下