我們定義DemoMapper類,但是並沒有在該類上定義類似@Service或者@Controller之類的註解,那麼爲什麼可以被Spring管理呢?
(1)方式一:使用@Mapper註解
爲了讓DemoMapper能夠讓別的類進行引用,我們可以在DemMapper類上添加@Mapper註解:
- @Mapper
- public interface DemoMapper {
- @Insert("insert into Demo(name) values(#{name})")
- @Options(keyProperty="id",keyColumn="id",useGeneratedKeys=true)
- public void save(Demo demo);
- }
直接在Mapper類上面添加註解@Mapper,這種方式要求每一個mapper類都需要添加此註解,麻煩。
(2)方式二:使用@MapperScan註解
通過使用@MapperScan可以指定要掃描的Mapper類的包的路徑,比如:
- @SpringBootApplication
- @MapperScan("com.kfit.*.mapper")
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
或者:
- @SpringBootApplication
- @MapperScan("com.kfit.mapper")
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
可以根據包的結構指定不同的表達式。
使用@MapperScan註解多個包
可以使用如下的方式指定多個包:
- @SpringBootApplication
- @MapperScan({"com.kfit.demo","com.kfit.user"})
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
如果mapper類沒有在Spring Boot主程序可以掃描的包或者子包下面,可以使用如下方式進行配置: