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

SpringBoot整合Mybatis自定義攔截器不起作用的處理方案

 更新時間:2021年09月23日 12:05:31   作者:小胖學編程  
這篇文章主要介紹了SpringBoot整合Mybatis自定義攔截器不起作用的處理方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

SpringBoot整合Mybatis自定義攔截器不起作用

Mybatis插件生效的方式:

1. 原始的讀取mybatis-config.xml文件

該方式和Spring無關,是通過反射的形式創(chuàng)建插件對象,此時會執(zhí)行org.apache.ibatis.plugin.Interceptor#setProperties方法,以讀取配置參數(shù)。

mybatis:
  mapper-locations: classpath*:/mapping/*.xml
  type-aliases-package: com.tellme.pojo
  #讀取全局配置的地址
  config-location: classpath:mybatis-config.xml

在resource目錄下配置mybatis的全局配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25000"/>
    </settings>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    </typeAliases>
    <!--配置的插件名-->
    <plugins>
        <plugin interceptor="com.xxx.yyy.plugins.PrintSqlInfoInterceptor"/>
    </plugins>
</configuration>

2. 與SpringBoot容器整合

網(wǎng)上很多方案說:mybatis自定義攔截器上加上@Component注解便可以生效。但是我將自定義攔截器放入到Spring容器中,自定義攔截器卻失效了。

然后找到了springboot配置多數(shù)據(jù)源后mybatis攔截器失效文章,說是自定義配置了數(shù)據(jù)源導致了攔截器失效。

2.1 mybatis的自動裝載

源碼位置:org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
  private static Log log = LogFactory.getLog(MybatisAutoConfiguration.class);
  @Autowired
  private MybatisProperties properties;
   //會依賴注入Spring容器中所有的mybatis的Interceptor攔截器
  @Autowired(required = false)
  private Interceptor[] interceptors;
   ...
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    factory.setConfiguration(properties.getConfiguration());
    //手動放入到了setPlugins方法中。
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      factory.setPlugins(this.interceptors);
    }
    if (this.databaseIdProvider != null) {
      factory.setDatabaseIdProvider(this.databaseIdProvider);
    }
    if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    }
    if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
    }
    if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      factory.setMapperLocations(this.properties.resolveMapperLocations());
    }
    return factory.getObject();
  }
   ...
}

上面源碼中:自動注入了Interceptor[]數(shù)組(我們只需將mybatis的自定義攔截器對象放入到Spring容器中)。后續(xù)放入了sqlSessionFactory中。

但是項目中雖然自定義配置了sqlSessionFactory類,但卻未設置factory.setPlugins(this.interceptors);。導致即使將自定義攔截器放入到Spring容器,但卻不生效。

解決方法,需要手動修改自定義的sqlSessionFactory類。

3. 在mybatis-config.xml配置又放入Spring容器

這種情況下,mybatis自定義攔截器會被執(zhí)行兩次。即在mybatis-config.xml配置的攔截器會通過反射的方式創(chuàng)建攔截器,放入Spring容器的攔截器也會被初始化。

源碼位置:org.mybatis.spring.SqlSessionFactoryBean#buildSqlSessionFactory

protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
    Configuration configuration;
    ...讀取屬性中的plugins,即org.mybatis.spring.SqlSessionFactoryBean#setPlugins設置的。
    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin: this.plugins) {
            configuration.addInterceptor(plugin);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registered plugin: '" + plugin + "'");
            }
        }
    }
    ...解析xml配置(通過反射創(chuàng)建攔截器對象)
    if (xmlConfigBuilder != null) {
        try {
            xmlConfigBuilder.parse();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'");
            }
        } catch(Exception ex) {
            throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    return this.sqlSessionFactoryBuilder.build(configuration);
}

最終會執(zhí)行到:

private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child: parent.getChildren()) {
            String interceptor = child.getStringAttribute("interceptor");
            Properties properties = child.getChildrenAsProperties();
            //反射創(chuàng)建mybatis的插件。
            Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
            interceptorInstance.setProperties(properties);
            configuration.addInterceptor(interceptorInstance);
        }
    }
}

SpringBoot 自定義Mybatis攔截器

開發(fā)過程中經(jīng)常回需要對要執(zhí)行的sql加以自定義處理,比如分頁,計數(shù)等。通過 MyBatis 提供的強大機制,使用插件是非常簡單的,只需實現(xiàn) Interceptor 接口,并指定想要攔截的方法簽名即可。

@Intercepts({@Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class})})
public class MyPageInterceptor implements Interceptor {
    private static final Logger logger= LoggerFactory.getLogger(MyPageInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        logger.warn(invocation.toString());
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o,this);
    }
    @Override
    public void setProperties(Properties properties) {
        logger.warn(properties.toString());
    }
}

我的配置

mybatis:
  type-aliases-package: me.zingon.pagehelper.model
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
    default-fetch-size: 100
    default-statement-timeout: 30

在springboot中要給mybatis加上這個攔截器,有三種方法,前兩種方法在啟動項目時不會自動調用自定義攔截器的setProperties方法。

第一種

直接給自定義攔截器添加一個@Component注解,當調用sql時結果如下,可以看到攔截器生效了,但是啟動時候并沒有自動調用setProperties方法。

第二種

在配置類里添加攔截器,這種方法結果同上,也不會自動調用setProperties方法。

@Configuration
public class MybatisConfig {
    @Bean
    ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.addInterceptor(new MyPageInterceptor());
            }
        };
    }
}

第三種

這種方法就是跟以前的配置方法類似,在yml配置文件中指定mybatis的xml配置文件,注意config-location屬性和configuration屬性不能同時指定

mybatis:
  config-location: classpath:mybatis.xml
  type-aliases-package: me.zingon.pagehelper.model
  mapper-locations: classpath:mapper/*.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="me.zingon.pacargle.model"/>
    </typeAliases>
    <plugins>
        <plugin interceptor="me.zingon.pagehelper.interceptor.MyPageInterceptor"> 
            <property name="dialect" value="oracle"/>
        </plugin>
    </plugins>
</configuration>

可以看到,在啟動項目的時候setProperties被自動調用了

前兩種方法可以在初始化自定義攔截器的時候通過 @Value 注解直接初始化需要的參數(shù)。

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

相關文章

  • Python自定義計算時間過濾器實現(xiàn)過程解析

    Python自定義計算時間過濾器實現(xiàn)過程解析

    這篇文章主要介紹了Python自定義計算時間過濾器實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • MyBatis連接池的深入和動態(tài)SQL詳解

    MyBatis連接池的深入和動態(tài)SQL詳解

    這篇文章主要介紹了MyBatis連接池的深入和動態(tài)SQL詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • java郵件發(fā)送簡單實現(xiàn)代碼

    java郵件發(fā)送簡單實現(xiàn)代碼

    這篇文章主要為大家詳細介紹了java郵件發(fā)送簡單實現(xiàn)代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • Lombok插件的安裝與簡單使用步驟

    Lombok插件的安裝與簡單使用步驟

    這篇文章主要介紹了Lombok插件的安裝與簡單使用步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • Springboot jar文件如何打包zip在linux環(huán)境運行

    Springboot jar文件如何打包zip在linux環(huán)境運行

    這篇文章主要介紹了Springboot jar文件如何打包zip在linux環(huán)境運行,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • Java日期與時間類原理解析

    Java日期與時間類原理解析

    這篇文章主要介紹了Java日期與時間類原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • SpringBoot個性化配置的方法步驟

    SpringBoot個性化配置的方法步驟

    這篇文章主要介紹了SpringBoot個性化配置的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02
  • Windows 下安裝配置 Eclipse詳細教程

    Windows 下安裝配置 Eclipse詳細教程

    Eclipse是一款非常優(yōu)秀的開源IDE,非常適合Java開發(fā),由于支持插件技術,受到了越來越多的開發(fā)者的歡迎。配合眾多令人眼花繚亂的插件,完全可以滿足從企業(yè)級Java應用到手機終端Java游戲的開發(fā)。本文將帶您手把手步入Eclipse的廣闊天地
    2016-09-09
  • spring boot openfeign從此和httpClient說再見詳析

    spring boot openfeign從此和httpClient說再見詳析

    這篇文章主要給大家介紹了關于spring boot openfeign從此和httpClient說再見的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧
    2018-06-06
  • java實現(xiàn)科研信息管理系統(tǒng)

    java實現(xiàn)科研信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了java科研信息管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02

最新評論