springboot实现自己的starter

实现一个简单的对象格式化starter

新建一个maven工程,引入spring-boot-starter和json

pom.xml

<?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.david</groupId>
  <artifactId>my-spring-boot-starter</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>my-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.7</maven.compiler.source>
    <maven.compiler.target>1.7</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>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.56</version>
      <optional>true</optional>
    </dependency>
    <!-- spring默认支持yaml,如果需要支持配置文件格式properties或xml需要添加这个依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
      <version>2.1.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

定义一个接口类IFormat,并实现2个不同的类,一个字符串一个json

public interface IFormat {

    <T> String doFormat(T obj);
}

实现类

json实现类

import com.alibaba.fastjson.JSON;

public class JsonFormat implements IFormat {

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



字符串实现类

public class StringFormat implements IFormat {

    @Override
    public <T> String doFormat(T obj) {
        return "String Format:"+obj.toString();
    }
}

 创建spring配置类

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 FormatAutoConfiguration{

    @ConditionalOnMissingClass("com.alibaba.fastjson.JSON")// 当没有json这个类时会加载这个bean,并交给spring容器管理
    @Primary // 设置一个首选项,不然会提示找到2个bean
    @Bean
    public IFormat stringFormat(){
        return new StringFormat();
    }

    @ConditionalOnClass(name = "com.alibaba.fastjson.JSON")// 当有json这个类时会加载这个bean,并交给spring容器管理
    @Bean
    public IFormat jsonFormat(){
        return new JsonFormat();
    }
}

创建springboot中可以在properties自动提示的类,这样就可以动态的配置一些属性,这里只定义了一个属性

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

@ConfigurationProperties(prefix = "com.david.format")// 自动提示的配置前缀
public class FormatProperties {

    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

接着定义装配的模板

public class FormatTemplate {

    private IFormat format;

    private FormatProperties formatProperties;

    public FormatTemplate(IFormat format, FormatProperties formatProperties) {
        this.format = format;
        this.formatProperties = formatProperties;
    }

    public <T> String doFormat(T obj){

        return "properties info:"+formatProperties.getInfo()+";"+format.doFormat(obj);
    }
}

然后定义自动装配模板的配置类,spring会自动注入两个bean创建FormatTemplate并交由spring容器管理

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;

@Import(FormatAutoConfiguration.class)// 导入其他bean的配置
@EnableConfigurationProperties(FormatProperties.class)// 启用配置文件
@Configuration
public class FormatTemplateAutoConfiguration {

    @Bean
    public FormatTemplate formatTemplate(IFormat format, FormatProperties formatProperties){
        return new FormatTemplate(format,formatProperties);
    }

}

最后一步就是整个自动装配的核心了,在resources目录下创建一个META-INF文件夹,然后在META-INF文件夹下创建一个spring.factories文件,文件内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.david.FormatTemplateAutoConfiguration

springboot预留了扩展点(SPI),通过在资源路径下创建META-INF文件夹,在META-INF下创建spring.factories文件,spring启动时会扫描所有资源文件下的这个文件,并根据文件配置内容加载对应bean的信息交由spring管理,这样我们就能使用autowired的注解实现快速注入使用,starter就是根据这个原理实现的。

项目结构如下图

接着把这个项目install成jar,在创建一个新的springboot工程引用这个jar

新工程pom.xml,目前还没有依赖json的jar包

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.david</groupId>
    <artifactId>my-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>my-web</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.david.my</groupId>
            <artifactId>mycode</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.david</groupId>
            <artifactId>my-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建一个user类,user类里面有name和age属性并重写toString方法

public class User {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

创建一个controller并自动注入FormatTemplate

import com.david.FormatTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    FormatTemplate formatTemplate;

    @RequestMapping("/format")
    public String format(){
        User user = new User();
        user.setName("David");
        user.setAge(27);
        return formatTemplate.doFormat(user);
    }
}

在application.properties中输入会有自动提示

启动运行项目,目前输出会是string格式化对象,配置的属性也有输出

加上json的jar的pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.david</groupId>
    <artifactId>my-web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>my-web</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.david.my</groupId>
            <artifactId>mycode</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.david</groupId>
            <artifactId>my-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- json jar 包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

重启并访问

 

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