MyBatis-Spring包自动扫描MyBatis Mapper接口并将其注册为Spring Bean

发布时间 2023-04-03 15:02:45作者: ban_boi

学习spring整合mybatis时,写SQL语句的Mapper接口明明没有任何被spring接管的痕迹(前面没有注解)但在serviceimpl类中却可以被自动装载。

 

BookDao.java(mapper接口类):

package com.itheima.dao;

import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface BookDao {

//    @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public void save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public void update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public void delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List<Book> getAll();
}

 

 

 BookServiceImpl.java(业务层实现类):

package com.itheima.service.impl;

import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        bookDao.save(book);
        return true;
    }

    public boolean update(Book book) {
        bookDao.update(book);
        return true;
    }

    public boolean delete(Integer id) {
        bookDao.delete(id);
        return true;
    }

    public Book getById(Integer id) {
        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}

 

 

这是因为之前引入的包MyBatis-Spring,默认会扫描整个项目中指定的包及其子包下的所有Mapper接口,并将其注册为Spring Bean。这个扫描范围是可以配置的,通过设置MapperScannerConfigurer的basePackage属性来指定要扫描的包。

若是在配置类里设置扫描范围,就写:

@Configuration
@MapperScan("com.example.dao")
public class MyBatisConfig {
    // 其他配置
}