Spring 引导 RestController 不能与实现接口的 类 一起工作

Spring boot RestController won't work with classes which implements an interface

我正在尝试实现 Springboot REST api。我定义 @RestController 的 class 似乎不起作用。我有一个名为 MyService 的 class,它实现了所有抽象方法。我在 class 声明的顶部添加了 @RestController 注释,并为我需要从 rest 调用中调用的方法添加了 @RequestMapping 注释。但这不起作用。我用 class 尝试了这个,它没有实现任何接口并且工作正常。

这是代码

package com.my.service;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyService implements MyServiceInterface{

    @Override
    @RequestMapping("/age")
    public String Age() {
        return  "24";
    }
}

MyServiceInterface的代码

public interface MyServiceInterface {
    public String Age();
}

我从邮递员那里得到的错误是

{"timestamp":1489688505136,"status":404,"error":"Not Found","message":"No message available","path":"/age"}

找到了!似乎添加 @Override 是我设法通过为非覆盖方法添加 @RequestMapping("/age") 使其工作的原因。 喜欢

@RequestMapping("/age")
public String Age() {
    return  "24";
}

我刚刚在合同测试期间遇到了同样的问题。我很困惑,因为还有其他一些 @RestController 实现了它们的接口并且它们被正确映射。

然后我以生产模式启动我的应用程序,并意识到控制器已正确映射。好奇怪!

正要删除接口,突然想到Spring代理。不知道为什么它出现在我的脑海里。然后我检查了我的 src/test/application.properties 并意识到它有这个 属性 spring.aop.proxy-target-class=false。我删除了它,现在一切正常。

现在我明白了。 src/main/application.properties 没有 属性。所以 Spring 代理方法是在生产模式下的默认方法。另一方面,测试使用的是另一种 Spring 代理方法。我要和我的队友核实为什么它在那里。我相信默认的 Spring 代理方法应该是可以使用的方法。