自定义spring boot starter

命名规范

start命名规范一般是模块名xxx-spring-boot-starter以及模块名xxx-spring-boot-autoconfigure

模块

starter一般有两个模块,一个是starter,一个是autoconfigure
在这里插入图片描述
在这里插入图片描述

autoconfigure模块

pom.xml必须加入这两个依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

我自己会加入lombok依赖

       <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

先创建xxxproperties,通过@ConfigurationProperties注解来映射配置文件的值,prefix属性指前缀

@Data
@ConfigurationProperties(prefix = "xkl.student")
public class StudentProperties {

    private String name = "李四";
    private Integer age = 18;
    private boolean enable = false;

}

赋值是为了让属性有默认的值,如果不想有默认的值可不赋值,后续他人在配置文件中可以使用会覆盖掉默认值,enable属性后续有用

创建一个想让这个starter提供的服务,比如我想让这个starter返回一个学生给我

//获取学生服务
public class StudentService {

    private final StudentProperties studentProperties;

    public StudentService(StudentProperties studentProperties) {
        this.studentProperties = studentProperties;
    }

    public String getStudent(){
        return "学生姓名:" + studentProperties.getName() +
                ",年龄:" + studentProperties.getAge();
    }

}

创建AutoConfiguration

@Configuration
@EnableConfigurationProperties(StudentProperties.class)
//Spring中引用了某个类才会构建这个bean
@ConditionalOnClass(StudentService.class)
//控制配置类是否生效,value指与配置文件的属性做对比,havingValue指当值是true才生效
@ConditionalOnProperty(value = "yhlz.student.enable",havingValue = "true")
public class StudentAutoConfiguration {

    @Autowired
    private StudentProperties studentProperties;

    @Bean
    //当spring容器有相同的bean则不会再创建这个bean
    @ConditionalOnMissingBean
    public StudentService getStudentService(){
        return new StudentService(studentProperties);
    }
    
}

最重要的一步,在resources下创建META-INF文件夹,再创建spring.factories,为什么要这样做可以去了解一下spring boot的自动化配置原理。
在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.yhlz.config.StudentAutoConfiguration

多个值可用,\分割
在这里插入图片描述
打包安装到仓库里面
在这里插入图片描述

starter模块

主要作用就是把autoconfigure包一层,pom.xml引用autoconfigure模块

    <dependencies>
        <dependency>
            <groupId>org.yhlz</groupId>
            <artifactId>student-spring-boot-autoconfigure</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

测试

测试也很简单,直接使用StudentService来调用它的get方法,返回它默认的值,假如想设定其他值就可以在配置文件中修改
在这里插入图片描述
可以将该值修改为false来让该配置失效
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值