美文网首页
创建一个自定义的springboot-starter

创建一个自定义的springboot-starter

作者: 绝对熙俊 | 来源:发表于2020-08-18 17:30 被阅读0次

    创建一个新的Springboot项目

    • 用idea创建一个maven项目
    • 修改项目的pom文件
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.4.RELEASE</version>
    </parent>
    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    </dependencies>
    
    • 创建一个Properties收集配置
    @ConfigurationProperties(prefix = "za.fcp.common.share")
    public class ShareProperties {
        /**
         * 是否启用,默认启用
         */
        private Boolean enable = true;
        public Boolean getEnable() {
            return enable;
        }
        public void setEnable(Boolean enable) {
            this.enable = enable;
        }
    }
    
    • 创建一个service或者Component,提供方法
    public class ShareComponent {
    
        private boolean enable;
    
        public ShareComponent(boolean enable) {
            this.enable = enable;
        }
    
        public boolean enable() {
            return this.enable;
        }
    }
    
    • 定义一个Configuration,当有配置参数的时候,把这个service加载成bean
    @Configuration
    @EnableConfigurationProperties(ShareProperties.class)
    @ConditionalOnProperty(
            prefix = "za.fcp.common.util",
            name = "enable",
            havingValue = "true"
    )
    public class ShareConfig {
    
        @Autowired
        private ShareProperties shareProperties;
    
        @Bean(name = "shareComponent")
        public ShareComponent shareComponent() {
            return new ShareComponent(shareProperties.getEnable());
        }
    
    }
    
    • 最后最关键,在resources下创建一个META-INF文件夹,这个文件夹里创建一个spring.factories文件
      这个文件就写死是读刚才的那个Configuration
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zhongan.fcp.common.share.configuration.ShareConfig
    
    • 好了,这就完成一个springboot-starter,其他应用只要加了这个za.fcp.common.share属性,就能注入ShareComponent,并使用这个service的方法了

    相关文章

      网友评论

          本文标题:创建一个自定义的springboot-starter

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