学习笔记052——Spring Boot 自定义 Starter

Spring Boot 自定义 Starter

Spring Boot Starter 启动器自动装载 bean 。

把一个完整的项目(框架)自动组装到我们的项目中

1、自定义一个要装载的项目

2、创建属性读取类 ServiceProperties

package com.htl.properties;

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

@Data
@ConfigurationProperties(prefix = "htl.service")
public class ServiceProperties {
    private String prefix;
    private String suffix;
}

3、创建 Service

package com.htl.service;

public class Service {
    private String prefix;
    private String suffix;

    public Service(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public String doService(String value){
        return this.prefix + value + this.prefix;
    }

}

4、创建自动配置类 AutoConfigration

package com.htl.configuration;

import com.htl.properties.ServiceProperties;
import com.htl.service.Service;
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.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(Service.class)
@EnableConfigurationProperties(ServiceProperties.class)
public class AutoConfiguration {

    @Autowired
    private ServiceProperties serviceProperties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(
            prefix = "htl.service",
            value = "enable",
            havingValue = "true"
    )
    public Service service(){
        return new Service(serviceProperties.getPrefix(),
                serviceProperties.getSuffix());
    }

}

5、创建 spring 工程文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.htl.configuration.AutoConfiguration

6、将项目打成 jar 包

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

7、jar 打包到本地仓库

mvn install:install-file -DgroupId=com.htl-DartifactId=mystarter002 -Dversion=1.0.0 -Dpackaging=jar -Dfile=D:\WorkSpace\IdeaProjects\mystarter002\out\artifacts\mystarter002_jar\mystarter002.jar

8、配置application.yml

htl:
  service:
    prefix: 123
    suffix: abc
    enable: true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值