【问题标题】:Spring Boot Controllers not working 404 errorSpring Boot 控制器不工作 404 错误
【发布时间】:2020-10-11 17:36:26
【问题描述】:

我正在开发一个 Spring Boot 应用程序,但我的端点根本不工作。我得到下一个问题:

{
    "timestamp": "2020-06-21T21:12:39.716+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/prduct/jjjk"
}

这是我项目的结构:

如您所见,控制器在同一路径中是 Application 类的子包,但未扫描。

package com.mercadolibre.mutants.controllers;

import com.mercadolibre.mutants.entities.Product;
import com.mercadolibre.mutants.repositories.ProductRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

  @Autowired
  ProductRepository productRepository;

  @GetMapping("/prduct/{id}")
  public ResponseEntity<Product> findById(@PathVariable("id") String id) {
    Optional<Product> p = productRepository.findById(id);
    return ResponseEntity.ok(p.orElse(null));
  }

  @PostMapping(value = "/products", consumes = "application/json")
  public ResponseEntity<Product> save(@RequestBody Product p) {
    Product result = productRepository.save(p);
    return ResponseEntity.ok(result);
  }
}

这是我的应用程序类:

package com.mercadolibre.mutants;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.mercadolibre.mutants")
public class MutantsApplication {

    public static void main(String[] args) {
        SpringApplication.run(MutantsApplication.class, args);
    }

}

我无法确定问题或我缺少什么。有什么想法吗?

【问题讨论】:

  • 尝试在ProductController上方添加@RequestMapping("/")
  • 只要确保/prduct/{id} 是故意的,而不是/product/{id}。如果是,您在到达端点时会相应地使用它。

标签: java spring-boot controller component-scan


【解决方案1】:

/product/{id}ProductController.java中的rest api中删除产品前的斜杠

将其更改为product/{id} 并再次运行。

【讨论】:

猜你喜欢
  • 2018-10-04
  • 2016-09-17
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 2019-08-14
  • 2015-07-31
相关资源
最近更新 更多