自定义一个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
相关文章
相关标签/搜索