1. 程式人生 > >No qualifying bean of type [XXX.XXX] found for dependency 解決方法

No qualifying bean of type [XXX.XXX] found for dependency 解決方法

原始碼:

@Service
public class UserService implements UserServices{

    @Autowired
    UserMapper userMapper ;

    public  boolean AddUserInfo(User user)
    {
        if(userMapper.insert(user)>0)
            return  true;
        else
            return  false;
    }

}

目錄結構:
這裡寫圖片描述

報錯資訊:

No qualifying bean of
type [com.mybatistest.dao.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

即userMapper注入失敗,原因是配置檔案中沒有啟動springmvc註解功能(介面不需要寫註解@services)

解決方法:在spring-servlet.xml中新增以下程式碼(其中11至37行為配置json轉換器)

<!-- 避免IE執行AJAX時,返回JSON出現下載檔案 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list
>
</property> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" p:supportedMediaTypes="*/*" /> </mvc:message-converters> </mvc:annotation-driven> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <mvc:default-servlet-handler /> <!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json轉換器 --> </list> </property> </bean>

注:注入失敗更常見的原因是在spring-servlet.xml中沒有新增掃描目錄,導致專案啟動時沒掃描相應的包,無法建立例項。解決辦法是在spring-servlet.xml中新增要掃描的包,比如:

 <context:component-scan base-package="com.mybatistest.Controller"/>
    <context:component-scan base-package="com.mybatistest.service.implement"/>
    <context:component-scan base-package="com.mybatistest.dao"/>