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的注解。

参考链接:@Repository 与 @Mapper的区别

posted @ 2021-03-23 21:17  rainbow70626  阅读(186)  评论(0编辑  收藏  举报