golang-wire依赖注入示例

当需要初始化的各个函数带有依赖性质的时候,此时就是wire发挥作用的时刻
工作目录结构:
golang-wire依赖注入示例_第1张图片
app.go

package app

import "fmt"

type Message struct {
	msg string
}
type Greeter struct {
	Message Message
}
type Event struct {
	Greeter Greeter
}

// NewMessage Message的构造函数
func NewMessage(msg string) Message {
	return Message{
		msg: msg,
	}
}

// NewGreeter Greeter构造函数
func NewGreeter(m Message) Greeter {
	return Greeter{Message: m}
}

// NewEvent Event构造函数
func NewEvent(g Greeter) Event {
	return Event{Greeter: g}
}
func (e Event) Start() {
	msg := e.Greeter.Greet()
	fmt.Println(msg)
}
func (g Greeter) Greet() Message {
	return g.Message
}

wire.go

// +build wireinject
// The build tag makes sure the stub is not built in the final build.

package app

import "github.com/google/wire"


// InitializeEvent 声明injector的函数签名
func InitializeEvent(msg string) Event {
	wire.Build(NewEvent, NewGreeter, NewMessage)
	return Event{} //返回值没有实际意义,只需符合函数签名即可
}

此时在app目录下输入wire即可生成wire_gen.go
在这里插入图片描述
wire_gen.go

// Code generated by Wire. DO NOT EDIT.

//go:generate go run github.com/google/wire/cmd/wire
//go:build !wireinject
// +build !wireinject

package app

// Injectors from wire.go:

// InitializeEvent 声明injector的函数签名
func InitializeEvent(msg string) Event {
	message := NewMessage(msg)
	greeter := NewGreeter(message)
	event := NewEvent(greeter)
	return event
}

cmd目录:
main.go

func main() {
	event := app.InitializeEvent("hello_world")

	event.Start()
}

在这里插入图片描述

你可能感兴趣的:(golang,golang,开发语言,后端)