源码地址: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);
}
}