打开ebatis源码发现已经为我们集成好了springboot,可以开箱即用。接下来我们去了解下ebatis是怎样自行封装starter。<br /> 找到ebatis-spring-boot-autoconfigure模块下,META-INF/spring.factories文件里可以找到ebatis自动装配的配置文件,打开后可以发现一行配置com.ymm.ebatis.spring.boot.autoconfigure.EbatisAutoConfiguration,该类既是自定义的自动配置关键文件了,在该类中发现两个特定的类EbatisProperties和EsMapperProxyFactory:<br /> EbatisProperties中定义了连接ES集群的方式,为了保证高ES集群的高可用,同时支持对集群的负载均衡,ebatis没有直接使用elasticsearch提供的RestClient和RestHighLevelClient接口来访问集群,而是抽象出一个Cluster。一个Cluster代表一个ES集群,如果系统需要连接多个集群,则通过ClusterRouter和ClusterLoadBalancer来实现,多集群的路由和负载均衡。Cluster代表一个ES集群实例,ebatis内建了两个实现:SimpleCluster,FixWeightedCluster和SimpleFederalCluster。 SimpleCluster和FixedWeightedCluster的区别在于,后者是带固定权值的值,在对集群做负载均衡的时候,可以通过权值来控制负载的比例。SimpleFederalCluster的特殊地方在于,在一批集群上做批量操作,同步一批集群,一般用于一批集群数据的增删改,不适用于查。<br /> EsMapperProxyFactory加载定义的Mapper对象,创建Mapper对象,需要先定义Mapper接口,所有的Mapper都需要加上@Mapper或@EasyMapper注解,然后通过MapperProxyFactory来创建接口的代理。<br /> 那么ebatis是怎么实现springboot自动装配的呢?走进入口类,入口类有一个main方法,这个方法其实就是一个标准的Java应用的入口方法,一般在main方法中使用SpringApplication.run()来启动整个应用。值得注意的是,这个入口类要使用@SpringBootApplication注解声明,它是SpringBoot的核心注解。
@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class})})public @interface SpringBootApplication {@AliasFor(annotation = EnableAutoConfiguration.class)Class<?>[] exclude() default {};
这个注解里面最重要的就是@EnableAutoConfiguration,再点进去可以看到,在@EnableAutoConfiguration注解内使用到了@import注解来完成导入配置的功能,而EnableAutoConfigurationImportSelector内部则是使用了SpringFactoriesLoader.loadFactoryNames方法进行扫描具有META-INF/spring.factories文件的jar包。
//加载spring.factories实现protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());Assert.notEmpty(configurations,"No auto configuration classes found in META-INF/spring.factories. If you "+ "are using a custom packaging, make sure that file is correct.");return configurations;}
任何一个springboot应用,都会引入spring-boot-autoconfigure,而spring.factories文件就在该包下面。spring.factories文件是Key=Value形式,多个Value时使用,隔开,该文件中定义了关于初始化,监听器等信息,而真正使自动配置生效的key是org.springframework.boot.autoconfigure.EnableAutoConfiguration。
