Skip to content

Commit f8cc66b

Browse files
committed
支持简单的字符串插值
1 parent a2d4fb4 commit f8cc66b

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

spring-properties-default.go

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -271,15 +271,42 @@ func bindStructField(p Properties, v reflect.Value, str string, opt bindOption)
271271
bindValue(p, v, key, def, opt)
272272
}
273273

274+
// Interpolate 处理字符串插值
275+
func Interpolate(p Properties, str string) string {
276+
277+
start := strings.Index(str, "${")
278+
if start < 0 {
279+
return str
280+
}
281+
282+
end := strings.IndexByte(str[start+2:], '}')
283+
if end < 0 {
284+
return str
285+
}
286+
287+
end = start + 2 + end
288+
key := str[start+2 : end]
289+
val, ok := p.GetDefaultProperty(key, nil)
290+
if !ok {
291+
panic(fmt.Errorf("property \"%s\" not config", key))
292+
}
293+
294+
return str[:start] + fmt.Sprint(val) + Interpolate(p, str[end+1:])
295+
}
296+
274297
// resolveProperty 解析属性值,查看其是否具有引用关系
275298
func resolveProperty(p Properties, _ string, value interface{}) interface{} {
276-
str, ok := value.(string)
277299

278-
// 不是字符串或者没有使用配置引用语法
279-
if !ok || !strings.HasPrefix(str, "${") {
300+
str, ok := value.(string)
301+
if !ok {
280302
return value
281303
}
282304

305+
// 遍历字符串看看是否包含 ${} 结构并解析
306+
if !strings.HasPrefix(str, "${") {
307+
return Interpolate(p, str)
308+
}
309+
283310
key, def := parsePropertyTag(str[2 : len(str)-1])
284311
if val, _ := p.GetDefaultProperty(key, def); val != nil {
285312
return resolveProperty(p, key, val)

spring-properties-default_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -807,3 +807,18 @@ func TestDefaultProperties_KeyCanBeEmpty(t *testing.T) {
807807
p.BindProperty("", &s)
808808
assert.Equal(t, s.KeyIsEmpty, "kie")
809809
}
810+
811+
func TestInterpolate(t *testing.T) {
812+
p := SpringCore.NewDefaultProperties()
813+
p.SetProperty("name", "Jim")
814+
str := SpringCore.Interpolate(p, "my name is ${name")
815+
assert.Equal(t, str, "my name is ${name")
816+
str = SpringCore.Interpolate(p, "my name is ${name}")
817+
assert.Equal(t, str, "my name is Jim")
818+
str = SpringCore.Interpolate(p, "my name is ${name}${name}")
819+
assert.Equal(t, str, "my name is JimJim")
820+
str = SpringCore.Interpolate(p, "my name is ${name} my name is ${name")
821+
assert.Equal(t, str, "my name is Jim my name is ${name")
822+
str = SpringCore.Interpolate(p, "my name is ${name} my name is ${name}")
823+
assert.Equal(t, str, "my name is Jim my name is Jim")
824+
}

0 commit comments

Comments
 (0)