mirror of
https://github.com/go-home-admin/toolset.git
synced 2025-12-24 13:37:52 +08:00
add: 接口注入
This commit is contained in:
@@ -97,7 +97,7 @@ func (BeanCommand) Execute(input command.Input) {
|
||||
for _, k := range keys {
|
||||
goType := fileParser.Types[k]
|
||||
for _, attr := range goType.Attrs {
|
||||
if attr.HasTag("inject") {
|
||||
if attr.HasTag("inject") || attr.HasTag("impl") {
|
||||
// 只收集使用到的 import
|
||||
bc.imports[fileParser.Imports[attr.TypeAlias]] = attr.TypeAlias
|
||||
}
|
||||
@@ -195,6 +195,13 @@ func genProvider(bc beanCache, m map[string]string) string {
|
||||
if tagName == "inject" {
|
||||
str = str + "\n\t\t" +
|
||||
sVar + "." + attrName + " = " + pointer + getInitializeNewFunName(attr, m)
|
||||
} else if tagName == "impl" {
|
||||
// 使用接口 接收注入
|
||||
tmp := getInitializeNewFunName(attr, m)
|
||||
tmp = strings.ReplaceAll(tmp, "*", "")
|
||||
|
||||
str = str + "\n\t\t" +
|
||||
sVar + "." + attrName + " = " + tmp
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,6 +238,10 @@ func getInitializeNewFunName(k parser.GoTypeAttr, m map[string]string) string {
|
||||
name = name[1:]
|
||||
}
|
||||
tag := k.Tag["inject"]
|
||||
if tag == "" {
|
||||
tag = k.Tag["impl"]
|
||||
}
|
||||
|
||||
if tag == "" {
|
||||
return alias + genInitializeNewStr(name) + "()"
|
||||
} else {
|
||||
|
||||
25
docs/bean.md
25
docs/bean.md
@@ -59,36 +59,15 @@ func (receiver DemoBean) Exit () {
|
||||
|
||||
### 接口注入
|
||||
|
||||
当前为了快速解析语法树, 没有做挎包读取的功能, 无法识别接口定义, 所以需要手动编写代码, 去支持注入
|
||||
|
||||
~~~~go
|
||||
type FromB interface {
|
||||
B()
|
||||
}
|
||||
|
||||
// 注入 b 实现, 是不能直接支持的, 需要提前 NewB() 进行b注册到全局容器。
|
||||
// 这里不要写Bean注解, 否则会报错
|
||||
// 这种方式支持循环依赖
|
||||
// @Bean
|
||||
type GetB struct {
|
||||
b FromB `inject:"b"`
|
||||
}
|
||||
|
||||
var _GetBSingle *GetB
|
||||
|
||||
// 手动编写代码, 去支持注入
|
||||
func NewGetB() *GetB {
|
||||
if _GetBSingle == nil {
|
||||
_GetBSingle = &GetB{}
|
||||
_GetBSingle.b = func() FromB {
|
||||
var temp = providers.GetBean("b")
|
||||
if bean, ok := temp.(providers.Bean); ok {
|
||||
return bean.GetBean("").(FromB)
|
||||
}
|
||||
return temp.(FromB)
|
||||
}()
|
||||
providers.AfterProvider(_GetBSingle, "a")
|
||||
}
|
||||
return _GetBSingle
|
||||
b FromB `impl:"b"`
|
||||
}
|
||||
|
||||
~~~~
|
||||
Reference in New Issue
Block a user