手写一个简单的SpringBoot-starter

starter会把所有用到的依赖都给包含进来,避免了开发者自己去引入依赖所带来的麻烦。 虽然不同的starter实现起来各有差异,但是他们基本上都会使用到两个相同的内容:ConfigurationProperties和AutoConfiguration。

在这里插入图片描述

1.Starters are a set of convenient dependency descriptors that
2.you can include in your application.

Starters 是一组可以让你很方便在应用增加的依赖关系描述符的集合。或者可以这样理解,平时我们开发的时候很多情况下都会有一个模块依赖另一个模块,这个时候我们一般都是采用 maven 的模块依赖,进行模块的依赖,但是这种情况下我们完全可以采用 Starter 的方式,将需要被依赖的模块用 Starter 的方式去开发,最后直接引入一个 Starter 也可以达到这样的效果。

命名规则

1.Do not start your module names with spring-boot . Let’s assume that
2.you are creating a starter for “acme”, name the auto-configure module
3.acme-spring-boot-autoconfigure and the starter acme-spring-boot-starter.
4.If you only have one module combining the two, use acme-spring-boot-starter.

由于 SpringBoot 官方本身就会提供很多 Starter,为了区别哪些 Starter 是官方,哪些是私人的或者第三方的,所以 SpringBoot 官方提出,第三方在建立自己的 Starter 的时候命名规则统一用xxx-spring-boot-starter
,而官方提供的 Starter 统一命名方式为spring-boot-starter-xxx

举例

假设我们现在有一个需求是将对象转换成 JSON,并在字符串前面加上一个名称,前轴我们支持通过配置文件配置的方式。

1.我们先创建一个 Starter,名字叫myjson-spring-boot-starter,并加入自动装配和 fastjson 的依赖,如下

在这里插入图片描述

2.然后我们创建一个 Service,并增加一个public String objToJson(Object object)方法,直接调用fastjson 的方法
package com.ryan.service;

import com.alibaba.fastjson.JSON;
/**
 * @author 沈道远
 * @date 2020-12-09 14:17
 */
public class MyJsonService {
    private String name;

    /**
     * 使用 fastjson 将对象转换为 json 字符串输出
     *
     * @param object 传入的对象
     * @return 输出的字符串
     */
    public String objToJson(Object object) {
        return getName() + JSON.toJSONString(object);
    }

    public String getName() {
        return name;
    }

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

}

3.编写配置类 ,创建一个ConfigurationProperties用于保存你的配置信息
package com.ryan.config;

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

/**
 * @author 沈道远
 * @date 2020-12-09 14:19
 */
@ConfigurationProperties(prefix = "ziyou.json")
public class MyJsonProperties {

    public static final String DEFAULT_NAME = "ziyou";

    private String name = DEFAULT_NAME;

    public String getName() {
        return name;
    }

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

    }
}
4.创建自动化配置类 ,创建一个AutoConfiguration,引用定义好的配置信息;在AutoConfiguration中实现所有starter应该完成的操作,并且把这个类加入spring.factories配置文件中进行声明
package com.ryan.config;

import com.ryan.service.MyJsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 夏泽林
 * @date 2020-12-09 14:21
 */

@Configuration
@ConditionalOnClass({MyJsonService.class})
@EnableConfigurationProperties(MyJsonProperties.class)
public class MyJsonAutoConfiguration {

    /**
     * 注入属性类
     */
    @Autowired
    private MyJsonProperties myJsonProperties;

    /**
     * 当当前上下文中没有 MyJsonService 类时创建类
     *
     * @return 返回创建的实例
     */
    @Bean
    @ConditionalOnMissingBean(MyJsonService.class)
    public MyJsonService myJsonService() {
        MyJsonService myJsonService = new MyJsonService();
        myJsonService.setName(myJsonProperties.getName());
        return myJsonService;
    }

}

5.然后我们再创建 resource/META-INF/spring.factories 文件,增加如下内容,将自动装配的类配置上
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ryan.config.MyJsonAutoConfiguration
6.然后我们通过运行mvn install命令,将这个项目打包成 jar 部署到本地仓库中,提供让另一个服务调用。
7.创建一个新的 SpringBoot web 项目test-myjson-spring-boot-starter,提供一个接口去访问。
package com.example.demo.controller;

import com.example.demo.entity.Persion;
import com.ryan.service.MyJsonService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 沈道远
 * @date 2020-12-04 14:27
 */
@RestController
public class UserController {

    @Autowired
    private MyJsonService myJsonService;

    @RequestMapping(value = "/tojson")
    public String getStr() {
        Persion user = new Persion();
        user.setName("dsfsf");
        user.setAge(18);
        return myJsonService.objToJson(user);
    }
}
8.application.yml中配置。
server:
  port: 8080

ziyou:
  json:
    name: java-geek-teck
9.pom.xml 中配置刚刚编写的 Starter。
<?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.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.ryan</groupId>
            <artifactId>myjson-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

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

</project>

11.启动测试项目,打开浏览器访问接口可以看到如下效果。

在这里插入图片描述
从结果中我们可以看到在 Starter 中定义的MyJsonService已经被成功的调用和执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值