自定義一個springboot starter

爲何想學

在使用了不少springboot的starter以後,感受這種形式很好用,若是我把本身平時使用的一些工具用starter的形式寫,之後在須要相似的工具時只須要直接拿來用或者作一些簡單的修改就能夠了。spring

建立一個starter

開發工具使用eclipse,安裝sts插件。以我使用ueditor爲例,建立一個叫ueditor-spring-boot-starter的spring boot maven項目。springboot

定義starter須要的變量

咱們使用springboot時,通常都會使用yml文件或者properties文件定義變量,若是個人springboot項目須要一些配置,也要在yml文件中定義,須要一些代碼才能實如今eclipse中的自定提醒。eclipse

@ConfigurationProperties(prefix="ueditor") public class ConfigOnProperties { private String rootPath; private String configPath; private String[] staticLocations; public String getRootPath() { return rootPath; } public void setRootPath(String rootPath) { File file = new File(rootPath); if(file.exists() && file.isDirectory()) this.rootPath = rootPath; else { String classPath = this.getClass().getResource("/").toString(); if(staticLocations != null) { for (String staticLocation : staticLocations) { File configFile = new File(staticLocation + "/" + configPath); if(configFile.exists()) { classPath = staticLocation + "/"; } } } if(classPath != null) { this.rootPath = classPath.replace("file:\\", "") .replace("file:/", "") + rootPath; }else { this.rootPath = rootPath; } } } public String getConfigPath() { return configPath; } public void setConfigPath(String configPath) { this.configPath = configPath; } public String[] getStaticLocations() { return staticLocations; } public void setStaticLocations(String[] staticLocations) { this.staticLocations = staticLocations; if(this.rootPath != null ) { setRootPath(this.rootPath); } } }

在上面的例子中,我定義了3個變量配置,分別是ueditor.rootPath、ueditor.configPath和ueditor.staticLocations。使用到了一個註解:@ConfigurationProperties(prefix="ueditor"),與後面的@EnableConfigurationProperties配合實現定義變量。maven

定義starter的默認bean配置

爲了方便在後面的使用中自定義ueditor的各類操做,我定義了一個service接口來執行ueditor的各類操做,同時爲這個接口寫了一個默認的實現。若是使用spring的@Service註解,在後面的使用中會出現一個關於重複bean的報錯,這裏使用configuration文件,來定義缺失bean:spring-boot

@Configuration @EnableConfigurationProperties(value=ConfigOnProperties.class) @ComponentScan(basePackages="xxxx.ctrl") public class UeditorAutoConfiguration { @Bean @ConditionalOnMissingBean(IUeditorService.class) public IUeditorService uEditorService() { return new DefaultUeditorService(); } }

@ConditionalOnMissingBean這個註解,定義了在缺失指定類型的bean時,使用這個bean來代替。工具

使spring掃描到這些配置

springboot默認的掃描bean範圍是@SpringBootApplication註解的類所在的package,也能夠經過@ComponentScan來定義掃描範圍,可是一個starter若是須要這樣的定義才能使用也太不智能了,百度了一下,能夠在starter的resources下,建立一個META-INF文件夾,而後建立文件spring.factories文件,裏面配置掃描包。開發工具

# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ xxxx.config.UeditorAutoConfiguration
相關文章
相關標籤/搜索