SpringQueryMap在项目中的应用

x33g5p2x  于2022-04-29 转载在 Spring  
字(2.4k)|赞(0)|评价(0)|浏览(458)

项目应用中遇到get请求传递参数的问题:
1、传递多个参数。
2、传递的参数可以为空,为空则不传递出去。

刚开始的项目比较单一,直接写的请求方法,比如:

@FeignClient("cmdb", url = "\${fastone.global.cmdb.host}")
interface CmdbClient {

	@GetMapping("/cmdb/v1/product")
	fun findByFastoneStrategyAndProductLevelAndPayTypeAndFastoneRegion(
		@RequestParam fastoneStrategy: String,
		@RequestParam productLevel: String,
		@RequestParam payType: String,
		@RequestParam fastoneRegion: String,
	): Response<List<CmdbProduct>>

	/**
	 * 带Context查询CmdbProduct信息
	 * context contains:fastoneStrategy,productLevel,payType,fastoneRegion
	 */
	@GetMapping("/cmdb/v1/product")
	fun findByFastoneStrategyAndProductLevelAndPayTypeAndFastoneRegionAndFastoneModel(
		@RequestParam fastoneStrategy: String,
		@RequestParam productLevel: String,
		@RequestParam payType: String,
		@RequestParam fastoneRegion: String,
		@RequestParam fastoneModel: String
	): Response<List<CmdbProduct>>

	@GetMapping("/cmdb/v1/product")
	fun findByFastoneStrategyAndProductLevelAndPayTypeAndFastoneRegionAndSystemPlatformAndProductTypeAndVendorModel(
		@RequestParam fastoneStrategy: String,
		@RequestParam productLevel: String,
		@RequestParam payType: String,
		@RequestParam fastoneRegion: String,
		@RequestParam systemPlatform: String,
		@RequestParam productType: String,
		@RequestParam vendorModel: String,
	): Response<List<CmdbProduct>>

}

上面的写法会造成查看方法和调用方法的地方都很难受,想查看或者调用方法都需要仔细查看名字

有没有什么方法能满足上面的需求,经同事推荐使用@SpringQueryMap 注解

使用方法:

@FeignClient("cmdb", url = "\${fastone.global.cmdb.host}")
interface CmdbClient {

	@GetMapping("/cmdb/v1/product")
	fun getCmdbProducts(@SpringQueryMap condition: CmdbQueryCondition): Response<List<CmdbProduct>>
}
data class CmdbQueryCondition(
	val skuId: String? = null,
	val fastoneStrategy: String? = null,
	val productLevel: String? = null,
	val fastoneRegion: String? = null,
	val vendor: String? = null,
	val productType: ProductType? = null,
	val systemPlatform: SystemPlatform? = null,
	val fastoneModel: String? = null,
	val fastoneFamily: String? = null,
	val vendorModel: String? = null,
	val payType: String? = null,
)

使用的方法的地方:

/**
	 * 获取IMAGE,STORAGE,STORAGE_EFS,TRAFFIC,FASTSTOR_ESSENTIAL等非VM的报价
	 */
	fun findByFastoneRegionAndFastoneModel(fastoneRegion: String, fastoneModel: String): CmdbProduct? {
		return cmdbClient.getCmdbProducts(
			CmdbQueryCondition(
				fastoneStrategy = fastoneStrategy,
				productLevel = productLevel,
				payType = PayType.ONDEMAND.name,
				fastoneRegion = fastoneRegion,
				fastoneModel = fastoneModel
			)
		).data.firstOrNull()
	}

这样整个方法就很清晰了

相关文章