rest控制器在基本路径上返回404

7ivaypg9  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(316)

我正在尝试用springboot制作restapi。当我这么做的时候”http://localhost:8080/foo/“,我得到我想要的,但当我使用”http://localhost:8080/api/foo/“,我得到404错误。我有其他控制器,几乎是一样的,他们工作得很好。我尝试过使用@requestmapping,但没有任何改变。应用程序属性:

.
.
spring.data.rest.base-path=/api

控制器:

@RestController
public class FooController {
    @Autowired
    private FooRepository fooRepository;

    @GetMapping("/foo")
    public List<Foo> retreiveAllFoos(){
        return fooRepository.findAll();
    }

    @GetMapping("/foo/{id}")
    public Foo retrieveFoo(@PathVariable int id) {
        Optional<Foo> foo = fooRepository.findById(id);
        return foo.get();
    }

    @DeleteMapping("/foo/{id}")
    public void deleteFoo(@PathVariable int id) {
        fooRepository.deleteById(id);
    }

    @PostMapping("/foo")
    public ResponseEntity<Object> createFoo(@RequestBody Foo foo){
        Foo savedFoo = fooRepository.save(foo);

        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(savedFoo.getId()).toUri();
        return ResponseEntity.created(location).build();
    }

    @PutMapping("/foo/{id}")
    public ResponseEntity<Object> updateFoo(@RequestBody Foo foo, @PathVariable int id){
        Optional<Foo> fooOptional = fooRepository.findById(id);

        if(!fooOptional.isPresent()) {
            return ResponseEntity.notFound().build();
        }

        foo.setId(id);

        fooRepository.save(foo);

        return ResponseEntity.noContent().build();
    }
}
nwwlzxa7

nwwlzxa71#

正确的属性是 spring.data.rest.basePath 所以你想在 application.properties :

spring.data.rest.basePath=/api

看到了吗https://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-已启动。更改-base-uri

相关问题