golang 依赖注入

栏目: Go · 发布时间: 5年前

内容简介:使用facebook的三方库:

使用facebook的三方库: https://github.com/facebookgo/inject

type C struct{
    B  *B  `inject:""`
}
type B struct{
    A   *A  `inject:""`//这里会根据注入对象的Name字段有选择的进行注入
}
type A struct{
    Name    string
}
var injectGraph inject.Graph
func main() {
    a := A{
        name: "hello",
    }
    a2 := A{
        Name: "hello2",
    }
    c := C{}
    err := injectGraph.Provide(//对象提供者
        &inject.Object{Value: &a},
        &inject.Object{Name: "这里可以给对象一个自定义命名", Value: &a2},
        &inject.Object{Value: &c},//这个也需要
    )
    if err != nil{}
    err = injectGraph.Populate()//填充对象到使用了inject标签的结构体字段中
    if err != nil{}
    fmt.Println(c.B.A.Name)
}
// 通过injectGraph.Objects()可以获取所有设置了Name的待填充对象
func GetObject(name string) interface{} {
    for _, o := range injectGraph.Objects() {
        if o.Name == name {
            return o.Value
        }
    }
    return nil
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Tangled Web

The Tangled Web

Michal Zalewski / No Starch Press / 2011-11-26 / USD 49.95

"Thorough and comprehensive coverage from one of the foremost experts in browser security." -Tavis Ormandy, Google Inc. Modern web applications are built on a tangle of technologies that have been de......一起来看看 《The Tangled Web》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具