搭建springboot+mybatis+mysql+maven項目,從controller-service-dao,最後寫mapper.xml,啓動之後報錯如下:
Field helloWorldDAO in com.example.demo.service.ServiceImpl.HelloWorldServiceImpl required a bean of type 'com.example.demo.DAO.HelloWorldDAO' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.DAO.HelloWorldDAO' in your configuration.
報錯基本的意思就是無法找到注入HelloWorldDAO這個bean,經過查找定位,可以用以下兩種方法解決:
1:在HelloWorldDAO這個類上添加@Mapper註解,代碼如下:
package com.example.demo.DAO;
import com.example.demo.entity.student;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface HelloWorldDAO {
List<student> query(String studentId) throws Exception;
}
2:在啓動類上添加包@MapperScan註解,代碼如下:
@MapperScan("com.example.demo.DAO")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
總結:在mapper接口上使用@Mapper註解,可以生成相應的接口實現類。如果接口類比較少的話,當然用@Mapper也是可以的。但是,我們平常在工作中,可能對應的接口比較多,這個時候用@Mapper註解就顯得比較麻煩了。這個時候我們可以在啓動類上加@MapperScan註解,@MapperScan("com.example.demo.DAO"),裏面寫對應接口的路徑,這樣我們只需要配置一次,在當前路徑下的接口類中都可以使用了,這樣是不是很方便呢。
知識就是要不斷的學習,不斷的複習,纔會記憶的更加的深刻。加油,美好的風景一直在路上。