不积跬步,无以至千里; 不积小流,无以成江海。

  自定义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就行了。

posted on 2018-12-03 14:45  去流浪,去换成长  阅读(157)  评论(0)    收藏  举报