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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值