Go-Spring 入门篇(五)
序言
上章 Go-Spring 入门篇(四)的代码已经很完整了,但是 controller
直接导入 service
造成对逻辑的直接依赖,这样会造成很高的耦合。
本章我们使用 interface
来做到解除依赖,这样不仅解决的导入的问题也能够快速的替换 serivce
的实现。
types/services.go
将上传的服务抽象称为接口。
package types
import "io"
type FileProvider interface {
PutObject(name string, r io.Reader, size int64) (string, error)
ExistsObject(name string) bool
}
controllers/upload/upload.go
然后把 *filesystem.Service
类型替换为 types.FileProvider
即可,spring-boot 会自动匹配接口对应的实例。
type Controller struct {
FileService types.FileProvider `autowire:""`
}
services/file/file.go
package services
import (
// ...
"learn/types"
)
func init() {
// 需要手动声明支持的接口对象
gs.Object(new(filesystem.Service)).
Export((*types.FileProvider)(nil))
}
重新运行 go run main.go
并测试,功能正常。
$ curl -F "file=@./1.jpg" http://127.0.0.1:8080/upload
$ {"code":0,"data":{"url":"temp/1.jpg"},"msg":"上传文件成功"}
这样我们就成功完成了 controler
对 service
解耦。
官网及交流
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: