springboot系列十四、自定義實現starter
阿新 • • 發佈:2018-12-31
一、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()); } }