1. 程式人生 > 其它 >SpringBoot 自定義Starter

SpringBoot 自定義Starter

Starter專案 1.建立專案 2.引入需要的依賴
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.6.7</version>
  </dependency>
</dependencies>
3.新建專案目錄
4.新增類 新建TestDemo DTO
/**
 * TestDemo
 * */
public class TestDemo {
    /**
     * 名稱*/
    private String name;

    public String getName() {
        return name;
    }

    
    public void setName(String name) {
        this.name = name;
    }
}
新建配置檔案 TestDemoProperties Properties
/**
 * 屬性
 * */
@ConfigurationProperties(prefix = "demo")
public class  TestDemoProperties {
    /**
     * 是否啟動
     * */
    private boolean enable;
    /**
     * test屬性
    * */
    private String test;

    public boolean isEnable() {
        return enable;
    }
    public void setEnable(boolean enable) {
        this.enable = enable;
    }
    public String getTest() {
        return test;
    }
    public void setTest(String test) {
        this.test = test;
    }
}
新建TestDemoService Service
/**
 * TestDemo
 * */
public class TestDemo {
    /**
     * 名稱*/
    private String name;

    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }
}
新建自動配置檔案 TestDemoAutoConfiguration
/**
* 自動配置類
* */
@Configuration
@ConditionalOnClass(TestDemoService.class) //判斷是否存在TestDemoService
@ConditionalOnProperty(prefix = "demo", value = "enable", matchIfMissing = true)  //判斷firststarter.enable屬性是否為true
@EnableConfigurationProperties(TestDemoProperties.class)
public class TestDemoAutoConfiguration {


    /**
    * 獲取TestDemoService
    * */
    @Bean
    @Order
    @ConditionalOnMissingBean
    public TestDemoService testdemoService() {
        return new TestDemoService();
    }
}
新建配置檔案
resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ausion.configuration.TestDemoAutoConfiguration
呼叫Starter專案
引入依賴
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.6.7</version>
</dependency>
<dependency>
    <groupId>com.ausion</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>compile</scope>
</dependency>
 
新建yaml
demo:
 enable: true
 test: 123456
新建Controller
@RestController
public class TestController {
    @Autowired
    private TestDemoService testDemoService; //引入自定義Starter中的testDemoService

    @RequestMapping("/test")
    public String addString(){
        return testDemoService.Test();
    }
}

結果