Golang 依赖注入
1. 手动实现依赖注入
package mainimport "fmt"type A struct {B *B
}type B struct {Inject string
}func main() {var a Ab := B{Inject: "Golang"}fmt.Println(b.Inject)a.B = &bfmt.Println(a.B.Inject)
}
2.开源的依赖注入框架
- 依赖反射实现的运行时的依赖注入(facebook/inject、uber/dig)
- 使用代码生成实现的依赖注入(google/wire)
facebookgo/inject :
facebookgo/inject 实现依赖注入: 类A的实例a是需要被注入的对象,类B的实例b是依赖的组件 将a、b的依赖关系交给第三方(IOC容器)来控制,调用Provide我们不再需要编写复杂的依赖代码(各种参数,实例的互相传入)。执行完Populate后,我们就可以直接使用实例a,其中需要依赖的组件在运行时由IOC容器来注入。
package mainimport ("fmt""net/http""os""github.com/facebookgo/inject"
)// Our Awesome Application renders a message using two APIs in our fake
// world.
type HomePlanetRenderApp struct {// The tags below indicate to the inject library that these fields are// eligible for injection. They do not specify any options, and will// result in a singleton instance created for each of the APIs.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),)
}// Our fake Name API.
type NameAPI struct {// Here and below in PlanetAPI we add the tag to an interface value.// This value cannot automatically be created (by definition) and// hence must be explicitly provided to the graph.HTTPTransport http.RoundTripper `inject:""`
}func (n *NameAPI) Name(id uint64) string {// in the real world we would use f.HTTPTransport and fetch the namereturn "Spock"
}// Our fake Planet API.
type PlanetAPI struct {HTTPTransport http.RoundTripper `inject:""`
}func (p *PlanetAPI) Planet(id uint64) string {// in the real world we would use f.HTTPTransport and fetch the planetreturn "Vulcan"
}func main() {// Typically an application will have exactly one object graph, and// you will create it and use it within a main function:var g inject.Graph// We provide our graph two "seed" objects, one our empty// HomePlanetRenderApp instance which we're hoping to get filled out,// and second our DefaultTransport to satisfy our HTTPTransport// dependency. We have to provide the DefaultTransport because the// dependency is defined in terms of the http.RoundTripper interface,// and since it is an interface the library cannot create an instance// for it. Instead it will use the given DefaultTransport to satisfy// the dependency since it implements the interface:var a HomePlanetRenderApperr := g.Provide(&inject.Object{Value: &a},&inject.Object{Value: http.DefaultTransport},)if err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)}// Here the Populate call is creating instances of NameAPI &// PlanetAPI, and setting the HTTPTransport on both to the// http.DefaultTransport provided above:if err := g.Populate(); err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(1)}// There is a shorthand API for the simple case which combines the// three calls above is available as inject.Populate://// inject.Populate(&a, http.DefaultTransport)//// The above API shows the underlying API which also allows the use of// named instances for more complex scenarios.fmt.Println(a.Render(42))}
Output:Spock is from the planet Vulcan.
uber/dig:
my.iniapp_name = web# possible values: DEBUG, INFO, WARNING, ERROR, FATAL
log_level = DEBUG[mysql]
ip = 127.0.0.1
port = 3306
user = dj
password = 123456
database = awesome[redis]
ip = 127.0.0.1
port = 6379
db = 0
package mainimport ("fmt""github.com/jessevdk/go-flags""go.uber.org/dig""gopkg.in/ini.v1"
)type Option struct {ConfigFile string `short:"c" long:"config" description:"Name of config file."`
}func InitOption() (*Option, error) {var opt Option_, err := flags.Parse(&opt)return &opt, err
}func InitConf(opt *Option) (*ini.File, error) {cfg, err := ini.Load(opt.ConfigFile)return cfg, err
}func PrintInfo(cfg *ini.File) {fmt.Println("App Name:", cfg.Section("").Key("app_name").String())fmt.Println("Log Level:", cfg.Section("").Key("log_level").String())
}func main() {container := dig.New()container.Provide(InitOption)container.Provide(InitConf)container.Invoke(PrintInfo)
}
Golang 依赖注入相关推荐
- golang 依赖注入 dig详解
golang的依赖注入dig 一篇文章带你了解golang依赖注入 dig介绍: dig 库是一个为 go 提供依赖注入 (dependency injection) 的工具包,基于 reflecti ...
- Golang 实现依赖注入
Golang 实现依赖注入 什么是依赖注入 依赖注入就是将实例变量传入到一个对象中去 为何要做依赖注入 让开发者从对项目中大量依赖的创建和管理中解脱出来 控制反转(IoC)与依赖注入(DI) 控制反转 ...
- 【golang】实现依赖注入
依赖注入 一.控制反转是什么? 1.如何理解 Ioc 呢? 2.控制反转和依赖注入 3.小总结 二.依赖注入代码实现 使用过 Java 的一定知道依赖注入这个概念,说到依赖注入就不得不提一下控制 ...
- 依赖注入框架 wire
在上一篇文章当中我们讲到了项目的目录结构,大体上水平切分为了四层,然后再根据需要进行垂直切分,然后由于我们大量的使用到了接口和依赖注入的手段,所以在项目初始化的时候如果手动进行依赖关系的初始化会比较麻 ...
- uber fx_使用uber fx简化依赖注入
uber fx TL; DR (TL;DR) Here you can find the full example on Github.Here you can find a link to Uber ...
- 依赖注入?依赖注入是如何实现解耦的?
如何用最简单的方式解释依赖注入?依赖注入是如何实现解耦的? 第一章:小明和他的手机 从前有个人叫小明 小明有三大爱好,抽烟,喝酒-- 咳咳,不好意思,走错片场了.应该是逛知乎.玩王者农药和抢微信红包 ...
- Spring学习-理解IOC和依赖注入
最近刚买了一本介绍ssm框架的书,里面主要对Mybatis.spring.springmvc和redis做了很多的讲解,个人觉得虽然有的内容我看不懂,但是整体上还是不错的.最近正在学习中,一边学习一边 ...
- 白话spring依赖注入
Spring能有效地组织J2EE应用各层的对象.Action?Service?DAO?,都可在Spring的管理下有机地协调.运行. Spring将各层的对象以松耦合的方式组织在一起,对象与对象之间没 ...
- DI 依赖注入实现原理
深度理解依赖注入(Dependence Injection) 前面的话:提到依赖注入,大家都会想到老马那篇经典的文章.其实,本文就是相当于对那篇文章的解读.所以,如果您对原文已经有了非常深刻的理解,完 ...
最新文章
- tomcat 配置方法
- 删除Windows 系统快捷方式箭头 Delete Windows Shortcuct Arrows
- 全面解读java虚拟机
- 权威解读 | 人类社会正进入DT时代 如何激活生产力?
- python为什么这么小_同样是 Python,怎么区别这么大
- Badboy录制及参数化详细步骤来一波
- 主成分分析法案例_主数据管理第一步——识别主数据
- PostgreSQL 日常数据库维护工作
- CSDN Blog推出专属的离线发布工具 - CSDN剪影
- 【数学建模】评价类算法
- DIY智能小车篇(四):常见问题 BUG汇总
- 对 a = [lambda : x for x in range(3)] 的理解
- 深圳中学因招聘上热搜:名校博士挤破头想进,教学成绩也确实不服不行
- 如何用CSDN发布文章
- OpenCV——图像窗口namedWindow
- 关闭和打开445端口
- MTK平台关于Metadata当中Size的配置
- 专用小交换机(PBX)的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
- 百度富文本编辑器(ueditor)样式错误,回显出现#39、quot
- 基于脉搏波信号和人工智能方法的应用