java / expert
Snippet
Custom Controller Argument Resolution with HandlerMethodArgumentResolver
HandlerMethodArgumentResolver allows for injecting custom objects into controller methods by resolving them from the web request context. This is highly useful for extracting security principals or specialized session data without polluting controller logic.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Componentpublic class CurrentUserResolver implements HandlerMethodArgumentResolver {@Overridepublic boolean supportsParameter(MethodParameter parameter) {return parameter.hasParameterAnnotation(CurrentUser.class) &¶meter.getParameterType().equals(UserAccount.class);}@Overridepublic Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();return request.getAttribute("authenticated_user");}}
spring
Breakdown
1
supportsParameter(...)
Determines if the resolver is applicable based on the parameter type and annotations.
2
resolveArgument(...)
Performs the actual logic to extract or construct the object to be injected into the method.