添加自己的starter

  1. 需要编写一个starter,


    4.0.0
    cn.hl
    my-spring-boot-starter
    1.0-SNAPSHOT
    
        
            cn.hl
            my-spring-boot-autoconfigure
            1.0-SNAPSHOT
        
    


2.创建autoconfigure项目




    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.0.RELEASE
         
    
    cn.hl
    my-spring-boot-autoconfigure
    1.0-SNAPSHOT

    my-spring-boot-autoconfigure
    Demo project for Spring Boot
    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

        
            org.projectlombok
            lombok
            true
        
    

3.在项目添加MyProperties,用于接收配置文件中的属性

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "my")
@Data
public class MyProerties {

    private String first;

    private String second;

}

4.添加MyService,用于实现该项目功能

import lombok.Data;

@Data
public class MyService {
    MyProerties myProerties;
    public String testMethod(){

        return "This is my first method: " + myProerties.getFirst();
    }
}

  1. 添加MyServiceAutoConfigure,用于引入配置文件类,和将功能类注入容器
 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnWebApplication
@EnableConfigurationProperties(MyProerties.class)
@Configuration
public class MyServiceAutoConfigure {

    @Autowired
    private MyProerties myProerties;

    @Bean
    public MyService myService() {
        MyService myService = new MyService();
        myService.setMyProerties(myProerties);
        return myService;
    }

}
  1. 在resourcr目录下创建META-INF目录,在该目录下新建spring.factories
  2. 在spring.factories中添加
org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.hl.starter.MyServiceAutoConfigure

8.打包autoconfigure项目,再打包starter项目。

你可能感兴趣的:(添加自己的starter)