1. 打开ebatis源码发现已经为我们集成好了springboot,可以开箱即用。接下来我们去了解下ebatis是怎样自行封装starter。<br /> 找到ebatis-spring-boot-autoconfigure模块下,META-INF/spring.factories文件里可以找到ebatis自动装配的配置文件,打开后可以发现一行配置com.ymm.ebatis.spring.boot.autoconfigure.EbatisAutoConfiguration,该类既是自定义的自动配置关键文件了,在该类中发现两个特定的类EbatisPropertiesEsMapperProxyFactory:<br /> EbatisProperties中定义了连接ES集群的方式,为了保证高ES集群的高可用,同时支持对集群的负载均衡,ebatis没有直接使用elasticsearch提供的RestClientRestHighLevelClient接口来访问集群,而是抽象出一个Cluster。一个Cluster代表一个ES集群,如果系统需要连接多个集群,则通过ClusterRouterClusterLoadBalancer来实现,多集群的路由和负载均衡。Cluster代表一个ES集群实例,ebatis内建了两个实现:SimpleClusterFixWeightedClusterSimpleFederalCluster SimpleClusterFixedWeightedCluster的区别在于,后者是带固定权值的值,在对集群做负载均衡的时候,可以通过权值来控制负载的比例。SimpleFederalCluster的特殊地方在于,在一批集群上做批量操作,同步一批集群,一般用于一批集群数据的增删改,不适用于查。<br /> EsMapperProxyFactory加载定义的Mapper对象,创建Mapper对象,需要先定义Mapper接口,所有的Mapper都需要加上@Mapper@EasyMapper注解,然后通过MapperProxyFactory来创建接口的代理。<br /> 那么ebatis是怎么实现springboot自动装配的呢?走进入口类,入口类有一个main方法,这个方法其实就是一个标准的Java应用的入口方法,一般在main方法中使用SpringApplication.run()来启动整个应用。值得注意的是,这个入口类要使用@SpringBootApplication注解声明,它是SpringBoot的核心注解。
    1. @Target({ElementType.TYPE})
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Inherited
    5. @SpringBootConfiguration
    6. @EnableAutoConfiguration
    7. @ComponentScan(
    8. excludeFilters = {@Filter(
    9. type = FilterType.CUSTOM,
    10. classes = {TypeExcludeFilter.class}
    11. ), @Filter(
    12. type = FilterType.CUSTOM,
    13. classes = {AutoConfigurationExcludeFilter.class}
    14. )}
    15. )
    16. public @interface SpringBootApplication {
    17. @AliasFor(
    18. annotation = EnableAutoConfiguration.class
    19. )
    20. Class<?>[] exclude() default {};

    这个注解里面最重要的就是@EnableAutoConfiguration,再点进去可以看到,在@EnableAutoConfiguration注解内使用到了@import注解来完成导入配置的功能,而EnableAutoConfigurationImportSelector内部则是使用了SpringFactoriesLoader.loadFactoryNames方法进行扫描具有META-INF/spring.factories文件的jar包。

    1. //加载spring.factories实现
    2. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
    3. AnnotationAttributes attributes) {
    4. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
    5. getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
    6. Assert.notEmpty(configurations,
    7. "No auto configuration classes found in META-INF/spring.factories. If you "
    8. + "are using a custom packaging, make sure that file is correct.");
    9. return configurations;
    10. }
    1. 任何一个springboot应用,都会引入spring-boot-autoconfigure,而spring.factories文件就在该包下面。spring.factories文件是Key=Value形式,多个Value时使用,隔开,该文件中定义了关于初始化,监听器等信息,而真正使自动配置生效的keyorg.springframework.boot.autoconfigure.EnableAutoConfiguration