自定义 Spring Boot starter

该文介绍如何创建一个自定义的SpringBootStarter,它读取配置文件中的`prefix`和`suffix`,生成一个`Service`对象,该对象能对输入参数进行处理。然后将这个Starter打包成jar,导入到Maven本地仓库,并在其他SpringBoot项目中作为依赖使用,实现自动装配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义 Spring Boot starter

写一个简单的工程,当作自定义的框架

package com.southwind.properties;

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

@Data
@ConfigurationProperties(
        prefix = "southwind.service"
)
public class ServiceProperties {
    private String prefix;
    private String suffix;
}
package com.southwind.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.suffix;
    }
}
package com.southwind.config;

import com.southwind.properties.ServiceProperties;
import com.southwind.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 AutoConfigure {

    @Autowired
    private ServiceProperties serviceProperties;

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

spring.factories

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.southwind.config.AutoConfigure

打成 jar 包

将 jar 导入 Maven 本地仓库

mvn install:install-file -DgroupId=com.southwind -DartifactId=003_starter -Dversion=1.0 -Dpackaging=jar -Dfile=D:\WorkSpace\IdeaProjects\003_myspringbootstarter\out\artifacts\003_myspringbootstarter_jar\003_myspringbootstarter.jar

Spring Boot 引用

<dependency>
    <groupId>com.southwind</groupId>
    <artifactId>003_starter</artifactId>
    <version>1.0</version>
</dependency>

1、创建一个工程 starter工具(要导入 Spring Boot 工程中),读取 application.yml 中的配置信息(prefix,suffix),生成一个 service 对象,业务是对传入的参数进行处理:prefix+参数+suffix,返回。

2、将 starter 工具导入 Spring Boot 工程中,直接使用(自动装配)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值