Reputation: 3015
I have one Entity User
in my app. Spring Data REST provides me standard endpoints:
`GET` /user
`GET` /user/<id>
`POST` /user
`PUT` /user
`PATCH` /user
`DELETE` /user/<id>
I need to override default behaviour of DELETE
endpoint not changing endpoint url /user
. If I add following to my controller:
@Controller
@RequestMapping("/user")
public class User {
@DeleteMapping("/{id}")
@CrossOrigin
public ResponseEntity<?> delete(@PathVariable("id") final String id) {
userService.delete(id); // in service I remove user with other
return ResponseEntity.ok().build();
}
// other custom endpoints
}
I found that other standard REST endpoints do not work - I always receive 405 error. So, my question is - how to customize this endpoint and not affect other endpoints? (I know how to do this in @RepositoryEventHandler
- but I should avoid this in my case)
Upvotes: 1
Views: 1058
Reputation: 30309
Did you read this: Overriding Spring Data REST Response Handlers?
@RepositoryRestController
@RequestMapping("/users") // or 'user'? - check this...
public class UserController {
@Autoware
private UserRepo userRepo;
@Transactional
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable("id") String id) { // or Long id?..
// custom logic
return ResponseEntity.noContent().build();
}
}
But if you want to add extra business logic to delete process you even don't need to implement a custom controller, you can use a custom event handler:
@Component
@RepositoryEventHandler(User.class)
public class UserEventHandler {
@Autoware
private UserRepo userRepo;
@BeforeDeleteEvent
public void beforeDelete(User u) {
//...
if (/* smth. wrong */) throw new MyException(...);
}
}
Upvotes: 4