Skip to content

Commit

Permalink
add: 接口注入
Browse files Browse the repository at this point in the history
  • Loading branch information
cyz-home committed Aug 16, 2024
1 parent 03a1314 commit e1f330f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 24 deletions.
13 changes: 12 additions & 1 deletion console/commands/bean.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
}
}
Expand Down Expand Up @@ -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 {
Expand Down
25 changes: 2 additions & 23 deletions docs/bean.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}

~~~~

0 comments on commit e1f330f

Please sign in to comment.