栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义SpringBoot Starter

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义SpringBoot Starter

自定义SpringBoot Starter
  1. 引入项目的配置依赖

    org.springframework.boot
    spring-boot-autoconfigure
    2.1.4.RELEASE

  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


    com.lhf.springboot
    spring-boot-starter-demo
    0.0.1-SNAPSHOT


  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();
    }
}

 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/931042.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号