Spring Boot官方提供了很多的Starter,每個Starter都有其各自的功能。我們用起來也爽歪歪。同時,我們也可以自定義一些Starter,提供出來給其他人用。
本文創建一個及其簡單的Starter,這個Starter用來在啓動的時候初始化Person對象。
首先,去 Spring Initializr 創建一個Spring Boot的項目(Starter仍舊是一個Spring Boot Application),如下圖1.
創建的過程中不需要添加依賴。同時,去掉生成的pom.xml中的下面代碼:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
這部分代碼是用來打包的,他需要main方法,但是我們的Starter中是不需要main方法的。所以這個插件要去掉。
然後修改生成的啓動類。修改後的代碼如下:
package cn.com.hanbinit.printspringbootstarter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PrintSpringBootStarterApplication {
private static final Logger logger = LoggerFactory.getLogger(PrintSpringBootStarterApplication.class);
@Value("${hanbin.name:}")
private String name;
@Bean
public Person initPerson(){
logger.info("我是自定義starter裏面打印的,我只會在服務啓動的時候初始化一下!");
return new Person(name);
}
}
在同目錄下創建了Person類,內容如下:
package cn.com.hanbinit.printspringbootstarter;
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
最後,還有一個很重要的事情,在resources下建立META-INF目錄,在目錄下創建spring.factories文件,在文件中添加如下配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.com.hanbinit.printspringbootstarter.PrintSpringBootStarterApplication
到這裏,這個Starter就創建完成了。這個時候我們就可以mvn clean install 或者 deploy給其他人用了。
下面創建一個demo application,引用了spring-boot-starter-web
依賴,我們要在它中使用上面的Starter。
首先,在demo工程的pom.xml中添加依賴:
<dependency>
<groupId>cn.com.hanbinit</groupId>
<artifactId>print-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
同時,修改啓動類爲下面的代碼:
package cn.com.hanbinit.demo;
import cn.com.hanbinit.printspringbootstarter.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
private final Person person;
public DemoApplication(Person person) {
this.person = person;
}
@GetMapping("/get_name")
public String print(){
return person.getName();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
在application.properties中配置 hanbin.name=wo shi hanbin
訪問http://localhost:8080/get_name,可得圖2所示結果:
關於Starter創建更多的可以多看看官方文檔,也可以看看spring-boot-autoconfigure
包的代碼。Starter的技術基礎還是Spring Boot的Auto-Configuration機制。