【问题标题】:Why does "@PathVariable" fail to work on an interface in SpringBoot [duplicate]为什么“@PathVariable”无法在 Spring Boot 中的接口上工作 [重复]
【发布时间】:2017-12-02 13:48:19
【问题描述】:

简单的应用程序 - 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 点击它 你会看到: 你好空

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;
  }
}

它工作正常。

那么这是一个功能吗?还是错误?

【问题讨论】:

  • 因为方法签名中的@PathVariable没有被继承,所以需要添加到你的实现方法中。

标签: java rest spring-boot


【解决方案1】:

你只是在你的工具中错过了@PathVariable

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

    return "Hello " + vendorName;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2016-04-09
    • 2019-06-19
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多