Ошибка создания компонента с именем requestMappingHandlerMapping - SpringBoot - PullRequest
2 голосов
/ 09 января 2020

Я получаю следующую ошибку во время выполнения.

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'scrcrdsController' method 
com.mastercard.qualityScore.controllers.ScrcrdsController#getSummary(String)
to {GET /api/v1/scrcrds/{id}}: There is already 'scrcrdsController' bean method
com.mastercard.qualityScore.controllers.ScrcrdsController#get(String) mapped.

Мне нужно создать новый API, который выбирает все оценки конкретного идентификатора или, возможно, комбинацию двух идентификаторов. Как я могу это исправить? Пожалуйста, помогите.

Мой контроллер выглядит следующим образом-

@RestController
@RequestMapping("/api/v1/scrcrds")
public class ScrcrdsController {
    @Autowired
    private ScrcrdRepository scrcrdRepository;

    //list all scrcrd records
    @GetMapping
    public List<Scrcrd> list() {
        return scrcrdRepository.findAll();
    }

    //get summary  of an employee
    @GetMapping(value = "{id}")
    public List<Scrcrd> getSummary(@PathVariable String id) {
        return  scrcrdRepository.findAllById(Collections.singleton(id));
    }

    //get scrcrd record by id
    @GetMapping(value = "{id}")
    public Scrcrd get(@PathVariable String id) {
        return scrcrdRepository.getOne(id);
    }

    //create a new scrcrd record
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)  //to get  201 response instead of 200
    public Scrcrd create(@RequestBody final Scrcrd scrcrd) {
        return scrcrdRepository.saveAndFlush(scrcrd);
    }

    //delete a scrcrd record
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String id) {
        //Also need to check for children records before deleting
        scrcrdRepository.deleteById(id);
    }

    //update a scrcrd record
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public Scrcrd update (@PathVariable String id, @RequestBody Scrcrd scrcrd) {
        //because this is a PUT, we expect all attributes to be passed in. A PATCH would only need what attribute is being modified
        //TODO: Add validation that all attributes are passed in, otherwise return a 400 bad payload
        Scrcrd existingScrcrd = scrcrdRepository.getOne(id);
        //attributes of emp are copied to existingScrcrd, emp_id, mgr_id, mgr_scr_dt and type_nam is not to be changed
        BeanUtils.copyProperties(scrcrd, existingScrcrd   , "emp__id", "mgr_id", "mgr_scr_dt", "type_nam");
        return scrcrdRepository.saveAndFlush(existingScrcrd);
    }
}

1 Ответ

2 голосов
/ 09 января 2020

Вы создали два метода с одинаковым GET-запросом и конечной точкой, т.е. /api/v1/scrcrds/{id}. Решение состоит в том, чтобы изменить конечную точку для одного из ваших запросов: либо * getSummary (), либо get () . Здесь я изменил конечную точку для getSummary().

    //get summary  of an employee
    @GetMapping(value = "summary/{id}")
    public List<Scrcrd> getSummary(@PathVariable String id) {
        return  scrcrdRepository.findAllById(Collections.singleton(id));
    }

    //get scrcrd record by id
    @GetMapping(value = "{id}")
    public Scrcrd get(@PathVariable String id) {
        return scrcrdRepository.getOne(id);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...