Building a Mini Spring MVC Framework from Scratch Using Pure JDK
This article walks through creating a lightweight Spring MVC‑like framework by setting up a clean web project, defining custom annotations, implementing a DispatcherServlet that scans packages, instantiates beans, performs dependency injection, maps URLs to controller methods, and finally runs the application without any Spring dependencies.
The author demonstrates how to build a miniature version of Spring MVC in a plain Java web project without importing Spring libraries, relying solely on the JDK.
First, the project structure is shown, including separate packages for annotation , controller , service , and dao . Custom annotations mirroring Spring MVC’s @Controller, @Service, @Repository, @Qualifier, and @RequestMapping are defined using JDK meta‑annotations such as @Documented, @Target, and @Retention.
Next, a custom DispatcherServlet is created by extending HttpServlet . The servlet is registered via the @WebServlet annotation (Servlet 3.0 style) and receives an initialization parameter that specifies the base package to scan.
During init() , the servlet performs four main tasks:
Scans the specified base package to collect class information.
Instantiates classes annotated with @Controller, @Service, or @Repository and stores a name‑to‑instance mapping.
Processes fields annotated with @Qualifier to perform dependency injection.
Scans methods annotated with @RequestMapping to build a URL‑to‑method mapping.
The servlet’s doPost() (and doGet() ) extracts the request URL, looks up the corresponding controller method from the mapping, and invokes it via reflection.
Configuration snippets illustrate the XML‑style component scan and the required Maven pom.xml dependency for the servlet API:
<context:component-scan base-package="com.zfz.myspringmvc"/>
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
Finally, the article shows the running result of the mini framework, confirming that the custom DispatcherServlet correctly routes requests to the controller, service, and DAO layers, completing the implementation of a functional, Spring‑like MVC framework.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.