SpringBoot-自定义Starter启动器

想详细了解SpringBoot的自动配置原理,可移步:

SpringBoot自动配置原理详解

手绘图,方便梳理整个过程

在这里插入图片描述

1、新建springboot模块-(gao-springboot-starter-autoconfigure)

结构如下:

img

新建HelloService自定义服务:

package com.gao;

/**
 * @description:
 * @author: XiaoGao
 * @time: 2021/10/10 14:14
 */
public class HelloService {
    HelloProperties helloProperties;
    public HelloProperties getHelloProperties(){
        return helloProperties;
    }
    public void setHelloProperties(HelloProperties helloProperties){
        this.helloProperties=helloProperties;
    }
    public String sayHello(String name){
        return helloProperties.getPrefix()+name+helloProperties.getSuffix();
    }
}

新建HelloProperties配置类:

注意这个注解@ConfigurationProperties

package com.gao;

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

/**
 * @description:
 * @author: XiaoGao
 * @time: 2021/10/10 14:14
 */
@ConfigurationProperties(prefix = "com.hello")
public class HelloProperties {
    private String prefix;
    private String suffix;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

新建自动配置类HelloServiceAutoConfiguration:

/**
 * @description:
 * @author: XiaoGao
 * @time: 2021/10/10 14:17
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;

    @Bean
    public HelloService helloService(){
        HelloService helloService=new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

在resources下编写META-INF\spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.gao.HelloServiceAutoConfiguration

完成后将其安装到maven仓库:

img

二、新建一个maven项目,作为启动器

img

在pom.xml导入gao-springboot-starter-autoconfigure依赖:

<dependency>
    <groupId>org.example</groupId>
    <artifactId>gao-spring-boot-starter-autoconfigure</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

将启动器导入到maven中:

img

这样一来,启动器就自定义成功了,接下来进行测试。

三、测试自定义启动器

  1. 创建maven项目

img

  1. 创建controller类
@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

    @RequestMapping("/hello")
    public String hello(){
        return helloService.sayHello("小高");
    }
}
  1. 配置prefix与suffix:
    在这里插入图片描述

  2. 浏览器访问img

成功,哈哈~~~


版权声明:本文为alpha_xia原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。