当前位置: 首页 > news >正文

springboot自定义starter

自定义starter主要就是将我们需要使用的对象自动添加到IOC容器,成为bean对象,通过引入starter,能够直接通过 @Autowired 注解或 @Resource 注解从IOC容器中获取该对象

一、创建starter

这里我用一个Student类代表向IOC容器中添加的bean,起步依赖名为 student-springboot-starter,目录结构如下:

导入依赖

<!-- 自动配置 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>2.7.0</version>
</dependency>
<!-- 提供get、set方法等 -->
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</version>
</dependency>

定义Student类(这个类将生成bean对象进入IOC容器)

@Data
public class Student {private String name;private Integer age;;
}

二、定义配置文件读取类

配置类是通过 无参构造 创建出来,在通过 set方法属性注入 的,所以一定要保证无参构造器和对应set方法存在  

@ConfigurationProperties(prefix = "student")
@Data
public class StudentProperty {private String name;private Integer age;
}

即使用时要通过如下配置信息设置bean的属性值(yml格式)

student:name: zsage: 18

三、定义自动配置类

@Configuration
@ConditionalOnClass(Student.class)
@EnableConfigurationProperties({StudentProperty.class})
public class StudentAutoConfig {@Autowiredprivate StudentProperty property;@Beanpublic Student student() {Student student = new Student();student.setName(student.getName());student.setAge(property.getAge());return student;}
}
  • @Configuration:标注这是一个配置类

  • @ConditionalOnClass(Student.class):条件注入,代表Student类存在时才会创建对应bean

  • @EnableConfigurationProperties({StudentProperty.class}):指出配置文件读取类

四、在文件中声明自动配置类

 目录结构如下:

 

方式1:通过spring.factories文件声明

使用条件:SpringBoot版本 >= 2.1.0.RELEASE

在resources目录下创建 META-INF 目录,在META-INF目录中创建 spring.factories 文件,

通过 org.springframework.boot.autoconfigure.EnableAutoConfiguration 属性之处自动配置类,多个类之间用逗号(,)隔开,需要换行时在上一行末尾加上\,如:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.example.autoconfig.StudentAutoConfig
方式2:通过 org.springframework.boot.autoconfigure.AutoConfiguration.imports 配置文件指出

使用条件:SpringBoot版本 >= 2.7.0

在resources目录下创建 META-INF 目录,在META-INF目录中创建 spring 目录,在spring目录下创建 org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件,在这个文件中直接指出自动配置类即可,一个类独占一行,如:

com.example.autoconfig.StudentAutoConfig

 完成以上配置就可以通过引入自定义starter,简单配置,就可以直接使用bean了!


http://www.mrgr.cn/news/47786.html

相关文章:

  • YOLOv10改进目录一览 | 涉及卷积层、轻量化、注意力、损失函数、Backbone、SPPF、Neck、检测头等全方位改进方向
  • 免费又好用的保护网站WAF,基于语义引擎的waf雷池社区版推荐
  • 自然语言处理问答系统
  • 春日编程助手:Spring Boot课程答疑服务
  • 做好不如计划好:生成计划管理
  • YOLOv11改进策略【注意力机制篇】| 2024 SCSA-CBAM 空间和通道的协同注意模块
  • 【Canvas与诗词】要做一棵树,站成永恒
  • 《系统架构设计师教程(第2版)》第18章-安全架构设计理论与实践-02-安全模型
  • Mac pro 之Android Studio之解决logcat日志无法输出问题
  • STM32CUBEIDE的使用【一】点亮LED
  • 一文详细解析如何使用LangChain、NestJS 和 Gemma 2 构建一个 Agentic RAG 应用
  • 小猿口算自动PK脚本
  • Matplotlib运行报错ValueError: object __array__ method not producing an array
  • 【自用视频笔记】25计算机基础综合408大纲新增考点 多处理机调度
  • VMWare vsphere ESXi 6.7在线升级至7.0.3
  • 【hot100-java】随机链表的复制
  • ODE45函数——中间变量提取,时变量参数,加速仿真以及运行进度条
  • CLIP——多模态预训练模型介绍
  • 【Linux系统编程】第三十弹---软硬链接与动静态库的深入探索
  • BERT的中文问答系统14