WebMvcConfigurer
A bean that mixes in WebMvcConfigurer adds things to the controllers: interceptors, CORS rules by path, resolvers for parameters of your own types, and more mappings of static resources. Override only the methods you need; the others do nothing.
Why
The starter sets up the controllers with no interceptors, no global CORS rules and only its own argument resolvers. Each application needs a few additions of its own, and they should live in one place, not be repeated in every controller:
- interceptors run before and after each controller method, and know which method it is;
- CORS mappings give rules to many paths at once;
- argument resolvers let a method declare a
Tenant tenantorUser userparameter instead of reading headers itself; - resource handlers serve files under more patterns, with their own caching.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
const log = SpringLog('app.web');
@Configuration()
class WebConfig with WebMvcConfigurer {
@override
void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(TimingInterceptor())
.addPathPatterns(['/api/**'])
.excludePathPatterns(['/api/health']);
registry.addInterceptor(AdminOnlyInterceptor());
}
@override
void addCorsMappings(CorsRegistry registry) => registry
.addMapping('/api/**')
.allowedOrigins(['https://shop.example'])
.allowedMethods(['GET', 'POST']);
@override
void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) =>
resolvers.add(TenantResolver());
@override
void addResourceHandlers(ResourceHandlerRegistry registry) => registry
.addResourceHandler(['/assets/**'])
.addResourceLocations(['file:build/web/assets/'])
.setCacheControl(CacheControl.maxAge(const Duration(days: 365)).immutable());
}
// Logs how long each controller method took.
final class TimingInterceptor with HandlerInterceptor {
@override
bool preHandle(
ServerHttpRequest request,
ServerHttpResponse response,
HandlerMethod handler,
) {
request.attributes['start'] = DateTime.now();
return true;
}
@override
void afterCompletion(
ServerHttpRequest request,
ServerHttpResponse response,
HandlerMethod handler,
Object? error,
) {
final start = request.attributes['start'] as DateTime;
log.info('${handler.description} took ${DateTime.now().difference(start)}'
'${error == null ? '' : ' and failed with ${error.runtimeType}'}');
}
}
// Methods marked @AdminOnly() answer 403 to anyone but an admin.
class AdminOnly {
const AdminOnly();
}
final class AdminOnlyInterceptor with HandlerInterceptor {
@override
bool preHandle(
ServerHttpRequest request,
ServerHttpResponse response,
HandlerMethod handler,
) {
if (handler.annotation<AdminOnly>() != null &&
request.headers['X-Role'] != 'admin') {
throw ResponseStatusException(HttpStatus.forbidden);
}
return true;
}
}
// A `Tenant tenant` parameter gets the tenant of the X-Tenant header.
class Tenant {
const Tenant(this.id);
final String id;
}
final class TenantResolver implements HandlerMethodArgumentResolver {
@override
bool supportsParameter(MethodParameter parameter) =>
parameter.type.type == Tenant;
@override
Object? resolveArgument(
MethodParameter parameter,
ServerHttpRequest request,
ServerHttpResponse response,
) => Tenant(request.headers['X-Tenant'] ?? 'default');
}
@RestController()
@RequestMapping('/api/orders')
class OrderController {
@GetMapping()
String list(Tenant tenant) => 'orders of ${tenant.id}';
@AdminOnly()
@DeleteMapping('/{id}')
void delete(@PathVariable() String id) {}
}
WebMvcConfigurer
| Method | Called with | Use it to |
|---|---|---|
addInterceptors(InterceptorRegistry registry) |
an empty registry | add HandlerInterceptors, for all paths or some. |
addCorsMappings(CorsRegistry registry) |
an empty registry | add CORS rules by path pattern. See CORS. |
addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) |
an empty list | add resolvers for parameters of your own types. |
addResourceHandlers(ResourceHandlerRegistry registry) |
an empty registry | add mappings of static resources. See Static resources. |
Rules:
- Any bean can be a configurer. Usually a
@Configuration()class mixes it in; a@Component()works too. - Several configurers are all called, in bean order (
@Order). They share the same registries and list, so what they add adds up: interceptors and resolvers run in the order they were added across all configurers. - They are called once, at startup, while the starter builds the controllers' handler mapping and the static resources' mapping. Changing the registries later has no effect.
- There is nothing else to configure through it: path matching, message converters, formatters and view resolvers have no counterpart here. JSON is set up through the
ObjectMapperandspring.json.*, conversions through the conversion service.
Interceptors
A HandlerInterceptor runs around controller methods. Unlike a filter, it runs only for requests mapped to a controller method, after the method is chosen, and it receives that method.
| Method | When | Return | Default |
|---|---|---|---|
FutureOr<bool> preHandle(request, response, HandlerMethod handler) |
Before the method, after its CORS check. | true to go on; false when the interceptor has answered the request itself. |
true |
FutureOr<void> postHandle(request, response, handler, Object? result) |
After the method returned result (the value of its Future), before the result is written. Headers can still be added. Not called when the method threw. |
— | nothing |
FutureOr<void> afterCompletion(request, response, handler, Object? error) |
When the request is done: after the result was written, or after an exception was answered. error is that exception, even when an @ExceptionHandler answered it; null on success. |
— | nothing |
Rules:
- Order:
preHandleruns in registration order,postHandleandafterCompletionin reverse order. preHandlereturningfalse: the method is not called and nothing more is written by the starter; the interceptor answers throughresponse(await response.send(429, 'Slow down')). The interceptors before it getafterCompletion.preHandlethrowing: the exception becomes the request's answer, through the@ExceptionHandlermethods (aResponseStatusException(HttpStatus.forbidden)is a403).afterCompletionis called only for interceptors whosepreHandlereturnedtrue. An exception thrown in it is logged as a warning and ignored. For a stream or an event stream, it runs when the stream has ended.- Registration is required. An interceptor runs only when a configurer adds it in
addInterceptors. AHandlerInterceptorbean alone is not picked up, as in Spring. - What they do not see: static resources,
404s, CORS pre-flights and theOPTIONSanswers of the router. Use a filter for those. - Mix it in (
with HandlerInterceptor) and override only the steps you need.
InterceptorRegistry and InterceptorRegistration
| Member | Meaning |
|---|---|
registry.addInterceptor(interceptor) |
Adds the interceptor after those already added, for every path until the registration restricts it. Returns the registration. |
registry.registrations |
The registrations, in order (read-only). |
registration.addPathPatterns(List<String> patterns) |
Restricts the interceptor to paths matching one of the patterns. Repeated calls add patterns. |
registration.excludePathPatterns(List<String> patterns) |
Keeps the interceptor away from paths matching one of the patterns, even when they are included. |
registration.appliesTo(String path) |
Whether the interceptor runs for a path: it matches an included pattern (or none is set) and no excluded one. |
registration.interceptor |
The interceptor. |
Patterns are path patterns (/api/**, /books/{isbn}), matched against the request path without the context path.
HandlerMethod
What an interceptor learns about the method:
| Member | Meaning |
|---|---|
beanName |
The controller bean's name (orderController). |
beanTypeName |
The controller class's name. |
description |
OrderController.delete, as logs show it. |
method |
The generator's description of the method: name, parameters, annotations, return type. |
classAnnotations |
The annotations on the controller class. |
parameters |
The method's parameters as MethodParameters. |
annotation<A>() |
The annotation of type A on the method, else on the class; null when neither has one. |
resolveBean() |
The controller object the method is called on. |
The chosen handler is also in the request attribute bestMatchingHandlerAttribute, and the path variables in uriTemplateVariablesAttribute (a Map<String, String>), for a filter that runs on the way out.
Argument resolvers
A HandlerMethodArgumentResolver supplies parameters the starter does not know how to fill: the current tenant, the current user, a value computed from several headers.
| Method | When | Meaning |
|---|---|---|
bool supportsParameter(MethodParameter parameter) |
Once per parameter of every controller method, at startup. | Whether this resolver fills the parameter. |
FutureOr<Object?> resolveArgument(MethodParameter parameter, ServerHttpRequest request, ServerHttpResponse response) |
Once per request, for each parameter it supports. | The value. May return a Future. An exception becomes the request's answer: throw a ResponseStatusException for a 400 or 401. |
Rules:
- Custom resolvers are asked first, before the built-in bindings, in list order. The first that says yes fills the parameter. So a resolver can take over any parameter, even an annotated one; the security starter uses this for
@AuthenticationPrincipal. Spring asks custom resolvers after its own. - A parameter no one fills fails the startup: without a resolver, a
Tenant tenantparameter has no binding (needs @PathVariable, @RequestParam, @RequestHeader, @CookieValue or @RequestBody). See Startup checks. supportsParameterruns at startup only, so it may be slow;resolveArgumentruns on every request, so it should be quick.
MethodParameter
| Member | Meaning |
|---|---|
name |
The parameter's name in the source. |
type |
The declared type: type.type is the Dart Type, type.nullable whether null is accepted. |
annotations |
The annotations on the parameter. |
annotation<A>() |
The first annotation of type A, or null. Use it to read the annotation's values. |
has<A>() |
Whether the parameter has an annotation of type A. |
index |
The position among all parameters, positional first, then named. |
handler |
The HandlerMethod it belongs to. |
parameter |
The generator's description, with whether it is named and required. |
// A parameter marked @CurrentUser() gets the logged-in user's name; a
// request without one is a 401.
class CurrentUser {
const CurrentUser();
}
final class CurrentUserResolver implements HandlerMethodArgumentResolver {
@override
bool supportsParameter(MethodParameter parameter) => parameter.has<CurrentUser>();
@override
Object? resolveArgument(parameter, request, response) =>
request.principal?.name ??
(parameter.type.nullable
? null
: throw ResponseStatusException(HttpStatus.unauthorized));
}
CORS mappings
addCorsMappings adds global CORS rules by path pattern. What a mapping leaves out gets permissive defaults: every origin, GET, HEAD and POST, every header, 30 minutes of pre-flight cache. The rules combine with each handler's @CrossOrigin, and they apply to the static resources too. Every rule and edge case: CORS.
Resource handlers
addResourceHandlers adds mappings of static resources with their own patterns, locations and caching. A mapping with the same pattern as spring.mvc.static-path-pattern replaces the default one. Every option: Static resources.
In Spring (Java)
@Configuration
class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TimingInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/health");
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new TenantResolver());
}
}
Differences that matter:
WebMvcConfigureris a mixin with four methods: interceptors, CORS mappings, argument resolvers and resource handlers. Spring's other methods (path matching, message converters, formatters, view controllers, ...) have no counterpart.- The registries take lists (
addPathPatterns(['/api/**'])), not varargs. preHandlereceives aHandlerMethod, never another kind of handler, and may be asynchronous.- Custom argument resolvers are asked before the built-in ones.
afterCompletiongets the exception even when an@ExceptionHandleranswered it.