前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 系列三:如何自定义一个SpringBoot Srarter

Spring Boot 系列三:如何自定义一个SpringBoot Srarter

原创
作者头像
叶秋学长
发布2022-08-02 11:22:04
2110
发布2022-08-02 11:22:04
举报
文章被收录于专栏:全栈学习专栏全栈学习专栏

前言上一期我们通过学习知道了自动配置原理,其实创建一个自定义SpringBoot Starter也很简单。

目录

如何自定义一个SpringBoot Srarter?

首先创建一个项目,命名为demo-spring-boot-starter,引入SpringBoot相关依赖

编写配置文件

自动装配

配置自动类

测试

如何自定义一个SpringBoot Srarter?

首先创建一个项目,命名为demo-spring-boot-starter,引入SpringBoot相关依赖

代码语言:javascript
复制
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
  1. 编写配置文件 这里定义了属性配置的前缀 @ConfigurationProperties(prefix = "hello") public class HelloProperties { private String name; //省略getter、setter }
  2. 自动装配 创建自动配置类HelloPropertiesConfigure @Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloPropertiesConfigure { }
  3. 配置自动类 在/resources/META-INF/spring.factories文件中添加自动配置类路径 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ cn.fighter3.demo.starter.configure.HelloPropertiesConfigure
  4. 测试 至此,随手写的一个自定义SpringBoot-Starter就完成了,虽然比较简单,但是完成了主要的自动装配的能力。
    • 创建一个工程,引入自定义starter依赖 <dependency> <groupId>cn.fighter3</groupId> <artifactId>demo-spring-boot-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
    • 在配置文件里添加配置 hello.name=张三
    • 测试类 @RunWith(SpringRunner.class) @SpringBootTest public class HelloTest { @Autowired HelloProperties helloProperties; @Test public void hello(){ System.out.println("你好,"+helloProperties.getName()); } }
    • 运行结果

    编辑 运行结果

本期分享到此为止

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 如何自定义一个SpringBoot Srarter?
    • 首先创建一个项目,命名为demo-spring-boot-starter,引入SpringBoot相关依赖
      • 本期分享到此为止
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档