繁体   English   中英

Spring Boot 是否可以使用接口作为控制器参数并让 spring 使用它的实现来实例化它?

[英]Spring Boot Is it possible to use an interface as controller parameter and let spring use it's implementation to instantiate it?

@RestController
@RequestMapping("/api/test")
class TestController {

    @GetMapping
    fun findSomething(params: MyInterface) {
        when (params) {
            is FirstImplementation -> doSomeThing()
            is SecondImplementation -> doSomeThing()
        }
    } 
}

sealed interface MyInterface

class FirstImplementation(
    val a: String,
    val b: Int,
) : MyInterface

class SecondImplementation(
    val b: Int,
    val c: String,
) : MyInterface

我是这样尝试的,但是我得到了一个自动生成的接口的 aop 代理,所以在表达式时失败了..

通常,在 Spring MVC 中定义控制器时,我们会用各种指定请求的注解来装饰其方法:端点的 URL、HTTP 请求方法、路径变量等。

如果我们向控制器添加 Web 请求注释,它们将优先于接口的注释。 换句话说,Spring 以类似于 Java 处理继承的方式解释控制器接口。

有关更多信息,请参阅此博客文章https://www.baeldung.com/spring-interface-driven-controllers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM