1、@Mapper註解:
作用:在接口類上添加了@Mapper,在編譯之後會生成相應的接口實現類
添加位置:接口類上面
@Mapper
public interface UserDAO {
//代碼
}
如果想要每個接口都要變成實現類,那麼需要在每個接口類上加上@Mapper註解,比較麻煩,解決這個問題用@MapperScan
2、@MapperScan
作用:指定要變成實現類的接口所在的包,然後包下面的所有接口在編譯之後都會生成相應的實現類
添加位置:是在Springboot啓動類上面添加,
@SpringBootApplication
@MapperScan("com.lquan.dao")
public class SpringbootMybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}
添加@MapperScan(“com.lquan.dao”)註解以後,com.lquan.dao包下面的接口類,在編譯之後都會生成相應的實現類
3、使用@MapperScan註解多個包
(實際用的時候根據自己的包路徑進行修改這個和我上一篇寫關於CompentScan的使用方式差不多,只不過CompentScan掃描的包下還是需要加入對應的註解,spring才能將其實例化)
@SpringBootApplication
@MapperScan({"com.lquan.demo","com.lquan.user"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4、 如果dao接口類沒有在Spring Boot主程序可以掃描的包或者子包下面,可以使用如下方式進行配置:
(沒驗證過,不確定能否使用,或許需要根據自己定義的包名進行修改路徑)
@SpringBootApplication
@MapperScan({"com.lquan.*.mapper","org.lquan.*.mapper"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
5、@MapperScan最NB的地方是它能夠把掃描的接口編程一個類,並且這個類還能夠被Spring容器所管理.