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

网友投稿 293 2022-12-01

四种方式使通用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;/** * @author Clinton Begin */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;

@Configurationpublic class ExamplePlugin implements Interceptor { ....}

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

@ComponentScan({"com.example.xxx","org.mybatis.example.xxx"})

@Import(ExamplePlugin.class)

三、@Configuration + @Bean

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

@Configurationpublic class MyBatisConfig { /** * mybatis plugin */ @Bean public Interceptor getInterceptor() { return new MybatisInterceptor(); }}

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

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

我喜欢,怎么样啊!

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

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

@Configurationpublic 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​​;

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java编程进阶小白也能手写HashMap代码
下一篇:初识Java基础之数据类型与运算符
相关文章

 发表评论

暂时没有评论,来抢沙发吧~