SpringBoot自定义starter

本文章记录了SpringBoot如何自定义starter

一、首先创建启动器

1、创建一个空的工程

2、建议对应的module,选择maven来进行创建

定义对应的GroupId 和ArtifactId

定义对应的Module名称


 

二、接下来创建springboot的初始化器,创建自动配置的相关的东西

1、新建module,选择spring initializr来进行创建

创建后不引入任何模块点击next,创建生成

 

三、启动器中引入自动配置模块

删除自动配置文件

删除配置器多余的依赖,只留下starter

四、创建自动配置类对应的Properties类


@ConfigurationProperties(prefix = "training.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;
    }
}

五、自定义测试的服务类

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();
    }
}

六、定义自动配置类


@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {

    @Autowired
    HelloProperties helloProperties;

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

编写完后需要在配置模块中创建spring.factories并把自动配置类配置到配置文件中

META-INF/spring.factories

七、打包

分别将配置类和启动类install,先执行配置类的install,然后执行启动类的install,打包到本地

八、编写测试工程,在工程中引入依赖

<dependency>
            <groupId>com.training.starter</groupId>
            <artifactId>training-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

编写controller进行测试

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String Hello(){
        return helloService.sayHello("AA");

    }
}

在配置文件中添加外置属性

training.hello.prefix="BB1"
training.hello.suffix="Hello Word"

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值