spring boot stater
通过使用Spring Boot Starter
将一些层、组件拆分为模块来管理,以便相互依赖复用。
自定义
1、创建一个Maven
项目
首先自定义一个Maven
项目,pom.xml
中引入依赖。
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
这里说下artifactId
的命名问题,Spring
官方 Starter
通常命名为spring-boot-starter-{name}
如 spring-boot-starter-web
, Spring
官方建议非官方Starter
命名应遵循{name}-spring-boot-starter
的格式.
2、创建一个简单的Starter
提供一个简单的Stater
,提供一个Service
,包含一个能够将字符串加上前后缀的方法String wrap(String word)。
public class DemoService {
private String prefix;
private String suffix;
public DemoService(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String wrap(String word) {
return prefix + word + suffix;
}
}
前缀、后缀通过读取application.properties(yml)内的参数获得。
@ConfigurationProperties("demo.service")
public class DemoServiceProperties {
private String prefix;
private String suffix;
#省略 set 和 get
}
编写AutoConfigure
类。
@Configuration
@ConditionalOnClass(DemoService.class)
@EnableConfigurationProperties(DemoServiceProperties.class)
public class DemoAutoConfigure {
@Autowired
private DemoServiceProperties demoServiceProperties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "demo.service",value = "enabled",havingValue = "true")
DemoService demoService(){
return new DemoService(demoServiceProperties.getPrefix(),demoServiceProperties.getSuffix());
}
}
解释下用到的几个和Starter相关的注解:
@ConditionalOnClass
,当classpath
下发现该类的情况下进行自动配置。@ConditionalOnMissingBean
,当Spring Context
中不存在该Bean
时。@ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true")
,当配置文件中example.service.enabled=true
时
更多相关注解,建议阅读官方文档部分
最后一步,在resources/META-INF/下创建spring.factories文件,内容供参考下面:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.demospringbootstarter.DemoAutoConfigure
执行mvn install
打包安装。
使用
1、新建一个新的Spring Boot
项目
把stater
的依赖加入项目中。
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
创建application.properties
,进行配置
demo.service.enabled=true
demo.service.prefix=####
demo.service.suffix=@@@@
使用
@Autowired
private DemoService demoService;
@GetMapping("/input/{word}")
public String input(@PathVariable("word") String word){
return demoService.wrap(word);
}
原理
总结下Starter
的工作原理.
Spring Boot
在启动时扫描项目所依赖的JAR
包,寻找包含spring.factories
文件的JAR
包- 根据
spring.factories
配置加载AutoConfigure
类 - 根据
@Conditional
注解的条件,进行自动配置并将Bean
注入Spring Context