gpt4 book ai didi

java - 为什么 "@PathVariable"无法在 Spring Boot 中的接口(interface)上工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:06 24 4
gpt4 key购买 nike

<分区>

简单应用-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);

}

简单的 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 starter-parent。用 GET/vendor/foobar 打它你会看到:你好空

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

如果您将 Controller 替换为未实现接口(interface)的版本并将注释移入其中,如下所示:

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

它工作正常。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com