All posts

7 min read

Node.js + Express developer learning Java + Spring Boot: what carries over, what's new, 30-day plan

Guide for Express developers transitioning to Spring Boot, covering transferable concepts, new paradigms, pitfalls, a 30‑day roadmap, and quick FAQ.

What carries over

Node.js / Express conceptSpring Boot equivalentWhy it matters
Routing – app.get('/users', …)Controller methods – @GetMapping("/users")Both map HTTP verbs + paths to handler code. The mental model of “request → handler” stays the same.
Middleware – app.use(bodyParser.json())Filters / Interceptors – OncePerRequestFilter or HandlerInterceptorThe idea of a processing pipeline that can inspect/modify request and response persists.
Dependency injection via modules – require('./service')Spring DI – @Service, @AutowiredYou’re still letting the framework wire objects, just with annotations and a container instead of manual require.
Environment configuration – process.env.PORTExternalized config – @Value("${server.port}") or application.ymlBoth encourage keeping secrets and env‑specific values out of code.
Asynchronous handling – async/await or callbacksReactive / CompletableFuture – @Async, WebFlux or plain CompletableFutureNon‑blocking request handling is still a goal; the syntax changes but the principle remains.
JSON serialization – res.json(obj)Jackson – return obj; (automatically converted)HTTP APIs still exchange JSON; Spring Boot auto‑configures Jackson for you.
Testing – supertest, jestSpring Test – MockMvc, @WebMvcTestThe pattern “spin up the web layer, send a request, assert response” is identical.
Static assets – express.static('public')Static resources – src/main/resources/staticServing files from a folder works the same way, just different conventions.
Error handling – app.use(errHandler)@ControllerAdvice – global exception handlersCentralised error handling is still a best practice; you just annotate a class instead of registering a function.

The biggest mental shift is moving from a loosely typed, dynamically loaded environment to a statically typed, compiled one. Your existing habits around modular code, clear separation of concerns, and test‑first development will serve you well in Spring Boot.


What's new

Side‑by‑side example: a tiny CRUD endpoint

Node.js + Express (JavaScript)

// src/routes/user.js
const express = require('express');
const router = express.Router();
const UserService = require('../services/userService');

router.get('/:id', async (req, res, next) => {
  try {
    const user = await UserService.findById(req.params.id);
    if (!user) return res.status(404).json({ error: 'Not found' });
    res.json(user);
  } catch (err) {
    next(err);
  }
});

module.exports = router;

Java + Spring Boot (Java)

// src/main/java/com/example/demo/controller/UserController.java
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}

What changed and why

AspectNode.js / ExpressSpring Boot
File structureFree‑form, often src/Conventional Maven/Gradle layout (src/main/java/...)
Export / importmodule.exports / require@Component / constructor injection
Async handlingasync/await returns a PromiseOptional<User> + Spring MVC resolves it synchronously; you can also return CompletableFuture<User> for async.
Routing declarationrouter.get('/:id', …)@GetMapping("/{id}") on a method inside a @RestController
Response buildingres.json(...) or res.status(...).json(...)ResponseEntity builder methods; Spring automatically serialises the body with Jackson.
Error flownext(err) passes to error middlewareThrow an exception or return an error ResponseEntity; global @ControllerAdvice can translate exceptions.
Type safetyNo compile‑time type checksUser is a concrete class; the compiler guarantees field existence.

Spring Boot also brings a massive ecosystem: Actuator for health checks, Spring Data JPA for repository abstraction, and built‑in support for security, validation, and more. Those are not “new” concepts but are provided out‑of‑the‑box, reducing boilerplate you would otherwise write yourself in Express.


Common pitfalls

  1. Forgetting the classpath – In Java you must place source files under the correct package directory. A misplaced file compiles but Spring won’t discover it as a bean.
  2. Over‑using @Autowired on fields – Field injection works but defeats constructor‑based DI, which gives you immutability and easier testing.
  3. Assuming null means “not found” – Spring MVC treats a null return as a 200 with an empty body. Use Optional<T> or throw ResponseStatusException(HttpStatus.NOT_FOUND) to get a proper 404.
  4. Mixing synchronous and reactive APIs – If you start using WebFlux (reactive) but keep blocking calls (e.g., JPA findById) you’ll block the event loop and lose the performance benefit.
  5. Ignoring the default servlet container – Spring Boot runs an embedded Tomcat/Jetty/Undertow. Don’t try to start a separate server process; let the spring-boot:run task manage it.
  6. Relying on process.env – Environment variables are still accessible via System.getenv, but Spring encourages @ConfigurationProperties or application.yml. Direct System.getenv bypasses profile‑aware configuration.
  7. Not configuring Jackson – By default Spring Boot serialises all getters. If you previously used res.json({ foo: undefined }) you’ll see null in Java; configure ObjectMapper to ignore nulls if you need the same output.

Your 30‑day plan

Week 1 – Foundations

  1. Set up the toolchain – Install JDK 17, Maven or Gradle, and an IDE (IntelliJ IDEA Community or VS Code with Java extensions). Run spring init --dependencies=web demo to generate a starter project.
  2. Hello‑World REST endpoint – Create a GreetingController with @GetMapping("/greet") that returns a POJO. Verify JSON output with curl.
  3. Configuration basics – Add application.yml with a custom property (app.message). Bind it using @ConfigurationProperties(prefix="app") and inject it into the controller.
  4. Mini project – Build a Todo list API with in‑memory storage (Map<Long, Todo>). Implement GET /todos, POST /todos, and DELETE /todos/{id}.

Week 2 – Dependency injection & data

  1. Service layer – Extract business logic from the controller into a TodoService annotated with @Service. Inject it via constructor.
  2. Spring Data JPA – Add the spring-boot-starter-data-jpa and H2 dependency. Define Todo as an @Entity and create a TodoRepository extends JpaRepository<Todo, Long>.
  3. Database migration – Add Flyway (spring-boot-starter-flyway) and write a simple V1__init.sql to create the todos table.
  4. Mini project – Extend the Todo API to persist data. Add GET /todos/{id} and proper 404 handling with ResponseStatusException.

Week 3 – Advanced web features

  1. Error handling – Create a @ControllerAdvice class with @ExceptionHandler methods for EntityNotFoundException and generic Exception. Return a consistent error JSON.
  2. Validation – Add spring-boot-starter-validation. Annotate DTO fields with @NotBlank, @Size, etc., and handle MethodArgumentNotValidException globally.
  3. Security basics – Add spring-boot-starter-security. Configure an in‑memory user (user/password) and protect the Todo endpoints with httpBasic().
  4. Mini project – Implement User‑owned Todos: each Todo has a ownerUsername. Secure the API so a user can only CRUD their own items.

Week 4 – Production readiness & polishing

  1. Actuator & health checks – Enable management.endpoints.web.exposure.include=*. Query /actuator/health and /actuator/info.
  2. Logging – Switch to Logback configuration (logback-spring.xml). Add a request logging filter (CommonsRequestLoggingFilter).
  3. Docker container – Write a Dockerfile that uses openjdk:17-jdk-slim, copies the built JAR, and runs java -jar app.jar. Test with docker build and docker run.
  4. Final project – Deploy the User‑owned Todo service to Docker, verify that environment variables (SPRING_PROFILES_ACTIVE=prod) correctly switch to a production profile with a PostgreSQL datasource.

At the end of the month you should be comfortable navigating a Spring Boot codebase, writing idiomatic Java, and leveraging the ecosystem to replace most of the manual plumbing you performed in Express.


FAQ

How do I debug a Spring Boot application compared to using node --inspect?

Run the app from your IDE in debug mode (e.g., Debug in IntelliJ) or start it with java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 and attach a debugger on port 5005.

Do I need to learn Maven/Gradle if I already use npm scripts?

Yes. Maven or Gradle is the build system that resolves dependencies, compiles Java, and packages the JAR. The concepts (scripts, plugins) are similar to npm, but the syntax differs.

Can I still use JavaScript on the front‑end while the back‑end is Spring Boot?

Absolutely. Spring Boot serves JSON over HTTP just like Express, so any SPA framework (React, Vue, Angular) works unchanged; you only change the base URL.

Is there a “hot‑reload” equivalent to nodemon?

Spring Boot DevTools provides automatic restart on classpath changes. Add the spring-boot-devtools dependency and run the app in your IDE; changes trigger a quick restart without losing session state.

Keep going

#nodejs #java #springboot #learningplan