SpringBoot 自定义 starter

in Tech Java

导入依赖

        <!-- 提供Spring、SpringBoot的注解 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>x.x.x</version>
        </dependency>

        <!-- 可选属性提示 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>x.x.x</version>
            <optional>true</optional>
        </dependency>

定义属性类

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
// 标记属性类,可配置前缀
@ConfigurationProperties("custom")
public class CustomProperies {
    private String name;

    public String getName() {
        return name;
    }

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

定义服务类

package com.example.config;

public class NameService {
    private String name;

    public String getName() {
        return name;
    }

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

定义自动配置类

package com.example.config;

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
// 开启配置属性
@EnableConfigurationProperties(CustomProperies.class)
// 类路径上存在NameService类才加载
@ConditionalOnClass(NameService.class)
// 可配置是否生效。默认生效
@ConditionalOnProperty(prefix = "custom",value = "enabled",matchIfMissing = true)
public class CustomAutoConfiguration {
    @Autowired
    CustomProperies properies;
    @Bean
    // 当BeanFactory不存在NameService类型的Bean时,才执行该方法
    @ConditionalOnMissingBean(NameService.class)
    public NameService customConfiguration(){
        NameService customConfiguration = new NameService();
        customConfiguration.setName(properies.getName());
        return customConfiguration;
    }
}

自动配置文件

需要在 resources 建立路径 META-INF,增加文件 sping.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.CustomAutoConfiguration

可选属性提示配置文件 additional-spring-configuration-metadata.json

{"properties": [
  {
    "name": "custom.name",
    "type": "java.lang.String",
    "description": "名称."
  }
]}

最后

使用 Maven 安装命令,打包添加到本地仓库,就可以引入其他项目啦!