di

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2019 License: MIT Imports: 17 Imported by: 1

README

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)
}

Documentation

Index

Constants

View Source
const (
	DI     = "di"
	Ignore = "-"
)
View Source
const (
	ErrorType errorDi = iota
	ErrorMissing
	ErrorUnexported
	ErrorTagDotIndex
	ErrorStopIterator
	ErrorUnserialize
)

Variables

This section is empty.

Functions

func ConfigLoad

func ConfigLoad(content string, serializer Serializer) error

func ConfigLoadFile

func ConfigLoadFile(path string, ct Serializer) error

func ConfigLoadReader

func ConfigLoadReader(reader io.Reader, ct Serializer) error

func Put

func Put(water Water)

func PutWithName

func PutWithName(water Water, name string)

func RegisterPlugin

func RegisterPlugin(lifecycle Lifecycle, p Plugin)

func Start

func Start()

func TomlLoad

func TomlLoad(content string) error

func TomlLoadFile

func TomlLoadFile(path string) error

func TomlLoadReader

func TomlLoadReader(reader io.Reader) error

Types

type BeforeInitPlugin

type BeforeInitPlugin struct {
}

func (*BeforeInitPlugin) Load

func (b *BeforeInitPlugin) Load(path string, ice Ice)

func (*BeforeInitPlugin) Prefix

func (b *BeforeInitPlugin) Prefix() string

func (*BeforeInitPlugin) Priority

func (b *BeforeInitPlugin) Priority() int

type BeforeInitType

type BeforeInitType interface {
	BeforeInit() interface{}
}

type Configurator

type Configurator func(Container)

func WithLogger

func WithLogger(logger *log.Logger) Configurator

func WithLoggerVerbose

func WithLoggerVerbose(verbose bool) Configurator

type Container

type Container interface {
	// 装载配置
	Configure(configurators ...Configurator) Container

	// 注册插件 根据lifecycle决定在哪一层被初始化
	RegisterPlugin(lifecycle Lifecycle, p Plugin)

	// 放入iceMap, 根据插件来注入
	PutIce(ice Ice)

	// 放入cupMap,water名字由容器的默认规则来决定, water必须是指针类型
	Put(water Water)

	// 放入cupMap,water名字自定义
	PutWithName(water Water, name string)

	// 获取除了excludedNames之外 dropType类型的cup
	GetCup(dropType reflect.Type, excludedNames ...string) (h *Cup)

	// 根据name获取 dropType类型的cup
	GetCupWithName(name string, dropType reflect.Type) (h *Cup)

	// 根据name获取 water
	GetWaterWithName(name string) Water

	// 深度遍历cupMap
	EachCup(cupFunc CupFunc)

	// 开始根据生命周期初始化
	Start()
}

func Configure

func Configure(configurators ...Configurator) Container

func NewContainer

func NewContainer(configurators ...Configurator) Container

type Cup

type Cup struct {
	Water        Water
	Class        reflect.Type  // classInfo.kind() Ptr
	Value        reflect.Value // Lookup.kind() Ptr
	Container    Container
	Dependencies []*Cup
}

type CupFunc

type CupFunc func(name string, cup *Cup) bool

break if return true

type CupSet

type CupSet map[*Cup]struct{}

type Ice

type Ice interface {
	// 获取 容器
	Container() Container
	// 获取 父级cup
	ParentCup() *Cup
	Value() reflect.Value
	Type() reflect.Type
	LoadPlugin(p Plugin)
	Prefix() string
}

type Init

type Init interface {
	Init()
}

type Lifecycle

type Lifecycle int
const (
	BeforeInit Lifecycle = iota
	TheInit
	BeforeReady
	TheReady
)

func (Lifecycle) Type

func (l Lifecycle) Type() reflect.Type

type Plugin

type Plugin interface {
	Load(path string, ice Ice)
	Prefix() string
	Priority() int
}

type Plugins

type Plugins []Plugin

func (Plugins) Len

func (pl Plugins) Len() int

func (Plugins) Less

func (pl Plugins) Less(i, j int) bool

func (Plugins) Swap

func (pl Plugins) Swap(i, j int)

type Ready

type Ready interface {
	Ready()
}

type Serializer added in v0.3.0

type Serializer interface {
	Unmarshal(data []byte, v interface{}) error
	Marshal(v interface{}) ([]byte, error)
}
var (
	JSON Serializer = new(jsonSerializer)
	TOML Serializer = new(tomlSerializer)
	YAML Serializer = new(yamlSerializer)
)

type Water

type Water interface{}

func GetWithName

func GetWithName(name string) Water

Directories

Path Synopsis
samples
get
put

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL