美文网首页
教你如何自定义SpringBoot中starter启动器

教你如何自定义SpringBoot中starter启动器

作者: 弹钢琴的崽崽 | 来源:发表于2020-03-02 12:28 被阅读0次

starter:
1、这个场景需要使用到的依赖是什么?
2、如何编写自动配置

3、模式:

  • 启动器只用来做依赖导入;
  • 专门来写一个自动配置模块;
  • 启动器依赖自动配置;别人只需要引入启动器(starter)
  • mybatis-spring-boot-starter;自定义启动器名-spring-boot-starter

1. 创建一个空的工程

2. 添加module-启动器

这是一个启动器

3. 再创建一个模块-自动配置

用Spring Initializr创建

这个模块是做自动配置的

SpringBoot版本1.5.10不引入任何模块

4.启动器模块引入自动配置模块的坐标

删掉自动配置模块中无用的文件

主配置文件,主启动类,pom.xml文件中test依赖,插件依赖都可以删掉

5. 自动配置模块的编写

a. 把所有可以配置的属性绑在HelloProperties类

package com.atguigu.starter;
@ConfigurationProperties(prefix = "atguigu.hello")
public class HelloProperties {

    private String prefix;
    private String suffix;

    public String getPrefix() {
        return prefix;
    }
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    public String getSuffix() {
        return suffix;
    }
    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

b. HelloService

c. 自动配置类

package com.atguigu.starter;
@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class)//让属性文件生效
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;
    }
}

d. spring.factories启动加载配置类

让自动配置类生效还得在类路径下写一个文件夹META-INF在此文件夹下放一个文件spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.starter.HelloServiceAutoConfiguration

6. 把整个工程装到maven仓库中

第一步:装自动配置包

第二部:装启动器

这样就可以拿坐标引入了

7. 测试工程

新建SpringBoot项目选中web模块,版本还是1.5.10

引入自定义启动器的坐标

a. Controller测试

b.前后缀在配置文件中配置

c. 访问成功

相关文章

网友评论

      本文标题:教你如何自定义SpringBoot中starter启动器

      本文链接:https://www.haomeiwen.com/subject/kaqmkhtx.html