Spring Foundation
A guided bridge from Core Java, Servlets, and JSP to Spring Framework and Spring Boot.
1. Connect the new concepts to familiar ones
| What you already know | Spring equivalent | What changes |
|---|---|---|
| new Service() inside a Servlet | Constructor injection of a Spring bean | The container constructs and supplies the service. |
| doGet / doPost | @GetMapping / @PostMapping | Methods declare the HTTP routes they handle. |
| request.getParameter | @ModelAttribute / @RequestParam | Spring binds request inputs into Java values. |
| request.setAttribute + RequestDispatcher.forward | Model attributes + view name | The view resolver finds the template. |
| JSP + JSTL | Thymeleaf templates + th:* attributes | HTML templates are rendered on the server. |
| Servlet filters | Spring Security filter chain | Security runs before controller methods. |
| Manually configuring Tomcat | Boot embedded Tomcat | The web server starts with main(). |
| JDBC DAO | MongoRepository | The Spring Data proxy supplies document CRUD. |
2. What Spring Framework does
Spring Framework supplies the infrastructure for Java applications: object creation and dependency injection, web MVC, validation integration, transaction abstractions, and more. It does not replace Java. A service is still a Java class, and a controller method is still a method called with arguments.
Inversion of Control means your code lets a container control object assembly. Imagine a TodoController needs a TodoService and the service needs a TodoRepository. Instead of constructing the whole chain inside doGet, you declare each dependency in a constructor. Spring’s ApplicationContext discovers components, constructs them, and supplies the references.
A bean is an object managed by that context. @Service marks a business service; @Controller marks an MVC controller; @RestController marks a JSON controller; @Configuration contains bean definitions. @Bean is used when you need to create an object from a library, such as a PasswordEncoder. The default bean scope is singleton: one instance per application context, shared across requests. Never store the current user’s request data in controller instance fields.
Constructor injection works without @Autowired when a class has one constructor. Dependencies can be final. It also makes unit tests simple: new TodoService(mockRepository) constructs the class without starting a server. Spring Data discovers repository interfaces through its repository configuration, then registers runtime implementations as beans.
@Service
public class TodoService {
private final TodoRepository repository;
public TodoService(TodoRepository repository) {
this.repository = repository;
}
}Choose constructor injection instead of manually creating Spring-managed collaborators. A manually constructed service will not automatically receive configured dependencies, proxy behavior, or lifecycle support.
3. What Spring Boot adds
Spring Boot builds on Spring Framework. It supplies auto-configuration, starter dependencies, executable packaging, and an embedded server. Auto-configuration inspects the classpath, configuration properties, and beans you already defined. With the MVC starter present, Boot configures web infrastructure. With Thymeleaf present, it configures a template engine. With MongoDB present and a URI supplied, it configures MongoDB access.
A starter is a convenient dependency group. The parent POM manages compatible versions, so individual starter versions are omitted. The Maven plugin packages dependencies into an executable JAR. You can run it with java -jar rather than deploying a WAR manually.
@SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. Put it above your application packages. It is not a substitute for understanding beans; it is the entry point that connects their discovery and configuration.
Boot is also useful for applications without web pages. A REST application still uses Spring MVC and Tomcat, but JSON serialization replaces template resolution. Spring Boot and Spring MVC are related parts of the stack, not two competing frameworks.
4. Trace one web request
For GET /todos, Tomcat accepts the HTTP request. Security filters apply their rules. DispatcherServlet locates the mapped controller method. The controller requests a list from the service, which uses the repository to read MongoDB documents. The controller places that list in Model and returns "list". Thymeleaf resolves templates/list.html and renders HTML. The response goes back to the browser.
For a JSON endpoint, the same route ends with the controller returning an object. A message converter serializes it to JSON. @RequestBody performs the reverse operation: JSON becomes the request DTO before your method executes.
Keep responsibilities clear: controllers handle HTTP and view/API contracts, services implement operations and authorization rules, repositories access documents, DTOs define accepted inputs, and templates/components present results.
5. HTTP and validation before coding
GET retrieves state and should not mutate it. POST creates a resource or submits a form. PUT replaces the editable state at a known resource URL. DELETE removes it. HTML forms natively use GET and POST; the Thymeleaf lab uses POST routes for update and delete. JSON clients can send PUT and DELETE directly.
Client validation improves usability, while server validation protects the contract. @NotBlank rejects empty titles, @Size caps length, @Email checks email shape, and @NotNull rejects missing required values. @Valid triggers validation. A validation annotation on a field alone does not make every method call validate automatically.
400 means invalid request, 401 means authentication is missing or invalid, 403 means the authenticated request lacks access, 404 means the resource is not available, and 409 means a conflict such as a duplicate email. The personal application deliberately uses 404 for foreign-owned todo ids.
6. MongoDB essentials
MongoDB stores BSON documents in collections. A database groups collections. A todo might contain _id, title, and completed. BSON supports more types than JSON; APIs expose JSON views of the stored data. A Java document is mapped by Spring Data rather than manually converted in each controller.
@Document names the collection. @Id selects the id field. MongoRepository<Todo,String> identifies the document and id types. Derived query names such as findByIdAndOwnerId instruct Spring Data to build an equality query. MongoDB is not accessed using @Entity, JpaRepository, or SQL joins in these projects.
Atlas is a managed MongoDB hosting service. Its website account manages projects and clusters; a separate database user authenticates application connections. Your app also needs a matching network IP rule. Each application uses its own database name to keep the labs independent.
A single document write is atomic. The read-then-save update shown in these labs can overwrite concurrent changes. That tradeoff keeps the first implementation teachable. A later exercise can add optimistic locking with @Version and return a conflict for a stale update.
7. Configuration and project layout
src/main/java contains compiled Java source. src/main/resources contains templates, static assets, and configuration that are copied into the JAR. src/test/java contains tests. target is generated output. pom.xml defines coordinates, dependencies, Java baseline, and plugins.
application.properties separates deployment choices from source. server.port selects the HTTP port. spring.mongodb.uri reads the driver URI; spring.mongodb.database selects the application database. ${MONGODB_URI} is a property placeholder resolved from the environment. Never substitute an actual password into the checked-in file.
When starting from an IDE, configure MONGODB_URI in its run configuration. Variables set in one terminal do not automatically appear inside an already-running IDE. Restarting or changing the IDE launch environment may be necessary.
8. Prepare your development tools
Install a JDK 21, Apache Maven 3.9+, and an IDE such as IntelliJ IDEA, Eclipse/STS, or VS Code with Java extensions. Maven must be on PATH and JAVA_HOME must point to the JDK directory, not its bin subdirectory. Use a terminal in the project folder. Internet access is needed on the first dependency download. Spring Boot projects include an embedded Tomcat server. The Servlets and JSPs tutorial explains how to install Tomcat separately.
For the React lab, also install Node.js 22.12+ and npm. For the REST labs, install Postman Desktop, or use the web client with its Desktop Agent for localhost requests.
java -version
javac -version
mvn -version
node --version
npm --versionExpect Java and javac to report version 21, Maven to report 3.9.x and its Java home, and Node to report a supported 22.x or newer version. If multiple JDKs are installed, Maven’s reported Java version determines compilation. The projects target Java 21; using an older JDK causes “release version 21 not supported.”
These examples deliberately pin Boot 4.1.1. Boot 4’s MVC starter is spring-boot-starter-webmvc; its MongoDB connection property is spring.mongodb.uri. When reading a Boot 3 tutorial, check its starter and configuration names before mixing it with this code.
Version references: Spring Boot requirements, Boot configuration properties, and Vite setup.
9. Check understanding
- Explain why a controller should not create a repository with new.
- Trace a GET request until Thymeleaf produces HTML.
- Explain the difference between Spring Framework, Spring MVC, and Spring Boot.
- Name the folder for templates and the folder for static CSS.
- Explain why a validation rule must run on the server even if the browser uses required.