手寫 spring-boot-starter 實現自定義類的格式化

1、定義格式化接口規範【FormatProcessor 】

package com.tiger.starter.format;

/**
 * 格式化接口規範
 */
public interface FormatProcessor {

    //定義一個格式化的方法
    <T> String format(T obj);
}

2.1、編寫 json 格式處理器類【JsonFormatProcessor 】,實現格式化接口 FormatProcessor 

package com.tiger.starter.format;

import com.alibaba.fastjson.JSON;

/**
 * 編寫 json 格式處理器
 */
public class JsonFormatProcessor implements FormatProcessor {

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

2.2、編寫 json 格式處理器類【StringFormatProcessor 】,實現格式化接口 FormatProcessor 

package com.tiger.starter.format;

import java.util.Objects;

/**
 * 編寫 String 格式處理器
 */
public class StringFormatProcessor implements FormatProcessor {

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

3、編寫 關聯配置文件 類【TigerProperties 】,如沒用到可省略

package com.tiger.starter.configuration;


import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Map;

/**
 * 關聯配置文件類
 */
@ConfigurationProperties(prefix = TigerProperties.TIGER_FORMAT_PREFIX)
public class TigerProperties {

    public static final String              TIGER_FORMAT_PREFIX = "tiger.format";
    private             Map<String, Object> info;
    private             String              name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

    public void setInfo(Map<String, Object> info) {
        this.info = info;
    }
}

4、編寫對外的格式模板類【TigerFormatTemplate】

package com.tiger.starter;

import com.tiger.starter.configuration.TigerProperties;
import com.tiger.starter.format.FormatProcessor;

/**
 * 對外提供的格式模板類
 * 格式化模板,根據條件選擇對應的模板
 */
public class TigerFormatTemplate {
    //格式處理器
    private FormatProcessor formatProcessor;
    //配置文件屬性
    private TigerProperties tigerProperties;

    public TigerFormatTemplate(TigerProperties tigerProperties, FormatProcessor formatProcessor) {
        this.tigerProperties = tigerProperties;
        this.formatProcessor = formatProcessor;
    }

    /**
     * 根據傳入的類型,自動對其格式化
     *
     * @param obj
     * @param <T>
     * @return
     */
    public <T> String doFormat(T obj) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("====== 開始格式化 ======").append("<br/>");
        stringBuilder.append("====== 讀取配置文件信息 ======info:【").append(formatProcessor.format(tigerProperties.getInfo())).append("】");
        stringBuilder.append("--name:【").append(formatProcessor.format(tigerProperties.getName())).append("】<br/>");
        stringBuilder.append("====== 格式結果【").append(formatProcessor.format(obj)).append("】<br/>");
        return stringBuilder.toString();

    }
}

5、條件注入配置類【FormatConditionalAutoConfiguration 】

package com.tiger.starter.configuration;


import com.tiger.starter.format.FormatProcessor;
import com.tiger.starter.format.JsonFormatProcessor;
import com.tiger.starter.format.StringFormatProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 條件注入
 */
@Configuration
public class FormatConditionalAutoConfiguration {

    /**
     * 不存在【com.alibaba.fastjson.JSON】時 ,注入
     *
     * @return
     */
    @ConditionalOnMissingClass("com.alibaba.fastjson.JSON")
    @Bean
    @Primary //主要的
    public FormatProcessor stringFormat() {
        return new StringFormatProcessor();
    }

    /**
     * 存在【com.alibaba.fastjson.JSON】時注入
     *
     * @return
     */
    @ConditionalOnClass(name = "com.alibaba.fastjson.JSON")
    @Bean
    public FormatProcessor jsonFormat() {
        return new JsonFormatProcessor();
    }

}

6、編寫 Bean 配置類【TigerBeanAutoConfiguration 】

package com.tiger.starter.configuration;


import com.tiger.starter.TigerFormatTemplate;
import com.tiger.starter.format.FormatProcessor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Bean 配置類
 */
@Import(FormatConditionalAutoConfiguration.class)//導入模板配置類
@EnableConfigurationProperties(TigerProperties.class)//自動注入配置信息
@Configuration//標識是一個配置類
public class TigerBeanAutoConfiguration {

    @Bean
    public TigerFormatTemplate tigerFormatTemplate(TigerProperties tigerProperties, FormatProcessor formatProcessor) {
        return new TigerFormatTemplate(tigerProperties, formatProcessor);
    }
}

7、編寫元信息文件,SPI【src/main/resources/META-INF/spring.factories】

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.tiger.starter.configuration.TigerBeanAutoConfiguration

8、pom文件

 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.tiger.starter</groupId>
  <artifactId>format-spring-boot-starter</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>format-spring-boot-starter</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

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

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

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.56</version>
      <optional>true</optional><!--可選-->
    </dependency>

  </dependencies>

  <build>
    <finalName>format-spring-boot-starter</finalName>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.*</include>
        </includes>
      </resource>
    </resources>

    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>8</source>
          <target>8</target>
        </configuration>
      </plugin>
    </plugins>

  </build>
</project>

9、打包後,該jar包便可以被引入到其他springboot項目中使用,例如在pom文件中引入改信息

    <dependencies>
         
        <!-- 自定義starter -->
        <dependency>
            <groupId>com.tiger.starter</groupId>
            <artifactId>format-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

10、其他springboot項目配置文件中寫入配置信息【src/main/resources/application.properties】

tiger.format.info.country=中國
tiger.format.info.province=廣東
tiger.format.info.city=廣州
tiger.format.info.region=天河
tiger.format.name=hello

或者【src/main/resources/application.yml】

tiger:
  format:
    info:
      country: 中國
      province: 廣東
      city: 廣州
      region: 天河
    name: hello tiger

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章