springboot自定义starter

20 篇文章 0 订阅
15 篇文章 0 订阅

springboot自定义starter

自定义starter主要就是将我们需要使用的对象自动添加到IOC容器,成为bean对象,通过引入starter,能够直接通过@Autowired注解或@Resorce注解从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: zs
  age: 18

三、定义自动配置类

@Configuration
@ConditionalOnClass(Student.class)
@EnableConfigurationProperties({StudentProperty.class})
public class StudentAutoConfig {

	@Autowired
    private StudentProperty property;

    @Bean
    public 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

utoConfiguration.imports文件,在这个文件中直接指出自动配置类即可,一个类独占一行,如:

com.example.autoconfig.StudentAutoConfig

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值