Video in progress
How do you write a HandlerMethodArgumentResolver to automatically supply the current tenant or user to a controller parameter?
You implement HandlerMethodArgumentResolver: supportsParameter says which parameter it handles, and resolveArgument builds the value from the request. Then you register it through WebMvcConfigurer.addArgumentResolvers.
📖 Answer
In every controller method, reading the header and looking up the tenant gets repeated. Instead:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentTenant {}
@Component
class TenantArgumentResolver implements HandlerMethodArgumentResolver {
private final TenantRepository tenants;
TenantArgumentResolver(TenantRepository tenants) { this.tenants = tenants; }
@Override
public boolean supportsParameter(MethodParameter p) {
return p.hasParameterAnnotation(CurrentTenant.class)
&& p.getParameterType().equals(Tenant.class);
}
@Override
public Object resolveArgument(MethodParameter p, ModelAndViewContainer mav,
NativeWebRequest req, WebDataBinderFactory bf) {
String code = req.getHeader("X-Tenant");
if (code == null) throw new MissingTenantException();
return tenants.findByCode(code).orElseThrow(() -> new UnknownTenantException(code));
}
}
@Configuration
class WebConfig implements WebMvcConfigurer {
private final TenantArgumentResolver resolver;
WebConfig(TenantArgumentResolver r) { this.resolver = r; }
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
list.add(resolver);
}
}
In the controller: List<OrderDto> list(@CurrentTenant Tenant t).
What to watch for:
- Custom resolvers are checked after Spring's built-in ones. So you can't "override" something of a
@RequestBodyor@RequestParamkind this way. - The result of
supportsParameteris cached, butresolveArgumentruns on every request. If you hit the database here, think about caching. - An exception inside the resolver reaches
@ControllerAdvice, so you can return a clear 400. - For the current user, Spring Security already has
@AuthenticationPrincipal; you don't have to write your own.
Sign up to mark studied questions and save your progress.