springboot可配置开启自定义starter

源码地址:https://gitee.com/marlon1999/springboot-learnning
编码不易,往各位记得点个star

有没有一种需求,想要一个starter给其他业务使用,但是业务有想需要的时候开启,不想使用的时候去掉,可以很方便的切换,这种可配置的starter,那就接下来认真的阅读本文章,可以帮助你很轻松的解决掉你得所有顾虑。
代码结构如下图所示:
在这里插入图片描述

根据上图新建类似的项目结构。

1 springboot-autoconfiguration模块

1.1 引入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
</dependency>

1.2 增加属性类

@Configuration
@ConfigurationProperties(prefix = "nft.server")
@Data
public class ServerProperties {

    private String name;
    private String addr;
    private Integer age;
}

1.3 增加配置类

@Configuration
@EnableConfigurationProperties(ServerProperties.class)
public class NftServerStartConfiguration {

    @Autowired
    private ServerProperties serverProperties;

    @Bean
    @ConditionalOnProperty(prefix = "nft.server",name = "enabled", havingValue = "true", matchIfMissing = false)
    public void startBoot(){
        System.out.println(this.serverProperties.getAddr());
    }
}

1.4 编写注解配置

用import将1.3编写的配置类导入到注解中,让注解管理起来

/**
 * nftserver注解开启
 * @author marlon
 * @create 2024-01-18 10:38
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(value = NftServerStartConfiguration.class)
@Documented
@Inherited
public @interface NftServer {

}

2 api-spring-boot-starter

2.1 引入autoconfiguration的依赖

<dependency>
    <groupId>com.marlon.springboot</groupId>
    <artifactId>springboot-autoconfiguration</artifactId>
    <version>1.0.0</version>
</dependency>

3 springboot-starter-test

3.1 引入starter的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.marlon.springboot</groupId>
    <artifactId>api-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

2 配置文件配置参数

nft.server.enabled 默认为false,如果不想开启就用默认值或者设置为false即可

nft:
  server:
    enabled: true
    name: marlon
    age: 22
    addr: 甘肃平凉

3 启动类上加注解@NftServer

@SpringBootApplication
@NftServer
public class AdfsDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdfsDemoApplication.class);
    }
}
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值