Why does “@PathVariable” fail to work on an interf

2019-02-25 10:46发布

This question already has an answer here:

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

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

}

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

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

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

It works fine.

So is this a feature? Or a bug?

1条回答
手持菜刀,她持情操
2楼-- · 2019-02-25 11:06

You just missed @PathVariable in your implement

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

    return "Hello " + vendorName;
  }
查看更多
登录 后发表回答