自定义SpringBoot Starter

自定义SpringBoot Starter

  1. 引入项目的配置依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>
  1. 创建xxxService类,完成相关的操作逻辑
  DemoService.java

@Data
public class DemoService{

    private String str1;

    private String str2;
  1. 定义xxxProperties类,属性配置类,完成属性配置相关的操作,比如设置属性前缀,用于在application.properties中配置
//指定项目在属性文件中配置的前缀为str,即可以在属性文件中通过 str.str1=springboot,就可以改变属性类字段 str1 的值了
@SuppressWarnings("ConfigurationProperties")
@ConfigurationProperties(prefix = "str")
@Data
public class DemoProperties {

    public static final String DEFAULT_STR1 = "SpringBoot ";

    public static final String DEFAULT_STR2 = "Starter";

    private String str1 = DEFAULT_STR1;

    private String str2 = DEFAULT_STR2;
   
   }
 
  1. 定义xxxAutoConfiguration类,自动配置类,用于完成Bean创建等工作
// 定义 java 配置类
@Configuration
//引入DemoService
@ConditionalOnClass({DemoService.class})
// 将 application.properties 的相关的属性字段与该类一一对应,并生成 Bean
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {

    // 注入属性类
    @Autowired
    private DemoProperties demoProperties;

    @Bean
    // 当容器没有这个 Bean 的时候才创建这个 Bean
    @ConditionalOnMissingBean(DemoService.class)
    public DemoService helloworldService() {
        DemoService demoService= new DemoService();
        demoService.setStr1(demoProperties.getStr1());
        demoService.setStr2(demoProperties.getStr2());
        return demoService;
    }

}

  1. 在resources下创建目录META-INF,在 META-INF 目录下创建 spring.factories,在SpringBoot启动时会根据此文件来加载项目的自动化配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.springboot.config.DemoAutoConfiguration 
  1. 其他项目中使用自定义的Starter
<!--引入自定义Starter-->
<dependency>
    <groupId>com.lhf.springboot</groupId>
    <artifactId>spring-boot-starter-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

  1. 编写属性配置文件
#配置自定义的属性信息
str.str1=str1
str.str2=str2
  1. 写注解使用
@RestController
public class StringController {

      @Autowired
    private DemoService demoService;  //引入自定义Starter中的DemoService 

      @RequestMapping("/")
      public String addString(){
        return demoService.getStr1()+ demoService.getStr2();
    }
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值