一、starter的作用
当我们实现了一个组建,希望尽可能降低它的介入成本,一般的组建写好了,只要添加spring扫描路径加载spring就能发挥作用。有个更简单的方式扫描路径都不用加,直接引入jar就能使用。
原理时因为springboot提供一个配置文件 spring.factories,预定好了加载那个配置类。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xjw.HelloAutoConfiguration
二、自定义实现starter
1、创建pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>generateCode-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>generateCode-starter</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build> </project>
2、创建配置类
package com.starter.demo; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class GeneraterConfig { @Bean
GeneraterIdService getGeneraterIdService(){
return new GeneraterIdService();
} }
3、组建类:GeneraterIdService.java
package com.starter.demo; import java.util.Date; public class GeneraterIdService {
public String generaterId(){
return new Date().getTime()+"";
}
}
4、spring.factories文件
路径:resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.starter.demo.GeneraterConfig
三、打包测试
1、引入
<dependency>
<groupId>com.example</groupId>
<artifactId>generateCode-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2、使用测试
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class RestTemplateTest {
@Autowired
GeneraterIdService generaterIdService; @Test
public void TestGeneraterId(){
System.out.println(generaterIdService.generaterId());
} }