栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

四种方式使通用SDK中自定义Mybatis Plugin生效?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

四种方式使通用SDK中自定义Mybatis Plugin生效?

一、官方做法

可以在官方文档看到,对于项目上引入自定义的Mybatis Plugin(文中以ExamplePlugin为例)通常采用在mybatis配置文件(mybatis-config.xml)中引入标签的方式处理;


  
    
  

我们可以注意到在标签中有一个标签,从命名来看,它是用来引入自定义属性的!

那么具体是怎么用的呢?

1> 大家都知道自定义Mybatis Plugin时需要实现Interceptor接口,在Interceptor接口中有一个抽象方法void setProperties(Properties properties);其用来接收配置文件中的property参数,即上面的标签中的内容。换言之,只有采用XML配置文件的方式注入Mybatis Plugin,setProperties()方法才有实际使用意义,否则是不会进入的。

package org.apache.ibatis.plugin;

import java.util.Properties;


public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  Object plugin(Object target);

  void setProperties(Properties properties);

}

因此,如果我们采用其他的方式注入Mybatis Plugin,不要尝试在setProperties()方法中对自定义的Mybatis Plugin中的一些属性赋值,那是无用的(亲测哦)。

如果我要自己写一个组件 / SDK,不好用这种方式;业务上假如也有自己的mybatis配置文件,它再一指定,好耶,要找我了(为什么你的MyBatis Plugin没生效!!!)。

二、@Component

直接利用Spring的扫包机制,将标注了@Component派生类注解的类直接扫描加载到Spring;

@Configuration
public class ExamplePlugin implements Interceptor {
    ....
}

**注意:**若使用当前方式,注意Spring的扫包路径;如果是写了一个SDK给其他业务模块引用,记得让他们在启动类添加一下扫描包路径,或者通过@import注解引入MybatisInterceptor类;

@ComponentScan({"com.example.xxx","org.mybatis.example.xxx"})
@import(ExamplePlugin.class)
三、@Configuration + @Bean

自定义的Mybatis Plugin仅作为一个普通的类,具体何时引入到Spring容器,由相应的配置类决定;例如:

@Configuration
public class MyBatisConfig {

    
    @Bean
    public Interceptor getInterceptor() {
        return new MybatisInterceptor();
    }
}

使用的注意点和二、@Component一样,区别在于这里要引入的是配置类MyBatisConfig;

推荐使用这种方式;为什么呢?

我喜欢,怎么样啊!

四、用到SpringBoot机制的@Configuration + @Bean

这个其实和三、@Configuration + @Bean差不多,区别在于三、是直接new一个MyBatisInterceptor,这里是通过mybatis-spring-boot-autoconfigure SpringBoot自动装配机制添加一个拦截器;
例如:

@Configuration
public class MyBatisConfig {

    @Bean
    ConfigurationCustomizer configurationCustomizer() {

        MybatisInterceptor statementInterceptor = new MybatisInterceptor();

        return (configuration) -> configuration.addInterceptor(statementInterceptor);
    }
}

不过首先要在pom中引入:


    org.mybatis.spring.boot
    mybatis-spring-boot-autoconfigure
    2.2.0

因为要额外引入mybatis-spring-boot-autoconfigure,所以在SDK中最好使用第三种方式@Configuration + @Bean;

软件设计上永远没有最好,只有更合适。具体使用那种方式大家灵活选择;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781619.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号