• SpringBoot自定义Starter


      自定义starter

      1、了解相关注解:

        @Configuration //标志这是一个配置类

        @ConditionalOnXXX //在指定条件成立的条件下该类才生效

        @AutoConfigureOrder //指定自动配置类的顺序

        @AutoConfigureAfter //功能同上

        @ConfigurationProperties // 结合相关XxxProperties类来绑定相关配置属性,将属性抽离到配置文件中。

        @EnableConfigurationProperties // 让XxxProperties生效,并可注入到容器中

      2、starter模式

        starter只负责依赖导入,其中不包含任何java代码。如图:

             

        自定义starter命名:xxx-spring-boot-starter如mybatis-spring-boot-starter是mybatis自己写的starter。

      3、加载

        自动配置类加载需配置:

        将需要启动就加载的自动配置类,配置在META-INF/spring.factories中,如下:

          

      定义一个简单的starter具体步骤:

        1)在一个Empty Project下创建两个Module

        

        在starter的pom中添加依赖:

        

        2)在starter-autoconfigurer中编写具体自动配置场景

        写一个service:

    public class OliverService {
    
       //包含一个properties
        OliverProperties oliverProperties;
    
        public OliverProperties getOliverProperties() {
            return oliverProperties;
        }
    
        public void setOliverProperties(OliverProperties oliverProperties) {
            this.oliverProperties = oliverProperties;
        }
    
       //业务方法
    public String helloOliver(){ return oliverProperties.getPerfix()+"-"+"oliver"+"-"+oliverProperties.getSuffix(); } }

        与配置文件关联的OliverProperties类,:

    //可在配置文件中配置其属性,只要前缀为oliver即可
    @ConfigurationProperties(prefix = "oliver") public class OliverProperties { private String perfix; private String suffix; public String getPerfix() { return perfix; } public void setPerfix(String perfix) { this.perfix = perfix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }

         自动配置类:

    @Configuration 
    @ConditionalOnWebApplication //web应用下生效
    @EnableConfigurationProperties(OliverProperties.class)//让OliverProperties生效,注入到容器中
    public class OliverAutoConfiguration {
    
    
        @Autowired
        OliverProperties oliverProperties;
    
       //将OliverService注入到容器中
        @Bean
        public OliverService oliverService(){
            OliverService oliver = new OliverService();
            oliver.setOliverProperties(oliverProperties);
            return oliver;
        }
    }

        3)建立META-INFO/spring.factories

        

    //spring.factories内容:
    org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.oliver.starter.OliverAutoConfiguration

        4)Maven install到仓库,此时就算定义完成了。在需要用的地方引入dependency就行了。

  • 相关阅读:
    20165339 预备作业3 Linux安装及学习
    20165339 学习基础和c语言基础调查
    20165339 我期望的师生关系
    2018-2019-1 20165332 《信息安全系统设计基础》第3周学习总结
    2018-2019-1 20165332 《信息安全系统设计基础》第2周学习总结
    2018-2019-1 20165332 《信息安全系统设计基础》第1周学习总结
    20165332 2017-2018-2《Java程序设计》课程总结
    20165332实验五 网络编程与安全
    20165332实验四 Android开发基础
    20165332第十周课下作业
  • 原文地址:https://www.cnblogs.com/oliverBolg/p/10058401.html
Copyright © 2020-2023  润新知