Simplify Order Processing with Strategy Pattern and Custom Annotations in Java
This article demonstrates how to replace cumbersome if‑else logic in an order‑processing system with a concise Strategy pattern implementation, using a custom @HandlerType annotation and Spring bean registration to make adding new order types effortless and maintainable.
We illustrate a typical order‑processing requirement where different order types need distinct handling.
First, the order entity and service interface are shown.
Traditional implementation uses a long chain of if‑else statements.
Using the Strategy pattern, the same logic can be reduced to two lines.
A custom annotation @HandlerType marks each concrete handler, and an abstract class AbstractHandler defines the common processing contract.
Each handler is registered as a Spring bean with @Component and the custom annotation.
At startup, a ClassScanner scans the specified package for classes annotated with @HandlerType, builds a map of order type to handler class, and injects it into HandlerContext via a HandlerProcessor that implements BeanFactoryPostProcessor.
The HandlerContext retrieves the appropriate handler bean from the Spring container using a utility BeanTool.
With this approach, adding a new order type only requires creating a new handler class; no changes to the existing service implementation are needed.
Full source code is available at the provided GitHub link.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
