在 MyBatis 中,Mapper 接口并不是一个普通的接口,而是一个包含 SQL 语句的映射文件。因此,Mapper 接口并不需要在 Spring 容器中注册为一个 bean,而是由 MyBatis 提供的 MapperScannerConfigurer 来扫描 Mapper 接口,并自动创建 Mapper 接口的实现类,这个实现类中包含了具体的 SQL 执行逻辑。
在这种情况下,@Autowired 注解可以使用在 Mapper 接口上,因为实际上 Spring 注入的是 Mapper 接口的实现类,而不是 Mapper 接口本身。这种方式被称为基于接口的代理注入,Spring 会为每个 Mapper 接口创建一个代理对象,用于执行具体的 SQL 语句。
假设有一个 Mapper 接口 UserMapper,它定义了一些操作数据库的方法,如下所示:
public interface UserMapper {
List<User> findAll();
User findById(Long id);
}
那么可以在 Service 类中使用 @Autowired 注解来注入 UserMapper 接口,
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAllUsers() {
return userMapper.findAll();
}
public User findUserById(Long id) {
return userMapper.findById(id);
}
}
当 UserService 类被实例化时,Spring 会自动为 UserMapper 接口创建一个代理对象,并将它注入到 userMapper 字段中。这样,UserService 就可以使用 UserMapper 接口定义的方法来操作数据库,而不需要手动创建 UserMapper 的实现类。,基于接口的代理注入是一种常用的方式,可以使得 Spring 和 MyBatis 更加方便地集成,提高开发效率和代码质量。
MyBatis中的Mapper接口与Spring的@Autowired注解
在MyBatis中,Mapper接口与SQL映射文件关联,不需要在Spring容器注册。MapperScannerConfigurer负责扫描并创建Mapper接口的实现类。@Autowired能在Mapper接口上使用,Spring为每个接口创建代理对象执行SQL。这种方式简化了Spring和MyBatis的集成,提高了开发效率。
967

被折叠的 条评论
为什么被折叠?



