Declarative Locking in Spring Boot: Build a Custom @Lock Annotation for Local and Distributed Concurrency Control
This article demonstrates how to eliminate boilerplate locking code by creating a custom @Lock annotation backed by Spring AOP, supporting both JVM-level ReentrantLock and Redis-based Redisson distributed locks with configurable timeout and lock type.
Reading font

In real-world business development, concurrent modification of shared data leads to race conditions such as lost updates or inconsistent state. The typical solution — manual synchronized, Lock, or Redisson RLock calls — scatters verbose lock-acquisition and release logic across services, making maintenance difficult and error-prone.
1. Annotation Definition
A runtime-retained, method-targeted annotation declares the lock key:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Lock {
String key();
}2. Unified Lock Abstraction
The PackLock interface extends java.util.concurrent.locks.Lock and provides default no-op implementations for interruptible lock, tryLock variants, and Condition, allowing concrete implementations to override only what they support.
3. Local Lock Implementation
ReentrantPackLockwraps a ReentrantLock and reads timeout configuration from LockProperties:
public class ReentrantPackLock implements PackLock {
private final ReentrantLock lock;
private final LockProperties lockProperties;
public ReentrantPackLock(LockProperties lockProperties) {
this.lock = new ReentrantLock();
this.lockProperties = lockProperties;
}
@Override public void lock() { lock.lock(); }
@Override public void lockInterruptibly() throws InterruptedException { lock.lockInterruptibly(); }
@Override public boolean tryLock() {
try { return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit()); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); }
}
@Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); }
@Override public void unlock() { lock.unlock(); }
@Override public Condition newCondition() { return lock.newCondition(); }
}4. Distributed Lock Implementation
RedissonPackLockobtains an RLock from RedissonClient using the annotation's key. It delegates lock operations to Redisson and throws UnsupportedOperationException for newCondition() because distributed locks do not support conditions:
public class RedissonPackLock implements PackLock {
private final RLock lock;
private final LockProperties lockProperties;
public RedissonPackLock(RedissonClient redissonClient, LockProperties lockProperties, Lock annotation) {
this.lockProperties = lockProperties;
this.lock = redissonClient.getLock(annotation.key());
}
@Override public void lock() { lock.lock(); }
@Override public void lockInterruptibly() throws InterruptedException { lock.lockInterruptibly(); }
@Override public boolean tryLock() {
try { return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit()); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); }
}
@Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); }
@Override public void unlock() { lock.unlock(); }
@Override public Condition newCondition() { throw new UnsupportedOperationException("Redisson distributed lock does not support Condition"); }
}5. Configuration Properties
LockProperties(bound to prefix pack.lock) selects lock type ( LOCAL or REDIS), key prefix, default wait time, and time unit:
@ConfigurationProperties(prefix = "pack.lock")
public record LockProperties(
@DefaultValue("LOCAL") LockType type,
String prefix,
@DefaultValue("-1") Long time,
@DefaultValue("") TimeUnit unit
) {
public enum LockType { LOCAL, REDIS }
}6. AOP Pointcut and Advice
LockAdvisorimplements PointcutAdvisor. Its pointcut matches any public method annotated with @Lock. The advice is a LockInterceptor that:
Resolves the Lock annotation on the invoked method.
Chooses a PackLock instance: for
LOCAL</type>, retrieves or creates a cached <code>ReentrantPackLockper key via ConcurrentHashMap.computeIfAbsent; for REDIS, creates a new RedissonPackLock per invocation (using the annotation's key).
Calls lock(), proceeds with the method, and ensures unlock() in a finally block.
public class LockAdvisor implements PointcutAdvisor {
private final Map<String, PackLock> localLockCache = new ConcurrentHashMap<>();
private final LockProperties lockProperties;
private final RedissonClient redissonClient;
public LockAdvisor(LockProperties lockProperties, RedissonClient redissonClient) { ... }
@Override public Advice getAdvice() { return new LockInterceptor(lockProperties, redissonClient); }
@Override public Pointcut getPointcut() {
return new StaticMethodMatcherPointcut() {
@Override public boolean matches(Method method, Class<?> targetClass) {
return method.isAnnotationPresent(Lock.class);
}
};
}
public class LockInterceptor implements MethodInterceptor {
@Override public Object invoke(MethodInvocation invocation) throws Throwable {
Lock annotation = invocation.getMethod().getAnnotation(Lock.class);
if (annotation == null) return invocation.proceed();
LockType type = lockProperties.type();
PackLock packLock = null;
if (type == LockType.LOCAL) {
packLock = localLockCache.computeIfAbsent(annotation.key(), k -> new ReentrantPackLock(lockProperties));
} else {
packLock = new RedissonPackLock(redissonClient, lockProperties, annotation);
}
packLock.lock();
try { return invocation.proceed(); }
finally { packLock.unlock(); }
}
}
}7. BeanPostProcessor for Proxy Creation
LockProxyCreatorimplements BeanPostProcessor and Ordered (lowest precedence). In postProcessAfterInitialization, it inspects the target bean's declared methods; if any public method carries @Lock, it wraps the bean with a Spring ProxyFactory that exposes the proxy and adds the LockAdvisor. If the bean is already an AOP proxy, it simply adds the advisor to the existing advised object.
public class LockProxyCreator implements BeanPostProcessor, Ordered {
private final LockAdvisor lockAdvisor;
public LockProxyCreator(LockProperties lockProperties, RedissonClient redissonClient) {
this.lockAdvisor = new LockAdvisor(lockProperties, redissonClient);
}
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
boolean needCreator = false;
for (Method method : targetClass.getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers()) && method.isAnnotationPresent(Lock.class)) {
needCreator = true; break;
}
}
if (!needCreator) return bean;
if (AopUtils.isAopProxy(bean)) {
Advised advised = (Advised) bean;
advised.addAdvisor(0, this.lockAdvisor);
return bean;
}
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(bean);
proxyFactory.setExposeProxy(true);
proxyFactory.setProxyTargetClass(true);
proxyFactory.addAdvisor(this.lockAdvisor);
return proxyFactory.getProxy();
}
@Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; }
}8. Verification Test
A service method deduct(Long stockId, Integer deductNum) reads stock, checks availability, and updates the database. Without locking, a concurrent test with 30 threads (using CountDownLatch and CyclicBarrier to synchronize start) produces oversell — multiple threads report successful purchase despite insufficient stock. After adding @Lock(key = "sss") to the method, the same test shows only the expected number of successful purchases, confirming the annotation serializes access correctly.
The article includes screenshots of console output before and after applying the annotation, demonstrating the oversell problem and its resolution.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.