Spring MVC
Annotated Controller
@PathVariable
Java
Web Development

Spring MVC Annotated Controller Interface with PathVariable

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Using Spring MVC controller interfaces with PathVariable can improve API consistency, but annotation placement must align with Spring mapping rules. If mappings fail, requests may return 404 or parameter binding errors. The safest pattern is explicit mapping contracts shared across interface and implementation.

A reliable implementation should remain understandable during troubleshooting and upgrades. That requires explicit assumptions, clear boundaries, and verifiable behavior under both normal and failure conditions.

Core Sections

1. Define route contract in interface

Place request mapping and parameter annotations where your Spring version supports inheritance. Keep names consistent between path template and parameter binding.

java
1@RequestMapping("/users")
2public interface UserApi {
3    @GetMapping("/{id}")
4    ResponseEntity<UserDto> findById(@PathVariable("id") Long id);
5}
6
7@RestController
8class UserController implements UserApi {
9    @Override
10    public ResponseEntity<UserDto> findById(Long id) {
11        return ResponseEntity.ok(new UserDto(id, "Ana"));
12    }
13}

The baseline should be intentionally small and deterministic. A compact first version is easier to test, easier to reason about, and faster to review when teams iterate.

2. Validate mapping behavior with tests

Controller tests should confirm both route matching and path variable conversion. This catches subtle annotation inheritance differences early.

java
1@WebMvcTest(UserController.class)
2class UserControllerTest {
3    @Autowired MockMvc mvc;
4
5    @Test
6    void findsUser() throws Exception {
7        mvc.perform(get("/users/1"))
8           .andExpect(status().isOk())
9           .andExpect(jsonPath("$.id").value(1));
10    }
11}

After baseline correctness, harden around edge cases and integration boundaries. Explicit validation, timeout handling, and predictable error semantics make downstream behavior safer.

3. Keep API contract evolution explicit

When routes evolve, update interface contract, implementation, and documentation together. Partial updates create confusing breakage across clients and tests.

Operationally, define what success looks like in measurable terms and record baseline metrics before rollout. This makes post-change evaluation objective rather than anecdotal.

Include at least one representative production-like test, one malformed-input test, and one dependency-failure test in CI. Repeatable coverage prevents regressions introduced by dependency changes or refactors.

Keep ownership and escalation paths clear. When incidents happen, responders should know who owns the code path, what logs and metrics to inspect first, and how to execute a safe rollback or fallback mode.

Before release, confirm recovery mechanics in practice. A rollback strategy that is never rehearsed is often too slow under pressure, while a validated recovery workflow can reduce outage impact dramatically.

A complete engineering solution also includes explicit contracts for ownership, inputs, and failure semantics. Document what callers may send, which errors are retriable, and what actions operators should take when dependencies degrade. Clear contracts reduce ambiguity between teams and prevent divergent behavior in different services that rely on the same pattern.

Testing should represent real constraints rather than toy inputs only. Add one production-like scenario, one malformed-input scenario, and one dependency-failure scenario with deterministic assertions. Keep these checks in continuous integration so every change verifies behavior against the same baseline. This practice catches regressions early and reduces the chance of late surprises during rollout.

Observability should be focused and intentional. Emit concise logs for key branch decisions, include request identifiers for traceability, and track metrics tied to user impact such as latency percentiles, error rates, and retry outcomes. Focused telemetry helps teams distinguish application defects from infrastructure instability quickly during incidents.

Before deployment, prepare rollback and fallback options that can be executed quickly. Feature toggles, staged rollout, and a validated reversion workflow significantly reduce operational risk when real traffic reveals assumptions that were not visible in development. Recovery planning in advance is a core reliability practice and should be rehearsed periodically.

Finally, keep runbook notes near the implementation and update them as behavior evolves. Short, current documentation dramatically improves handoffs and lowers on-call resolution time.

Common Pitfalls

  • Mismatching path template variable names and method parameter names.
  • Assuming annotation inheritance works identically across framework versions.
  • Splitting route definitions across many interfaces without ownership clarity.
  • Skipping controller tests and discovering mapping regressions in production.
  • Changing endpoint signatures without synchronized client contract updates.

Summary

  • Keep route and variable names aligned in one contract.
  • Test mapping and binding behavior with MockMvc.
  • Document framework version expectations for annotation inheritance.
  • Update interfaces and implementations in lockstep.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.