JAVA

Java Annotation

neal89 2025. 4. 1. 12:44

🧩 Why Use Annotations?

Reflection-based servlets map URL paths to method names. But what if you want to map /site1 to a method named page1()? Or handle complex paths like /add-member?

Java method names can't contain dashes or certain special characters, and using method names alone limits flexibility.

Annotations solve this by letting you attach metadata to methods, which can be read at runtime to handle routing, validation, or configuration.


✨ Creating a Custom Annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RouteMapping {
    String path();
}
  • @Retention(RUNTIME): Annotation is retained at runtime so it can be accessed via reflection.
  • @Target(METHOD): Can only be applied to methods.
  • path(): Custom property representing the URL path.

🧪 Applying the Annotation to a Controller

public class MyController {

    @RouteMapping(path = "/home")
    public void showHome(HttpRequest req, HttpResponse res) {
        res.writeBody("<h1>Welcome Home</h1>");
    }

    @RouteMapping(path = "/add-member")
    public void addMember(HttpRequest req, HttpResponse res) {
        res.writeBody("<h1>Member Added</h1>");
    }
}

🔍 Reading Annotation via Reflection

public class AnnotationServlet implements HttpServlet {
    private final List<Object> controllers;

    public AnnotationServlet(List<Object> controllers) {
        this.controllers = controllers;
    }

    @Override
    public void service(HttpRequest request, HttpResponse response) throws IOException {
        String path = request.getPath();
        for (Object controller : controllers) {
            for (Method method : controller.getClass().getDeclaredMethods()) {
                RouteMapping mapping = method.getAnnotation(RouteMapping.class);
                if (mapping != null && mapping.path().equals(path)) {
                    try {
                        method.invoke(controller, request, response);
                        return;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        throw new PageNotFoundException("Not found: " + path);
    }
}

✅ Benefits of Annotation-based Routing

Feature Benefit

Flexible URL mapping /site1 → page1(), /add-member → addMember()
Cleaner code No need for manual if-based routing or naming conventions
Maintainable Just add @RouteMapping to register new paths
Framework-style Mimics routing in Spring MVC, Express.js, etc.

🚨 Limitations

  • Requires reflection, which may have performance implications.
  • Overusing annotations can make logic harder to trace.
  • You still need to ensure parameter and response types match.

🔚 Summary

Annotations let you attach metadata to Java code and are especially useful in frameworks. For routing, @RouteMapping provides a clean way to associate methods with URL paths, solving problems that reflection-only routing cannot handle (like dashes in URLs).

In real-world Java web frameworks like Spring MVC, annotations such as @RequestMapping, @GetMapping, and @PostMapping are heavily used to build clean, flexible, and maintainable controllers.