vendredi 16 septembre 2022

Create a convenience decorator to generate a Controller from a function using BeanPostProcessor?

I'm looking to write a decorator that takes a very simple function and wraps it inside a controller.

@AutoGetMapping("/users/{id}")
    public ResponseEntity<User> getById(@PathVariable long id) {
        Optional<User> user = userService.getById(id);
        if (user.isPresent()) {
            return new ResponseEntity<>(user.get(), HttpStatus.OK);
        } else {
            throw new RecordNotFoundException();
        }
    }

gets transformed to

@RestController
public class UserController {
 
    @Autowired
    UserService userService;
 
    @GetMapping("users")
    public ResponseEntity<List<User>> getAll() {
        return new ResponseEntity<>(userService.getAll(), HttpStatus.OK);
    }
 
    @GetMapping("users/{id}")
    public ResponseEntity<User> getById(@PathVariable long id) {
        Optional<User> user = userService.getById(id);
        if (user.isPresent()) {
            return new ResponseEntity<>(user.get(), HttpStatus.OK);
        } else {
            throw new RecordNotFoundException();
        }
    }
}

(maybe even the service layers).

I'm just looking for a place to start. I think im making a mistake in trying to use BeanPostProcessor and BeanDefinitionRegistryPostProcessor to do this. Can someone point me in the right direction on how to start doing this ?

Aucun commentaire:

Enregistrer un commentaire