栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot自定义starter

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot自定义starter

1. 新建springboot项目

注意:spring 官方提供 starter 通常命名为 spring-boot-starter-{name}, 我们自定义的starter一般命名为 {name}-spring-boot-starter

2. 删除启动类

3.修改pom文件

       

        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-autoconfigure
        
        
            org.projectlombok
            lombok
            true
        


    
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
            
        
    


4. 定义属性配置类

@Data
@ConfigurationProperties("test.example")
public class TestProperties {

    private String host;

    private int port;
}

5. 定义业务类

@Slf4j
public class TestService {

    private String host;

    private int port;

    public TestService(TestProperties test){
        this.host = test.getHost();
        this.port = test.getPort();
    }

    public void print(){
        log.info(this.host + ":" +this.port);
    }
}

6. 定义配置类

@Configuration
@ConditionalOnClass(TestService.class)
@EnableConfigurationProperties(TestProperties.class)
@ConditionalOnProperty(prefix = "test.example",value = "enabled", havingValue = "true")
@Slf4j
public class TestAutoConfigure {

    @Autowired
    private TestProperties testProperties;

    @Bean
    @ConditionalOnMissingBean(TestProperties.class)
    TestService testService(){
        return new TestService(testProperties);
    }
}

7. 在resources目录下新建meta-INF 目录,在下面新建 spring.factories 文件,文件中申明配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  com.baviya.testspringbootstarter.config.TestAutoConfigure

8.使用mvn clean install 打包

9. 项目中添加依赖

        
            com.test
            test-spring-boot-starter
            1.0.0-SNAPSHOT
        

10. 在application文件中,定义属性,和上面的 属性配置类 TestProperties 关联

test:
  example:
    enabled: true
    host: 127.0.0.1
    port: 8080

12.在业务中使用

@RestController
@RequestMapping
@Slf4j
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping
    public String test(HttpServletRequest request){
        testService.print();
    }
}

1. 遇到的问题:Unable to read meta-data for class  XXXXX

是因为没有删除启动类导致,删除重新打包即可

2. 删除启动类打包失败

修改pom文件中build模块

 
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
            
        
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324632.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号