zoukankan      html  css  js  c++  java
  • go 依赖注入

    在go语言中没有类以及构造函数的说法,只有类似的结构体:

    package main
    
    import "fmt"
    
    type Books struct {
       title string
       author string
       subject string
       book_id int
    }
    
    
    func main() {
    
        // 创建一个新的结构体
        fmt.Println(Books{"Go 语言", "www.runoob.com", "Go 语言教程", 6495407})
    
        // 也可以使用 key => value 格式
        fmt.Println(Books{title: "Go 语言", author: "www.runoob.com", subject: "Go 语言教程", book_id: 6495407})
    
        // 忽略的字段为 0 或 空
       fmt.Println(Books{title: "Go 语言", author: "www.runoob.com"})
    }

    依赖注入实现:https://github.com/facebookarchive/inject

    简介:Package inject provides a reflect based injector. 基于反射实现

    实例:

    package main
    
    import (
        "fmt"
        "net/http"
        "os"
    
        "github.com/facebookgo/inject"
    )
    
    type HomePlanetRenderApp struct {
        NameAPI   *NameAPI   `inject:""`
        PlanetAPI *PlanetAPI `inject:""`
    }
    
    func (a *HomePlanetRenderApp) Render(id uint64) string {
        return fmt.Sprintf(
            "%s is from the planet %s.",
            a.NameAPI.Name(id),
            a.PlanetAPI.Planet(id),
        )
    }
    
    type NameAPI struct {
        // 接口类型 不能被自动创建 所以需要被明确地提供
        HTTPTransport http.RoundTripper `inject:""`
    }
    
    func (n *NameAPI) Name(id uint64) string {
        return "Spock"
    }
    
    type PlanetAPI struct {
        HTTPTransport http.RoundTripper `inject:""`
    }
    
    func (p *PlanetAPI) Planet(id uint64) string {
        return "Vulcan"
    }
    
    func main() {
        var g inject.Graph
        var a HomePlanetRenderApp
        err := g.Provide(
            &inject.Object{Value: &a},
            &inject.Object{Value: http.DefaultTransport},
        )
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    
        // creating instances
        if err := g.Populate(); err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
    
        fmt.Println(a.Render(42))
        fmt.Println(a.NameAPI.HTTPTransport == a.PlanetAPI.HTTPTransport)
    }
  • 相关阅读:
    File初识和练习
    图床
    servlet
    css伪类及伪元素用法
    css中的定位position
    块级元素与行级元素
    清除浮动
    CSS浮动
    fastjson 1.2.6以下版本 解析字符串末尾出现/x会陷入死循环 报oom异常
    记一次select2赋值动态数组的坑
  • 原文地址:https://www.cnblogs.com/hepeng/p/12788327.html
Copyright © 2011-2022 走看看