SpringBoot 自定义一个Starter

1 创建一个自定义Starter项目

image20220515160038568

CustomConfig

@Configuration
@EnableConfigurationProperties(value = CustomProperties.class) // 使配置类生效
@ConditionalOnProperty(prefix = "mmw.config", name = "enable", havingValue = "true") // 自动装配条件
public class CustomConfig {

    @Resource
    private CustomProperties customProperties;

    @Bean
    public ConfigService defaultCustomConfig() {
        return new ConfigService(customProperties.getAge(), customProperties.getName(), customProperties.getInfo());

    }
}

CustomProperties

@ConfigurationProperties(prefix = "mmw.config")
public class CustomProperties {
    private Integer age;
    private String name;
    private String info;
    // getter/setter
}

ConfigService

public class ConfigService {
    private Integer age;
    private String name;
    private String info;
    public ConfigService(Integer age, String name, String info) {
        this.age = age;
        this.name = name;
        this.info = info;
    }
    public String showConfig() {
        return "ConfigService{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", info='" + info + '\'' +
                '}';
    }
}

META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.mmw.demo.config.CustomConfig

2 创建一个测试springBoot项目

image20220515161006770

application.yml

mmw:
    config:
        enable: true
        age: 26
        name: 'my custom starter'
        info: 'custom web info...'
server:
    port: 8081

spring:
    application:
        name: customStarterTestDemo

TestController

@RestController
public class TestController {
    @Resource
    private ConfigService configService;

    @GetMapping("/test")
    public String test() {
        return configService.showConfig();
    }
}

3 测试自动装配

image20220515161241855


版权声明:本文为Tomorrow_MMW原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。