无法在 RestController 中使用 @DeleteMapping 绑定 id 以从列表中删除项目
unable to bind the id using @DeleteMapping in RestController to delete an item from the list
我正在尝试获取此列表中的数据以使用 Postman 处理删除请求:
我创建了这个列表:
@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
您可以尝试使用 @PostConstruct
注释(参见 the official reference)
将列表初始化从构造函数移至 init
方法。
@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保证线程安全支持。
我正在尝试获取此列表中的数据以使用 Postman 处理删除请求:
我创建了这个列表:
@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
您可以尝试使用 @PostConstruct
注释(参见 the official reference)
将列表初始化从构造函数移至 init
方法。
@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保证线程安全支持。