SpringBoot 自定義Starter
阿新 • • 發佈:2022-05-19
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.6.7</version>
</dependency>
</dependencies>
/** * TestDemo * */ public class TestDemo { /** * 名稱*/ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
/** * 屬性 * */ @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; } }
/**
* TestDemo
* */
public class TestDemo {
/**
* 名稱*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/** * 自動配置類 * */ @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(); } }
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.ausion.configuration.TestDemoAutoConfiguration
<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>
demo:
enable: true
test: 123456
@RestController
public class TestController {
@Autowired
private TestDemoService testDemoService; //引入自定義Starter中的testDemoService
@RequestMapping("/test")
public String addString(){
return testDemoService.Test();
}
}
結果