iT邦幫忙

2018 iT 邦幫忙鐵人賽
0
Software Development

30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構系列 第 32

Day 32 - Configuration meta-data in Spring Boot

寫程式免不了有些組態設定之類的,尤其當你這程式是一個公用類別的時候,還必須教大家怎麼設定變數直,出份文件之類的

現在可以透過 org.springframework.boot:spring-boot-configuration-processor 來自動產生參數的描述檔,當大家需要變動參數時,就可以自動提示知道有那些參數跟說明,省事非常多,最重要的是不會有所謂版本對不起來。

舉例來說我有個設定檔提供程式內部使用像下面這樣

@Data
@Component
@ConfigurationProperties(prefix = "service")
public class ServiceConfig {
    /**
     * config web domain url
     */
    private String domainurl = "xxx";
}

所以我在 application.yaml

service:
  domainurl: "http://samzhu.asuscomm.com"

SpringBoot就會替我自動注入 ServiceConfig

@Autowired
private ServiceConfig serviceConfig;

serviceConfig.getDomainurl(); // 這邊可以取得 http://samzhu.asuscomm.com

但是如果是個公用設定,一般人是不會知道必須配置 service.domainurl ,這樣非常麻煩,
但是你可以透過 org.springframework.boot:spring-boot-configuration-processor 來幫你做這件事,
產生 matadata 資訊,別人可以透過這資訊檔知道有那些參數可以配置

最後會像下面這樣

設定時可以自動提示

產出的描述檔在

我使用 Gradle 說明一下怎麼配置

  1. buildscript.repositories 增加 maven { url 'http://repo.spring.io/plugins-release' }
  2. buildscript.dependencies 增加 classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'
  3. 增加 configure(allprojects)
  4. 增加 compileJava.dependsOn(processResources)
  5. dependencies 增加 optional "org.springframework.boot:spring-boot-configuration-processor"
  6. Rebuild Project

就可以完成了

完整配置參考

buildscript {
	ext {
		springBootVersion = '1.4.1.RELEASE'
	}
	repositories {
		mavenCentral()
		maven { url 'http://repo.spring.io/plugins-release' }
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
		classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7'
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'

jar {
	baseName = 'nt-ask'
	version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
}

configure(allprojects) {
	apply plugin: 'propdeps'
	apply plugin: 'propdeps-maven'
	apply plugin: 'propdeps-idea'
	apply plugin: 'propdeps-eclipse'
}

compileJava.dependsOn(processResources)

dependencies {
	optional "org.springframework.boot:spring-boot-configuration-processor"
	compile('org.projectlombok:lombok')
	compile('org.springframework.boot:spring-boot-starter-web')
	compile('org.springframework.boot:spring-boot-starter-data-rest')
	compile('org.springframework.boot:spring-boot-starter-data-mongodb')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

參考
Spring Cloud Streamを試す(redis) - Qiita
Pimp your config with configuration meta-data in Spring Boot - Jakub Staš


上一篇
Day 31 - 客製化 Swagger UI
下一篇
Day 33 - Spring HATEOAS
系列文
30天從零開始 使用 Spring Boot 跟 Spring Cloud 建構完整微服務架構35
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言