1.创建一个 空项目 xxx-spring-boot-starter 作为场景启动器,方便别人引用

2. 创建 xxx-spring-boot-autoconfigure:包含自动配置类、属性类、核心服务等

3.注册自动配置(Spring Boot 2.7+ / 3.x)

在 resources 目录下创建:
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

文件内容为自动配置类的全限定名,一行一个,例如:

com.example.starter.autoconfigure.GreeterAutoConfiguration

自动配置类
自动配置类是 Starter 的灵魂。它使用条件注解,确保仅在特定条件下生效。
 

import org.springframework.boot.autoconfigure.AutoConfiguration;
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;

@AutoConfiguration     // Spring Boot 2.7+ 引入,等价于 @Configuration 且有自动配置语义
@EnableConfigurationProperties(GreeterProperties.class)
@ConditionalOnClass(GreeterService.class)     // 当类路径中存在该类时才生效
@ConditionalOnProperty(prefix = "greeter", name = "enabled", havingValue = "true", matchIfMissing = true)
public class GreeterAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public GreeterService greeterService(GreeterProperties properties) {
        return new GreeterService(properties);
    }
}

核心服务类
核心的业务逻辑放在这里
 

public class GreeterService {
    private final GreeterProperties properties;

    public GreeterService(GreeterProperties properties) {
        this.properties = properties;
    }

    public String greet(String name) {
        return properties.getPrefix() + " " + name + properties.getSuffix();
    }
}

属性配置类
配置核心服务类需要的属性名称

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

@ConfigurationProperties(prefix = "greeter")
public class GreeterProperties {
    /**
     * 问候语前缀,默认为 "Hello"
     */
    private String prefix = "Hello";

    /**
     * 问候语后缀,默认为 "!"
     */
    private String suffix = "!";

    // getter / setter 略
}

更多推荐