手把手 自定義{name}-spring-boot-starter組件

前記

想必大家都用過spring boot的starter組件,開箱即用,最近對此做了學習,整理筆記記錄如下

準備

創建一個maven項目,定義要封裝的功能組件,然後通過spring的自動裝配機制和條件裝備機制,讓封裝的組件能夠被開箱即用

項目

demo的功能是創建解析類,實現將對象格式化輸出字符串;針對項目中引入的類,條件選擇加載解析類

功能定義

依賴的包

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.1.6.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.56</version>
      <optional>true</optional>
    </dependency>
    <!--spring默認使用yml中的配置,但有時候要用傳統的xml或properties配置,就需要使用spring-boot-configuration-processor了-->

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <version>2.1.6.RELEASE</version>
      <optional>true</optional>
    </dependency>

接口定義

public interface FormatProcessor {
    <T> String format(T obj);
}

實現類JsonFormatProcessor

public class JsonFormatProcessor implements FormatProcessor{
    @Override
    public <T> String format(T obj) {
        return "JsonFormat"+ JSON.toJSONString(obj);
    }
}

實現類StringFormatProcessor

public class StringFormatProcessor implements FormatProcessor{
    @Override
    public <T> String format(T obj) {
        return "StringFormat"+Objects.toString(obj);
    }
}

調用類

public class FormatTemplate {
    private FormatProcessor formatProcessor;
    private HelloProperties helloProperties;
    public FormatTemplate(FormatProcessor formatProcessor,HelloProperties helloProperties) {
        this.formatProcessor = formatProcessor;
        this.helloProperties = helloProperties;
    }

    public <T> String doFormat(T obj){
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("DO Format:").append("<br/>");
        stringBuilder.append("HelloProperties:").append(formatProcessor.format(helloProperties.getInfo())).append("<br/>");
        stringBuilder.append("Obj format result:").append(formatProcessor.format(obj)).append("<br/>");
        return stringBuilder.toString();
    }
}

現在功能就已經封裝好了

添加spring管理

@Configuration
public class FormatAutoConfiguration {

    @Bean
    @Primary
    @ConditionalOnMissingClass("com.alibaba.fastjson.JSON")
    public FormatProcessor stringFormat(){
        return  new StringFormatProcessor();
    }

    @Bean
    @ConditionalOnClass(name= "com.alibaba.fastjson.JSON")
    public  FormatProcessor jsonFormat(){
        return new JsonFormatProcessor();
    }
}
@ConfigurationProperties(prefix = HelloProperties.DEFAULT_PREFIX)
public class HelloProperties {
    public static final String DEFAULT_PREFIX="xuedy.hello.format";
    private Map<String,Object> info;


    public Map<String, Object> getInfo() {
        return info;
    }

    public void setInfo(Map<String, Object> info) {
        this.info = info;
    }
}
@Import(FormatAutoConfiguration.class)
@EnableConfigurationProperties(HelloProperties.class)
@Configuration
public class HelloAutoConfiguration {
    @Bean
    public FormatTemplate formatTemplate(FormatProcessor formatProcessor,HelloProperties helloProperties){
        return new FormatTemplate(formatProcessor,helloProperties);

    }
}

src/main/resources/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.example.autoconfiguration.HelloAutoConfiguration

maven install 添加到本地倉庫
此時所有工作已完成

測試

用一個spring boot 項目來測試這個這個starter 組件是否可以達到預期結果

pom.xml

<dependency>
    <groupId>org.example</groupId>
    <artifactId>format-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.56</version>
    <optional>true</optional>
</dependency>

測試類

RestController
public class TestController {
//非starter 組件時,Bean沒有被託管的調用,需要手動
//    public static void main( String[] args )
//    {
//       Map hashMap=new HashMap();
//       hashMap.put("name","123");
//       StringFormatProcessor processor = new StringFormatProcessor();
//        FormatTemplate formatTemplate=new FormatTemplate(processor);
//        System.out.println(formatTemplate.doFormat(hashMap));
//    }

//starter 組件,Bean自動託管,有項目環境決定加載哪個實體類 ,取決於json包的引用
    @Autowired
    FormatTemplate formatTemplate;

    @GetMapping("/test")
    public String testFormat(){
        Map hashMap=new HashMap();
        hashMap.put("name","123");
       return formatTemplate.doFormat(hashMap);
    }
}

自定義配置參數加載

xuedy.hello.format.info.phone=1590****654
xuedy.hello.format.info.age=18
xuedy.hello.format.info.city=B.J

測試

訪問接口http://localhost:8080/test

註釋掉fastjson 的依賴,會加載StringFormatProcessor解析

解析結果如下

DO Format:
HelloProperties: StringFormat  {phone=15901390654, age=18, city=B.J}
Obj format result:StringFormat{name=123}

添加fastjson 的依賴,會加載JsonFormatProcessor解析

解析結果如下

DO Format:
HelloProperties: JsonFormat {"phone":"15901390654","age":"18","city":"B.J"}
Obj format result:JsonFormat {"name":"123"}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章