抽取通用模塊做爲項目的一個spring boot starter。可參照mybatis的寫法。spring
IDEA建立Empty Project並添加以下2個module,一個基本maven模塊,另外一個引入spring-boot-starter依賴。springboot
1) xxx-spring-boot-starter - 引入依賴並管理依賴版本mybatis
demo-spring-boot-starterapp
<dependencies> <dependency> <groupId>org.chris</groupId> <artifactId>demo-spring-boot-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>
2) xxx-spring-boot-autoconfigure - xxx的自動配置類maven
demo-spring-boot-autoconfigurespring-boot
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>
屬性類DemoProperties
@ConfigurationProperties(prefix = "chris.demo") public class DemoProperties { private String name; private String content; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
功能類DemoService測試
public class DemoService { private DemoProperties demoProperties; public DemoProperties getDemoProperties() { return demoProperties; } public void setDemoProperties(DemoProperties demoProperties) { this.demoProperties = demoProperties; } public String demoShow(){ return this.demoProperties.getName() + " ----- " + this.demoProperties.getContent(); } }
自動配置類DemoAutoConfigurationthis
@Configuration @ConditionalOnWebApplication @EnableConfigurationProperties(DemoProperties.class) public class DemoAutoConfiguration { @Autowired private DemoProperties demoProperties; @Bean public DemoService demoService(){ DemoService demoService = new DemoService(); demoService.setDemoProperties(demoProperties); return demoService; } }
最後添加DemoAutoConfiguration到EnableAutoConfiguration中spa
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.chris.springboot.DemoAutoConfiguration
在新的spring boot項目中若是須要引用以上starter,只須要在依賴中添加以下,code
<dependency> <groupId>org.chris</groupId> <artifactId>demo-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
測試類DemoController
@RestController public class DemoController { @Autowired private DemoService demoService; @GetMapping("demo") public String demo(){ return demoService.demoShow(); } }
附上代碼