为什么“@ PathVariable”无法在SpringBoot中的接口上工作 [英] Why does "@PathVariable" fail to work on an interface in SpringBoot

查看:233
本文介绍了为什么“@ PathVariable”无法在SpringBoot中的接口上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单应用程序 - Application.java

Simple application - 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

Simple interface - 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

Simple controller - 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
命中它你会看到:
Hello null

Run this, with your favorite SpringBoot starter-parent. Hit it with GET /vendor/foobar and you will see: Hello null

Spring认为'vendorName'是一个查询参数!

Spring thinks that 'vendorName' is a query parameter!

如果用不实现接口的版本替换控制器并将注释移入其中,如下所示:

If you replace the controller with a version that does not implement an interface and move the annotations into it like so:

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

一切正常。

这是一个功能吗?或者一个错误?

So is this a feature? Or a bug?

推荐答案

您的工具中刚刚错过 @PathVariable

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

    return "Hello " + vendorName;
  }

这篇关于为什么“@ PathVariable”无法在SpringBoot中的接口上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆