java 52 lines · 8 steps

Injecting the current user in Spring MVC

A custom @CurrentUser annotation plus an argument resolver lets controllers receive the logged-in User directly as a method parameter.

Explained by highlit
1@Target(ElementType.PARAMETER)
2@Retention(RetentionPolicy.RUNTIME)
3public @interface CurrentUser {
4}
5 
6@Component
7public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
8 
9 private final UserRepository userRepository;
10 
11 public CurrentUserArgumentResolver(UserRepository userRepository) {
12 this.userRepository = userRepository;
13 }
14 
15 @Override
16 public boolean supportsParameter(MethodParameter parameter) {
17 return parameter.hasParameterAnnotation(CurrentUser.class)
18 && User.class.isAssignableFrom(parameter.getParameterType());
19 }
20 
21 @Override
22 public Object resolveArgument(MethodParameter parameter,
23 ModelAndViewContainer mavContainer,
24 NativeWebRequest webRequest,
25 WebDataBinderFactory binderFactory) {
26 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
27 
28 if (authentication == null || !authentication.isAuthenticated()
29 || authentication instanceof AnonymousAuthenticationToken) {
30 throw new AccessDeniedException("No authenticated user present");
31 }
32 
33 String username = authentication.getName();
34 return userRepository.findByUsername(username)
35 .orElseThrow(() -> new UsernameNotFoundException(username));
36 }
37}
38 
39@Configuration
40public class WebConfig implements WebMvcConfigurer {
41 
42 private final CurrentUserArgumentResolver currentUserArgumentResolver;
43 
44 public WebConfig(CurrentUserArgumentResolver currentUserArgumentResolver) {
45 this.currentUserArgumentResolver = currentUserArgumentResolver;
46 }
47 
48 @Override
49 public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
50 resolvers.add(currentUserArgumentResolver);
51 }
52}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom HandlerMethodArgumentResolver removes boilerplate by turning security context lookups into a clean controller parameter.
  2. 2Pairing a marker annotation with supportsParameter lets you scope a resolver precisely to the parameters you intend it for.
  3. 3Custom resolvers only take effect once registered via WebMvcConfigurer.addArgumentResolvers.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Injecting the current user in Spring MVC — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code