为什么“@PathVariable”无法在SpringBoot中的接口上运行

时间:2017-06-29 02:16:56

标签: 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) {
    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 starter-parent运行此命令。 用GET / vendor / foobar点击它 你会看到: 你好null

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?

1 个答案:

答案 0 :(得分:1)

您在工具中错过了@PathVariable

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

    return "Hello " + vendorName;
  }