How to convert RequestHeader to custom object in Spring
Basically I implemented it with the suggestion from the comments. Below is an example:
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
@RestController
public class SimpleController {
@GetMapping("/user")
public String greeting(@RequestHeader(name = "userId") User user) {
return "Hey, " + user.toString();
}
}
public class User {
private String id;
private String firstName;
private String lastName;
...
}
And then we'll create a converter:
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class UserFromHeaderConverter implements Converter<String, User> {
@Override
public User convert(final String userId) {
// fetch user from the database etc.
final User user = new User();
user.setId(userId);
user.setFirstName("First");
user.setLastName("Last");
return user;
}
}
To test it, please execute: curl --header "userId: 123" localhost:8080/user
Result would be: Hey, User{id='123', firstName='First', lastName='Last'}
Versions:
spring-boot:2.0.3
spring-web:5.0.7