DI(依赖注入)Golang 实现 😋

🔥 快速入门内容目录


功能特性

快速开始

下载

$ go get github.com/ljun20160606/di

创建一个main文件

package main

import (
	"github.com/ljun20160606/di"
)

func init() {
	ducks := new(Ducks)
	di.Put(ducks)
}

type Duck interface {
	Quack()
}

type Ducks struct {
	Duck Duck `di:"*"`
}

type DarkDuck struct{}

func (*DarkDuck) Quack() {
	panic("implement me")
}

func main() {
	duck := new(DarkDuck)
	di.Put(duck)

	di.Start()

	ducks := di.GetWithName("main.Ducks").(*Ducks)
	if ducks.Duck.(*DarkDuck) != duck {
		panic("error")
	}
}

内容

DI

放入容器

package main

import "github.com/ljun20160606/di"

func main() {
	name := "duck"
	// 只支持指针类型
	di.Put(&name)
}

自动注入

di:"*"代表根据类型自动注入

package main

import (
	"github.com/ljun20160606/di"
)

type Duck struct {
	Name *string `di:"*"`
}

func main() {
	name := "duck"
	duck := Duck{}
	di.Put(&name)
	di.Put(&duck)
	// 开始依赖注入
	di.Start()
}

主动从容器中获取

name可以根据日志获得,规则为package+typeName

package main

import (
	"fmt"
	"github.com/ljun20160606/di"
)

func main() {
	name := "duck"
	// 只支持指针类型
	di.Put(&name)
	withName := *(di.GetWithName("string").(*string))
	fmt.Println(name == withName)
}

加载配置

config插件的关键字为#,可以自定义插件详细看文件plugin_config.go,共支持di.JSON di.YAML di.TOML
import (
	"fmt"
	"github.com/ljun20160606/di"
)

type Duck struct {
	Name string `di:"#.name"`
}

func main() {
	di.ConfigLoad(`name: duck`, di.YAML)
	//di.ConfigLoadFile("path", di.YAML)
	//di.ConfigLoadReader(reader, di.YAML)
	duck := Duck{}
	di.Put(&duck)
	di.Start()

	fmt.Println(duck.Name == "duck")
}

还支持根据前缀映射配置,如下取前缀为test.properties内的配置映射到对应的PrefixProperties结构体中

import (
	"fmt"
	"github.com/ljun20160606/di"
)

type Prefix struct {
	// 如果希望使用相同的PrefixProperties可以写为*PrefixProperties
	// 否则只会拷贝结构体本身
	// 如果想映射整个配置可以写`di:"#.{}"`
	Properties PrefixProperties `di:"#.{test.properties}"`
}

type PrefixProperties struct {
	Type        string
	Value       string
	SnakeFormat string `yaml:"snake_format"`
}

func main() {
    di.ConfigLoad(`
test:
  properties:
    type: prefix
    value: test
    snake_format: snake`, YAML)

    prefix := Prefix{}
    di.Put(&prefix)

    fmt.Println(prefix.Properties)
}