0

I use Spring Data REST with spring.data.rest.base-path property set as /api. If I extend CrudRepository for User entity, I'll have an /api/users endpoint available in my RESTful service. Now assume, I want to add a custom endpoint to /api/users like this:

@RepositoryRestController
public class UserController {

    @PatchMapping(path = "/users/{username}/update", produces = "application/hal+json")
    @ResponseStatus(HttpStatus.OK)
    public EntityModel<User> updateUser(@PathVariable String username, @RequestBody User user) {
        // some update logic here ... 
        return EntityModel.of(user);
    }

}

The path element in @PatchMapping annotation still contains explicit hardcoded /users part in it. Is there any programmatic way to replace it with the path variable to the collection resource of User type which is managed by Spring Data REST?

escudero380
  • 536
  • 2
  • 7
  • 25
  • Well there is the `@RequestMapping` at the class level. But I'm not quite sure that is what you are looking for. https://stackabuse.com/spring-annotations-requestmapping-and-its-variants/ **Edit:** using `${...}` you can use placeholders which map to local properties (among others). https://stackoverflow.com/a/31904513/13211030 – Fullslack Sep 23 '20 at 10:57
  • Either in `@RequestMapping` or in `@PatchMapping` I need to somehow replace `/users` part with something like `RepositoryEntityLinks.linkFor(User.class).toString()` – escudero380 Sep 23 '20 at 11:09
  • That looks impossible because the mappings are initialized during startup. Therefor you can only load it from property sources. Also isn't the User.class always going to be converted to a /user endpoint, and thus why the need for a dynamic mapping? – Fullslack Sep 23 '20 at 11:17
  • It's just the matter of refactoring. If I rename `User` into `Person`, I'll have manually replace `/users` with `/persons` for every `@GetMapping`, `@PostMapping`, etc... – escudero380 Sep 23 '20 at 11:20
  • Using placeholder like `"${users.path}"` and defining a special local property for this would be an option. Although, I will have to annotate my `CrudRepository` with `@RepositoryRestResource(path = "${users.path")` as well for consistency... Still, in search for better option. – escudero380 Sep 23 '20 at 11:21

0 Answers0