程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(3)

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

发布于2022-08-07 20:38     阅读(951)     评论(0)     点赞(20)     收藏(5)


 前言

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

目录

如何自定义一个SpringBoot Srarter?

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

编写配置文件

自动装配

配置自动类

测试


如何自定义一个SpringBoot Srarter?

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

  1.         <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter</artifactId>
  4.         </dependency>
  5.         <dependency>
  6.             <groupId>org.springframework.boot</groupId>
  7.             <artifactId>spring-boot-configuration-processor</artifactId>
  8.             <optional>true</optional>
  9.         </dependency>
  1. 编写配置文件

    这里定义了属性配置的前缀

    1. @ConfigurationProperties(prefix = "hello")
    2. public class HelloProperties {
    3.     private String name;
    4.     //省略getter、setter
    5. }
  2. 自动装配

    创建自动配置类HelloPropertiesConfigure

    1. @Configuration
    2. @EnableConfigurationProperties(HelloProperties.class)
    3. public class HelloPropertiesConfigure {
    4. }
  3. 配置自动类

    /resources/META-INF/spring.factories文件中添加自动配置类路径

    1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    2.   cn.fighter3.demo.starter.configure.HelloPropertiesConfigure
  4. 测试

    至此,随手写的一个自定义SpringBoot-Starter就完成了,虽然比较简单,但是完成了主要的自动装配的能力。

    • 创建一个工程,引入自定义starter依赖

      1.         <dependency>
      2.             <groupId>cn.fighter3</groupId>
      3.             <artifactId>demo-spring-boot-starter</artifactId>
      4.             <version>0.0.1-SNAPSHOT</version>
      5.         </dependency>
    • 在配置文件里添加配置

      hello.name=张三
      
    • 测试类

      1. @RunWith(SpringRunner.class)
      2. @SpringBootTest
      3. public class HelloTest {
      4.     @Autowired
      5.     HelloProperties helloProperties;
      6.     @Test
      7.     public void hello(){
      8.         System.out.println("你好,"+helloProperties.getName());
      9.     }
      10. }
    • 运行结果

                                                       运行结果

本期分享到此为止,关注博主不迷路,叶秋学长带你上高速~~

原文链接:https://blog.csdn.net/m0_63722685/article/details/126082845



所属网站分类: 技术文章 > 博客

作者:javagogogo

链接:http://www.javaheidong.com/blog/article/472566/ec8efbec5916b9599b3d/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

20 0
收藏该文
已收藏

评论内容:(最多支持255个字符)