1、springboot场景启动器的作用:
- 引入相关的依赖jar包
- 自动完成bean的配置和加载
2、命名规范
- 官方的starter命名应当遵循:spring-boot-starter-xxx,可以不加版本号,因为父依赖已经添加
- 第三方的starter命名应当遵循:xxx-spring-boot-starter,必须添加版本号
3、如何编写一个stater
3.1新建一个项目,导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--加入这个可以写配置文件的时候有自动提示的效果-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--不加这个配置,打包出来的stater可能无法使用-->
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
3.2新建一个properties
@ConfigurationProperties(prefix = "com.wisdom")
public class HelloServiceProperties {
private String name = "wisdom";
private String hobby = "basketball";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
3.3新建功能实现类
public class HelloServiceConfiguration {
private String name;
private String hobby;
public String getName() {
return "name is " + name;
}
public String getHobby() {
return "hobby is " + hobby;
}
public void setName(String name) {
this.name = name;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
3.4新建自动配置实现类
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloServiceConfiguration.class)
@ConditionalOnProperty(prefix = "com.wisdom", value = "enabled", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
@ConditionalOnMissingBean(HelloServiceConfiguration.class)
public HelloServiceConfiguration helloServiceConfiguration() {
HelloServiceConfiguration helloService = new HelloServiceConfiguration();
helloService.setName(helloServiceProperties.getName());
helloService.setHobby(helloServiceProperties.getHobby());
return helloService;
}
}
3.5在resources文件夹下新建META-INF文件夹,并新建文件spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.hpu.demo.config.HelloServiceAutoConfiguration
运行mvn clean install就可以完成打包
4、如何使用自定义的stater
4.1新建一个测试项目,引入自定义的stater
<!--自定义的stater-->
<dependency>
<groupId>com.hpu</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
4.2编写配置文件
com.wisdom.hobby=study
com.wisdom.name=pss
4.3编写单元测试
@Autowired
private com.hpu.demo.service.HelloServiceConfiguration helloServiceConfiguration;
@Test
void contextLoads() {
System.out.println(helloServiceConfiguration.getName());
}
输出:name is pss