1. starter启动原理

  • starter-pom引入 autoconfigurer 包

10. 自定义starter - 图1

  • autoconfigure包中配置使用 META-INF/spring.factoriesEnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
  • 编写自动配置类 xxxAutoConfiguration -> xxxxProperties
  • @Configuration
  • @Conditional
  • @EnableConfigurationProperties
  • @Bean
  • ……

引入starter —- xxxAutoConfiguration —- 容器中放入组件 —— 绑定xxxProperties —— 配置项

2. 自定义步骤

atguigu-hello-spring-boot-starter(启动器)
atguigu-hello-spring-boot-starter-autoconfigure(自动配置包)
image.png
在atguigu-hello-spring-boot-starter里面引入atguigu-hello-spring-boot-starter-autoconfigure的maven坐标

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.hao</groupId>
  7. <artifactId>hao-hello-spring-boot-starter</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <dependencies>
  10. <dependency>
  11. <groupId>com.hao</groupId>
  12. <artifactId>hao-hello-spring-boot-starter-autoconfigure</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. </dependency>
  15. </dependencies>
  16. </project>

创建一个Service引用一个自动注入的bean

package com.hao.hello.service;
//默认不要放在容器中
public class HelloService {

    @Autowired
    HelloProperties helloProperties;

    public String sayHello(String userName){
        return helloProperties.getPrefix() + ": " + userName + "》 " + helloProperties.getSuffix();
    }
}

创建一个bean设置配置文件绑定

package com.hao.hello.bean;

@ConfigurationProperties("hao.hello")
public class HelloProperties {

    private String prefix;
    private String suffix;

    @Override
    public String toString() {
        return "HelloProperties{" +
                "prefix='" + prefix + '\'' +
                ", suffix='" + 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;
    }
}

创建配置类将创建的Service加入到容器中(如果用户自己创建了同名的Service类就不会自动将写好的Service类自动注入,而是以用户写的优先)

package com.hao.hello.auto;

@Configuration
@ConditionalOnMissingBean(HelloService.class)
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {

    @Bean
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        return helloService;
    }

}

**创建META-INF文件夹,并在META-INF文件夹下面创建spring.factories文件将自动配置的主程序类加入
image.png
image.png