SpringBoot-自定义Starter

目录

一、starter启动原理

         二、自定义 Starter


一、starter启动原理

  • starter-pom引入 autoconfigurer
  • autoconfigure包中配置使用 META-INF/spring.factoriesEnableAutoConfiguration的值,使得项目启动加载指定的自动配置类

二、自定义 Starter

        首先在一个工程里创建两个项目,一个普通maven项目,另一个使用spring-initializer。

         修改starter的配置文件,加入下面内容:

<dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>atguigu-hello-spring-boot-starter-autoconfigure</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>

<!--让starter引用autoconfigure-->

        在autoconfigure包下创建spring.factories文件

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.hello.auto.HelloServiceAutoConfiguration

        创建相应的包、类

 

@Configuration
@EnableConfigurationProperties(HelloProperties.class)  //默认HelloProperties放在容器中
public class HelloServiceAutoConfiguration{

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

}
/**
 * 默认不要放在容器中
 */
public class HelloService {

    @Autowired
    HelloProperties helloProperties;

    public String sayHello(String userName){
        return helloProperties.getPrefix() + ":"+userName+"》"+helloProperties.getSuffix();
    }
}
@ConfigurationProperties("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;
    }
}

        分别cleaninstallautoconfigure包和starter包,存到本地maven仓库中

         去新的工程中引用自定义starter包

<dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>atguigu-hello-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
</dependency>

       在application.yaml中配置参数

atguigu:
  hello:
    prefix: hello
    suffix: you are beautiful

        测试

@RestController
public class helloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/iKun")
    public String helloIKun(){
        return helloService.sayHello("cxk");
    }
}

版权声明:本文为weixin_62427168原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。