欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot不掃描@repository的問題及解決

 更新時間:2024年05月29日 14:40:14   作者:Smaksze  
這篇文章主要介紹了springboot不掃描@repository的問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

springboot不掃描@repository問題

問題

單獨使用@repository注解注dao層,而且不使用@mapperscan掃描時,啟動項目會報錯:

Field xxxxMapper in com.sms.shiro.service.impl.xxxxServiceImpl required a bean of type ‘com.sms.shiro.mapper.xxxxMapper’ that could not be found.

一.@mapper和@repository的區(qū)別

1.@mapper是mybatis的注解,@repository是spring家族的注解。

2.使用@mapper注解時,spring并不認(rèn)識,@autowired注入到service里的mapper會爆紅。

二.回到問題中來

明明springboot里的ComponentScan掃描了啟動器包下的所有含注解的組件,那為什么卻找不到@repository的組件?

原因:

造成這個問題的原因是因為springboot在掃描時候自動過濾掉了接口和抽象類,所以@repository修飾的mapper接口并不能稱為一個bean,自然也就無法注入到service中。

三.解決方式

第一種: 不使用@repository,在mapper層接口直接使用@mapper,但如果項目工程較大的話就會很麻煩。

第二種: 如果想使用@repository,因為springboot無法掃描到mapper接口,則在啟動器上使用@mapperscan掃描所有mapper接口的包,如:@MapperScan("com.sms.shiro.*.mapper")

第三種: 其實使用@mapperscan注解掃描mapper接口后,mapper接口就不需要@repository和@mapper去注冊bean了,但如果想項目結(jié)構(gòu)比較明了,在使用了@mapperscan掃描后,@repository和@mapper都可使用,都不會報錯了,但是使用@repository會解決在service中@autowired mapper爆紅的問題。

SpringBoot關(guān)于@Mapper和@Repository的一些疑問

@Mapper 是 Mybatis 的注解,和 Spring 沒有關(guān)系,@Repository 是 Spring 的注解,用于聲明一個 Bean。

@Mapper

Mybatis 需要找到對應(yīng)的 mapper,在編譯的時候動態(tài)生成代理類,才能實現(xiàn)對數(shù)據(jù)庫的一系列操作,所以我們需要在接口上添加 @Mapper 注解。

例如(這里只是為了演示并且sql不復(fù)雜,所以這里使用注解的方式來編寫sql語句):

@Mapper
public interface UserMapper {

    @Select("select * from user where id = #{id}")
    User getById(Integer id);

    @Select("select * from user")
    List<User> getAll();
}

編寫測試方法,可以發(fā)現(xiàn)加了自動裝配注解的userMapper會出現(xiàn)報錯(并不影響代碼正常運行),這是因為@Mapper是Mybatis中的注解,我們沒有顯示的標(biāo)明UserMapper是spring中的一個Bean,idea此時會認(rèn)為在運行時找不到實例注入,所以會提示錯誤

在這里插入圖片描述

雖然這個報錯并不影響代碼的正常運行,但是看著很不舒服,我們可以@Repository注解(也可以使用@Componet,只要注明這是一個bean就可以)來顯示的說明UserMapper是一個bean

@Repository

@Repository 是spring提供的一個注解,用于聲明 dao 層的 bean,如果我們要真正地使用 @Repository 來進行開發(fā),那么我們需要手動實現(xiàn)UserMapperImpl,也就是說手寫 JDBC代碼?。?!

@Repository
public class UserMapperImpl implements UserMapper{
	
	@Override
	public User getById(Integer id){
		// 裝載Mysql驅(qū)動
		// 獲取連接
		// 創(chuàng)建Statement
		// 構(gòu)建SQL語句
		// 執(zhí)行SQL返回結(jié)果
	}
}

@MapperScan(“com.xxx.xxx”)

如果我們不使用@Mapper注解,還有另一種方式讓Mybatis找到mapper接口,那就是 @MapperScan 注解,可以在啟動類上添加該注解,自動掃描包路徑下的所有mapper接口。

@SpringBootApplication
@MapperScan("com.example.springboot_mybatis.mapper")
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

使用@MapperScan注解之后,就不需要在mapper接口上添加任何注解了??!

心得:

總的來說,@Mapper 和 @MapperScan 這兩個必須有一個,否則就會出錯!

@Repository 可有可無,對程序正常運行沒什么影響,但是可以消除idea報錯的問題

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論