記錄一下mybatis-spring-boot-starter配置mybatis插件.
以前使用mybatis的自定義插件的時候都是使用xml的配置形式來配置,現在使用starter的時候突然一下不知道怎麼配置了,這裡記錄一下怎麼配置mybatis的插件。
參考連結
spring boot 中如何設定mybatis的插件
使用starter
現在使用springboot項目引入元件基本都是使用starter的形式來引用了。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
mybatis-spring-boot-autoconfigure的使用手冊
開始以為使用starter加載插件應該也是在配置檔案裡面配置,找到一個屬性是這樣的,有一個這樣的屬性,這個interceptors是一個集合,點選想對應的方法看源碼對應是get方法
mybatis.configuration.interceptors對應的方法是這個,這是一個get方法,一般是設定屬性都是對應的set方法,是以這裡如果配置了之後是啟動不起來的,會報類型轉換錯誤。
public List<Interceptor> getInterceptors() {
return interceptorChain.getInterceptors();
}
正确的使用方法
文檔上面的介紹是這樣的,隻要把插件攔截器配置成一個bean就可以了,mybatis-starter會自動加載的。
代碼
定義一個Configuration,這個Configuration會被springboot加載到就可以的,SqlCostInterceptor就是自己寫大插件攔截器。
package com.madman.springbootdemo.mybatisInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfiguration {
@Bean
SqlCostInterceptor myInterceptor() {
return new SqlCostInterceptor();
}
}
使用ConfigurationCustomizer來自定義加載
這個可以參考最上面那個連結,就是實作這個接口的方法,然後把他加載成bean就可以。