Go-Spring 入门篇(五)

序言

示例代码 github.com/acrossmountain/gs-demo

上章 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":"上传文件成功"}

这样我们就成功完成了 controlerservice 解耦。

官网及交流

Go-Spring 官网
Github

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!