自定义SpringBoot-Starter

在使用SpringBoot时,经常会使用Starter,自己实现一个Starter可以帮助自己更好的理解SpringBoot开箱即用的原理。

 

第一步:创建一个普通的Maven工程,pom.xml重要内容如下:

<modelVersion>4.0.0</modelVersion>
<groupId>com.mn</groupId>
<artifactId>Cicada-Spring-Boot-Stater</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>1.5.19.RELEASE</version>
    </dependency>
</dependencies>

第二步:创建一个配置类,用于读取application.properties或者yml文件中的内容

@ConfigurationProperties(prefix = "example.service")
public class StarterServiceProperties
{
    private String config = "default";

    public void setConfig(String config)
    {
        this.config = config;
    }

    public String getConfig()
    {
        return config;
    }
}

 

第三步:创建一个Configruration类

@Configuration
@ConditionalOnClass(StarterService.class)
@EnableConfigurationProperties(StarterServiceProperties.class)
public class StarterAutoConfigure
{

    @Autowired
    private StarterServiceProperties starterServiceProperties;

    @Bean
    @ConditionalOnMissingBean
    //  @ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")
    StarterService starterService()
    {
        return new StarterService(starterServiceProperties.getConfig());
    }
}

第四步:创建一个需要注入的类

public class StarterService
{
    private String config;

    public StarterService(String config)
    {
        this.config = config;
    }

    public String getConfig()
    {
        return config;
    }

    public void print()
    {
        System.out.println(config);
    }
}

第五步:极为重要的一步,将自动配置类注册到 spring.factories 文件中

在resources/META-INF/  新建一个spring.factories文件,并按自己实际包路径修改以下配置

 

org.springframework.boot.autoconfigure.EnableAutoConfiguration=xx.xx.StarterAutoConfigure

 

第六步:将该Starter安装到本地仓库,使用maven命令mvn install,具体maven使用请自行学习。

 

第七步:创建一个SpringBoot项目,将该Starter引入到项目中。

<dependency>
    <groupId>com.mn</groupId>
    <artifactId>Cicada-Spring-Boot-Stater</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

实验:

          配置文件为空:

       

配置文件添加example.service.config=hello-cicada

 

附GitHub项目地址:https://github.com/mning628/Cicada/tree/master/Cicada-Parent

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值