Java “为什么?”@“路径变量”;无法在SpringBoot中的接口上工作

Java “为什么?”@“路径变量”;无法在SpringBoot中的接口上工作,java,rest,spring-boot,Java,Rest,Spring Boot,简单应用程序-application.java package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args)

简单应用程序-application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}
简单接口-ThingApi.java

package hello;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public interface ThingApi {

  // get a vendor
  @RequestMapping(value = "/vendor/{vendorName}", method = RequestMethod.GET)
  String getContact(@PathVariable String vendorName);

}
简单控制器-ThingController.java

package hello;

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

@RestController
public class ThingController implements ThingApi {

  @Override
  public String getContact(String vendorName) {
    System.out.println("Got: " + vendorName);

    return "Hello " + vendorName;
  }
}
与您最喜爱的SpringBoot初学者家长一起运行此操作。 用GET/vendor/foobar点击它 你会看到: 你好,空

Spring认为“vendorName”是一个查询参数

如果将控制器替换为未实现接口的版本,并将注释按如下方式移动到其中:

package hello;

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

@RestController
public class ThingController {

  @RequestMapping(value = "/vendor/{vendorName}", method = RequestMethod.GET)
  public String getContact(@PathVariable String vendorName) {
    System.out.println("Got: " + vendorName);

      return "Hello " + vendorName;
  }
}
它很好用


那么这是一个特征吗?还是一个bug?

您刚刚错过了工具中的
@PathVariable

@Override
  public String getContact(@PathVariable String vendorName) {
    System.out.println("Got: " + vendorName);

    return "Hello " + vendorName;
  }

因为方法签名中的
@PathVariable
不是继承的,所以需要将其添加到实现方法中。