1. 程式人生 > >ssm框架整合出現的介面註解“No qualifying bean of type found for dependency”

ssm框架整合出現的介面註解“No qualifying bean of type found for dependency”

專案結構:出錯位置:在UserController中,對介面注入失敗
package controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.UserDao;
import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

@Controller
public class UserController {

    @Autowired
    private UserDao userDao;



    @RequestMapping("/create")
    public String create(@ModelAttribute("form")User users,Model model) throws IOException {
        if((userDao.queryUser(users.getName()) == null)){
            userDao.insertUser(users);
            model.addAttribute("User",users);
            return "login";
        }else{
            return "create";
        }
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("form") User User, Model model) throws IOException {
        model.User tmpUser = userDao.queryUser(User.getName());
        if(User.getPwd().equals(tmpUser.getPwd())){
            model.addAttribute(tmpUser);
            if (request.getParameter("save") != null) {
                savePassword(response, tmpUser);
            }
            return "detail";
        }else{
            return "login";
        }
    }

    public void savePassword(HttpServletResponse response, User users){
        Cookie UserCookie = new Cookie("username", users.toString());
        //設定Cookie的有效期為3天
        UserCookie.setMaxAge(60 * 60 * 24 * 3);
        response.addCookie(UserCookie);
    }
}

錯誤資訊:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.UserDao controller.UserController.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.UserDao] 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)}
Mybatis版本:3.3.0    根據錯誤提示表明UserDao介面註解失敗。UserDao介面是mybatis的mapper.xml對映介面。一般情況下介面註解失敗的原因是mapper對映檔案配置出錯和spring配置檔案出錯。在spring配置檔案中影響到UserDao介面的只有資料來源配置以及MapperFactoryBean的配置。 mapper.xml
<?xml version="1.0" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
> <mapper namespace="test"> <select id="queryUser" resultType="model.User" parameterType="java.lang.String">
select * from user where name=#{value} </select> <insert id="insertUser" parameterType="model.User"> insert into user(name,pwd,age) values(#{name},#{pwd},#{age}) </insert> </mapper>

其中一個錯誤就是namespace的名字問題。mapper的namespace必須是與之對映的介面類全名,由於之前寫的專案是自己new的介面實現類,然後再方法中呼叫sqlSession的方法。例如:

其中test就是mapper的namespace名,insertUser就是對應的insertid。其本質介面實現類和mapper並不是對映關係,因此完全可以執行成功。在本專案中要使介面和mapper出現對映關係,那麼namespace的名字必須是類的全名。即把”test“改為“dao.UserDao”。還有一點值得注意,在UserDao中的方法命名必須和mapper一直。例如:UserDao
package dao;

import model.User;

public interface UserDao {
    public User queryUser(String name);
    public void insertUser(User User);
}

當配置成功後出現左側的綠色箭頭,在mapper檔案中也有。當這個問題改好之後發現專案執行還是和原來一樣的錯誤,那麼現在唯一可能出錯的地方就是spring配置檔案的問題。

ApplicationContext-datasuorce.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- 載入配置檔案 -->
    <context:property-placeholder location="classpath:META-INF/db.properties"/>
    <!-- 資料庫連線池,使用dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive">
            <value>255</value>
        </property>
        <property name="maxIdle">
            <value>2</value>
        </property>
        <property name="maxWait">
            <value>120000</value>
        </property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 指定資料來源 -->
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="classpath:config/UserDaoMap.xml"/>
    </bean>

    <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="dao.UserDao" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

</beans>
在除錯的時候發現UserDao這個介面注入還是失敗,沒辦法只好自己手動載入。
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-datasource.xml");
        userDao = (UserDao) applicationContext.getBean("userDao");
新增如上程式碼,發現可以執行。那麼說明配置檔案沒有問題,那麼究竟是什麼原因導致的呢?會不會是配置檔案沒有自動載入。web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/applicationContext-datasource.xml</param-value>
  </context-param>

 <!--<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  -->

  <servlet>
    <servlet-name>smart</servlet-name>
    <servlet-class>
      org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:META-INF/applicationContext.xml</param-value>
    </init-param>

    <load-on-startup>3</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>smart</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
可以看到配置檔案我也載入了,經過比對後發現自己沒有新增監聽器(已經註釋),加上後項目執行成功。對於監聽器做了哪些事這裡附上一個連結:詳解contextConfigLocation。   至此針對ssm mapper對映介面注入失敗問題的總結:
    1.mapper的namespcae命名和介面必須一致,介面中的方法名和mapper對映id必須一致。    2.對於spring配置檔案一定要載入,一直要配置監聽器。

相關推薦

ssm框架整合出現介面註解No qualifying bean of type found for dependency

專案結構:出錯位置:在UserController中,對介面注入失敗package controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; imp

配置ssm專案報錯:No qualifying bean of type ... found for dependency ...expected at least 1 bean which

配置ssm專案時,提示提示在service層注入出錯,出錯資訊如下:大致的錯誤資訊為: cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:

No qualifying bean of type...found for dependency:expected at least 1 bean which qualifies... 異常解決方案

ssm框架,maven管理,idea開發,搭建過程中遇到以下問題: No qualifying bean of type ... found for dependency: expected at

新下載的工程,啟動tomcat出現識別檔案失敗的現象。No qualifying bean of type 'com.kanq.platform.cert.mapper.CertificateSjdr

首選檢查下資料庫配置: 問題資訊描述如下: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with nam

SpringBoot- springboot集成Redis出現報錯:No qualifying bean of type 'org.springframework.data.redis.connection.RedisConnectionFactory'

ani 集成 autowired rt.jar evaluate tab using getbean iat Springboot將accessToke寫入Redisk 緩存,springboot集成Redis出現報錯 No qualifying bean of type

No qualifying bean of type報錯問題處理

ted don mon ref scan getbean metadata .get 一個 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of typ

spring註入時報錯::No qualifying bean of type 'xxx.xxMapper'

and class can 解決 base ica fail pri exception 做一個小項目,因為有 baseService,所以偷懶就沒有寫單獨的每個xxService接口,直接寫的xxServiceImpl,結果在service實現類中註入Mapper的時

spring異步執行報異常No qualifying bean of type 'org.springframework.core.task.TaskExecutor' available

sun type determine ext tde dap 查找 ann def 最近觀察項目運行日誌的時候突然發現了一個異常, [2018-04-03 10:49:07] 100.0.1.246 http-nio-8080-exec-9 DEBUG org.sprin

[java]No qualifying bean of type 解決方法

1.錯誤原因:註解寫錯   2.原理如下: 現在的spring早就已經擺脫了之前一堆xml配置檔案的情況,都是通過註解配置的方式進行依賴注入了,通常情況下,我們會有一個配置類,然後通過AnnotationConfigApplicationContext進行載入 AnnotationCo

No qualifying bean of type

這種找不到bean的錯誤,兩種情況,一是xml配置的掃描路徑有誤,沒掃到。二是註解有錯誤,缺失了 @service或者其他註解       這裡是因為   裡面的IMessageService 的實現類 缺少了@Serv

factory.NoSuchBeanDefinitionException: No qualifying bean of type

我的錯誤原因是 自己 引用了自己 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.moneyP2P.p2p.VSFP.spring.serv

【Spring 定時器】定時器 No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined

stackoverflow 版 http://stackoverflow.com/questions/31199888/spring-task-scheduler-no-qualifying-bean-of-type-org-springframework-sche

【Spring 定時器】Spring 定時器 No qualifying bean of type [org.springframework.scheduling.TaskScheduler]

Spring 定時器 No qualifying bean of type [org.springframework.scheduling.TaskScheduler] is defined 最近專案裡面,用了spring的定時任務,一直以來,專案執行的不錯。定時器

No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found amon

多資料來源報錯:No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found among  candidates: [test2DataSource, te

品優購專案異常No qualifying bean of type [org.springframework.data.redis.core.RedisTemplate] found for depe

報錯 嚴重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.sprin

SpringCloud:No qualifying bean of type 'org.springframework.cloud.client.discovery.DiscoveryClient'

問題描述 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'discoveryClientConfigServiceB

spring下bean繼承另一個bean導致No qualifying bean of type錯誤。

前言 在spring下面假如你定義了自動掃描: 然後,service長這樣: biz繼承了service: 執行時候你會發現: org.springframework.beans.factory.UnsatisfiedDependencyException

spring 報錯 No qualifying bean of type

報錯如下 --------------------------------------------- 嚴重: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error cr

JPA錯誤記錄 No qualifying bean of type 'javax.persistence.EntityManagerFactory' available

最近在公司在一個已經很臃腫的專案上新增新功能,要求使用的是新資料庫,並且使用Spring Data JPA。這讓我很懵逼,因為此專案臃腫的程度已經無法想象了,裡面有N+個數據源,並且ORM使用到了JDBC、mybatis、Spring Data JPA。如果當時約定使用相同的技術就不會出現問題了

MyBatis對映錯誤,No qualifying bean of type 'xx.xx.UserDao' available

在學習myBatis持久層框架時,通常遇到一些挫折,下面我遇到一個錯讓我頭疼了兩週,但最後的解決方案卻十分簡單,下面就讓我說說 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitio