SSM或Spring Boor开发中@Repository和@Mapper的区别
在做一个SpringBoot项目的时候在Dao层使用了@Repository注解然后报了这个错:
Description:
Field userService in com.example.demo.Three.controller.UserController required a bean of type 'com.example.demo.Three.dao.UserDao' 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.Three.dao.UserDao' in your configuration.
错误大概意思是没有该Bean。在service使用@Autowired注解也会显示该bean不存在。
于是更换了@Mapper注解,虽然service还是显示未找到该bean,但是程序能够运行成功,后面查阅了资料才理解了。
Mybatis的配置文件有xml文件格式和注解格式,使用@Mapper注解的时候,Spring程序在运行时,Mybatis就会自动找到使用@Mapper注解的mapper,在编译的时候动态生成代理类。所以在service层能够注入成功。
使用@Repository注解也是可以的,只需要加入扫描注解即可。
@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.Three.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
这两种注解的区别在于:
1、使用@Mapper后,不需要在spring配置中设置扫描地址,通过mapper.xml里面的namespace属性对应相关的mapper类,spring将动态的生成Bean后注入到ServiceImpl中。
2、@Repository则需要在Spring中配置扫描包地址,然后生成dao层的bean,之后被注入到ServiceImpl中
@Mapper是Mybatis的注解,@Mapper=@Repository+@MapperScan
@Repository是Spring的注解。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理