无法在RestController中使用@DeleteMapping绑定ID以从列表中删除项目

问题描述 投票:0回答:1

我正在尝试获取此列表中的数据以使用邮递员处理删除请求:

我已创建此列表:

@Service
public class SchoolService {

    private List<School> SchoolLists = new ArrayList<School>();

    public SchoolService() {
        System.out.println("Service School is created");

        SchoolLists.add(new School(1, "The white hands Group");

        SchoolLists.add(new School(2,"The Yellow Hands"));

在这里,我试图通过id从列表中删除一个元素:

public void deleteSchool(Integer id){
        SchoolLists.remove(id);

        throw new RuntimeException("School not found for given ID = " + id);
    }

这是我在RestController中处理删除请求的方式:

@RestController
public class SchoolController {

@Autowired
private SchoolService schoolService;

@DeleteMapping("/school/{id}")
    public void deleteSchool(@PathVariable Integer id )
    {
        SchoolService.deleteSchool(id);
    }

这是我在邮递员中遇到的错误:enter image description here

这是删除异常后出现的错误:

enter image description here

spring-boot postman spring-restcontroller
1个回答
0
投票
您可以尝试使用@PostConstruct批注(请参见the official reference

@Service public class SchoolService { private List<School> SchoolLists = new CopyOnWriteArrayList<School>(); @PostConstruct public init() { System.out.println("Service School is created"); SchoolLists.add(new School(1, "The white hands Group"); SchoolLists.add(new School(2,"The Yellow Hands"));

使用CopyOnWriteArrayList来确保线程安全支持。
© www.soinside.com 2019 - 2024. All rights reserved.