Skip to content

About

A collection of practical Spring Boot examples covering REST APIs, Spring Security, Hibernate & JPA, WebFlux, OAuth2, AOP, database integration, testing, and more. A hands-on reference for learning, understanding, and revising the Spring ecosystem.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Latest commit

 

History

49 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SpringBootExamples

A multi-module Spring Boot 2.1.8.RELEASE reference repository covering core Spring Boot mechanics, web templating, REST services (Spring MVC, JAX-RS/Jersey, HATEOAS, RestTemplate, WebFlux), data persistence with JPA/Hibernate and reactive MongoDB, AOP, security with OAuth2 and SSL/HTTPS, remoting (RMI and Hessian), email, internationalization, and unit/integration testing.

Each directory under the root Maven aggregator is a standalone, focused example designed to isolate a single concept or integration pattern without unnecessary scaffolding.


Table of Contents


Technical Overview

All technologies listed below are verified directly in the root pom.xml and child module POMs.

Category Technology / Version Where Used
Language Java 8 (<java.version>1.8</java.version>) All modules
Framework Spring Boot 2.1.8.RELEASE (spring-boot-starter-parent) Root pom.xml and all 29 modules
Build System Apache Maven (multi-module POM, maven-jar-plugin 3.1.1, spring-boot-maven-plugin) Root and module pom.xml files
Web (Servlet) Spring Web MVC (spring-boot-starter-web), Embedded Tomcat (default), Embedded Jetty (spring-boot-starter-jetty) Web modules, embedded-jetty-server
Web (JAX-RS) Jersey (spring-boot-starter-jersey) rest-jersey-example, rest-hateoas
Web (Reactive) Spring WebFlux (spring-boot-starter-webflux), Project Reactor spring-webflux-demo
API Hypermedia & Docs Spring HATEOAS (spring-boot-starter-hateoas), Springfox Swagger2 & Swagger UI (2.8.0) rest-hateoas, swagger-ui
HTTP Client RestTemplate backed by Apache HttpClient (org.apache.httpcomponents:httpclient) resttemplate
View Templates FreeMarker, Thymeleaf, Mustache, JSP + JSTL (tomcat-embed-jasper), WebJars (bootstrap 3.3.6, bootstrap-datepicker 1.0.1, jquery 1.9.1) Template modules, rest-crud-hibernate
Persistence Spring Data JPA / Hibernate (spring-boot-starter-data-jpa), H2 Database (com.h2database:h2), Spring Data Reactive MongoDB (spring-boot-starter-data-mongodb-reactive) rest-crud-hibernate, unit-testing, spring-webflux-demo
Security & Auth Spring Security, Spring Security OAuth2 (spring-security-oauth2-autoconfigure 2.1.8.RELEASE), JKS Keystore oauth2, ssl-https
Aspect-Oriented Programming Spring AOP (spring-boot-starter-aop), AspectJ, Log4j2 API (org.apache.logging.log4j) aop
Remoting Spring RMI (RmiServiceExporter, RmiProxyFactoryBean), Caucho Hessian (4.0.51 server / 4.0.62 client) spring-rmi
Email Spring Boot Mail (spring-boot-starter-mail / JavaMailSender) email
Logging Spring Boot default Logback / Commons Logging / SLF4J, explicit logback.xml logger-configuration, spring-webflux-demo
Testing spring-boot-starter-test, JUnit 3/4 (junit), JUnit 5 (junit-jupiter-api, junit-jupiter-engine, junit-platform-launcher), Mockito (mockito-junit-jupiter), WebTestClient, MockRestServiceServer, TestRestTemplate, reactor-test, @DataJpaTest Module src/test suites

Repository Architecture

The repository is structured as a single Maven multi-module project (pom.xml) with SpringExamples (com.springexamples.demo:SpringExamples:0.0.1-SNAPSHOT) acting as the parent POM.

  • Shared project-level configuration: Root pom.xml inherits from spring-boot-starter-parent:2.1.8.RELEASE, pins Java 1.8 and UTF-8 encoding, configures maven-jar-plugin, and declares 29 <module> entries. Root .gitignore excludes Maven target/, Eclipse metadata, archives, and binaries.
  • Independent example modules: 28 top-level modules are self-contained Spring Boot applications with their own pom.xml, source packages (com.springexamples.* or com.howtodoinjava.*), application.properties (where needed), and tests. None of the top-level modules depend on one another at compile time.
  • Nested multi-module group: spring-rmi acts as an intermediate aggregator (packaging: pom) grouping four separate Spring Boot modules (hessian-server, hessian-client, rmi-server, rmi-client) that interact over network protocols at runtime.
flowchart TD
    Root["SpringExamples (Root Parent POM - Spring Boot 2.1.8.RELEASE)"]

    Root --> Core["Bootstrapping & Config"]
    Root --> Server["Servers, Packaging & SSL"]
    Root --> Views["View Templates"]
    Root --> Rest["REST & Reactive Web"]
    Root --> Data["Data & Testing"]
    Root --> Cross["Cross-Cutting, Security & Remoting"]

    Core --> M1["minimum-setup"]
    Core --> M2["main-class"]
    Core --> M3["get-loaded-beans-info"]
    Core --> M4["disable-spring-boot-banner"]
    Core --> M5["custom-spring-boot-banner"]
    Core --> M6["command-line-runner"]
    Core --> M7["logger-configuration"]
    Core --> M8["enable-scheduling"]
    Core --> M9["i18n"]

    Server --> S1["context-path-server-port"]
    Server --> S2["server-customization"]
    Server --> S3["embedded-jetty-server"]
    Server --> S4["packaging-war"]
    Server --> S5["ssl-https"]

    Views --> V1["template-freemarker"]
    Views --> V2["template-thymeleaf"]
    Views --> V3["template-mustache"]
    Views --> V4["template-jsp"]

    Rest --> R1["rest-jersey-example"]
    Rest --> R2["rest-hateoas"]
    Rest --> R3["swagger-ui"]
    Rest --> R4["resttemplate"]
    Rest --> R5["spring-webflux-demo"]

    Data --> D1["rest-crud-hibernate"]
    Data --> D2["unit-testing"]

    Cross --> C1["aop"]
    Cross --> C2["email"]
    Cross --> C3["oauth2"]
    Cross --> C4["spring-rmi (Aggregator)"]

    C4 --> RM1["rmi-server"]
    C4 --> RM2["rmi-client"]
    C4 --> RM3["hessian-server"]
    C4 --> RM4["hessian-client"]
Loading

Module-by-Module Documentation

Every module declared in the root pom.xml (plus the four child modules under spring-rmi) is documented below based on its actual source files.

Core Bootstrapping & Configuration

minimum-setup

Concept: Minimal Spring Boot Web application setup and auto-configured REST endpoint.

Purpose: Provides the smallest working Spring Boot web baseline using spring-boot-starter-web.

Implementation:

  • Application: Entry point annotated with @SpringBootApplication.
  • HelloController: @RestController exposing index() via @RequestMapping("/") returning "Greetings from Spring Examples !!".
  • AppTest: Boilerplate JUnit 3 TestCase (assertTrue(true)).
  • Dependencies in minimum-setup/pom.xml: spring-boot-starter-web, spring-boot-starter-test.

Execution Flow: SpringApplication.run(Application.class, args) starts the embedded Tomcat container on port 8080, scans com.springexamples.demo and its subpackages, registers HelloController, and routes GET / requests to index().

How to Run:

mvn -pl minimum-setup spring-boot:run

Key Takeaways: @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan, eliminating manual web.xml or DispatcherServlet setup.


main-class

Concept: Specifying the executable main class when multiple entry points exist in the same artifact.

Purpose: Demonstrates how spring-boot-maven-plugin selects a single startup class via Maven properties when a module contains multiple main classes.

Implementation:

  • MainClassOne and MainClassTwo: Both classes are annotated with @SpringBootApplication and define main(String[] args).
  • main-class/pom.xml: Sets <start-class>com.springexamples.demo.MainClassOne</start-class> under <properties>.
  • AppTest: Boilerplate JUnit 3 TestCase.

Execution Flow: When packaged or run via Spring Boot's Maven plugin, <start-class> instructs the plugin to write Start-Class: com.springexamples.demo.MainClassOne into the executable JAR manifest rather than failing with an ambiguous main class error.

How to Run:

mvn -pl main-class spring-boot:run

Key Takeaways: If an artifact contains multiple main methods, <start-class> in pom.xml resolves the ambiguity for Spring Boot repackaging and spring-boot:run.


get-loaded-beans-info

Concept: Inspecting all Spring beans registered in the ApplicationContext.

Purpose: Lists every auto-configured and user-defined bean name loaded during startup.

Implementation:

  • Application: Defines a @Bean CommandLineRunner run(ApplicationContext appContext) lambda that invokes appContext.getBeanDefinitionNames(), sorts the array alphabetically, and prints each bean name to System.out.
  • AppTest: Boilerplate JUnit 3 TestCase.

Execution Flow: After Spring Boot refreshes the ApplicationContext, the CommandLineRunner bean executes once, querying getBeanDefinitionNames() on the live context and printing sorted bean names to standard output.

How to Run:

mvn -pl get-loaded-beans-info spring-boot:run

Key Takeaways: Injecting ApplicationContext into a CommandLineRunner bean is a straightforward way to debug auto-configuration and verify which beans are active at runtime.


disable-spring-boot-banner

Concept: Turning off the Spring Boot ASCII startup banner.

Purpose: Shows both the programmatic API and externalized property approaches for suppressing the startup banner.

Implementation:

Execution Flow: SpringApplication applies Banner.Mode.OFF before printing the banner, skipping console and log banner output during context initialization.

How to Run:

mvn -pl disable-spring-boot-banner spring-boot:run

Key Takeaways: Banner.Mode can be CONSOLE, LOG, or OFF, configurable either via SpringApplication.setBannerMode(...) or spring.main.banner-mode.


custom-spring-boot-banner

Concept: Replacing the default Spring Boot startup banner with custom text.

Purpose: Demonstrates classpath banner.txt discovery and Spring Boot version token interpolation.

Implementation:

Execution Flow: On startup, SpringBootBanner / ResourceBanner detects classpath:/banner.txt, resolves ${spring-boot.formatted-version}, and writes it to System.out.

How to Run:

mvn -pl custom-spring-boot-banner spring-boot:run

Key Takeaways: Placing banner.txt in src/main/resources automatically overrides the default banner without Java code changes.


command-line-runner

Concept: Executing initialization logic immediately after the Spring Boot ApplicationContext is loaded.

Purpose: Demonstrates implementing CommandLineRunner both on the main @SpringBootApplication class and on a separate @Component.

Implementation:

  • Application: Implements CommandLineRunner, overrides run(String... args), and logs "ApplicationStartupRunner run method Started !!".
  • ApplicationStartupRunner: @Component implementing CommandLineRunner with its own run(String... args) logging the same message.

Execution Flow: Spring Boot starts the embedded server and refreshes the context, then locates all beans implementing CommandLineRunner (both Application and ApplicationStartupRunner) and invokes run(args) on each before startup finishes.

How to Run:

mvn -pl command-line-runner spring-boot:run

Key Takeaways: Multiple CommandLineRunner beans can coexist in the same context; if execution order matters, pair them with @Order.


logger-configuration

Concept: Configuring log levels, log file destinations, and console/file formatting patterns via application.properties.

Purpose: Demonstrates Spring Boot's default Logback configuration properties without introducing a custom logback.xml.

Implementation:

  • Application: Implements CommandLineRunner using Apache Commons Logging (LogFactory.getLog(getClass())) to emit one INFO and one DEBUG statement on startup.
  • HelloController: Maps / to return "Greetings from Spring Examples !!".
  • logger-configuration/src/main/resources/application.properties: Sets logging.level.org.springframework=DEBUG, logging.level.com.springexamples=DEBUG, logging.file=${java.io.tmpdir}/application.log, logging.pattern.console, and logging.pattern.file.

Execution Flow: Spring Boot binds the logging.* properties to Logback during early initialization (LoggingApplicationListener), writes logs to both the console and ${java.io.tmpdir}/application.log, and outputs both INFO and DEBUG lines from Application.run.

How to Run:

mvn -pl logger-configuration spring-boot:run

Key Takeaways: Package-level logging (logging.level.<package>) and output formatting can be controlled without writing XML configuration files. Note that logging.pattern.file in this module omits the trailing n after %msg%, which causes file log entries to run together without newlines.


enable-scheduling

Concept: Running periodic background tasks with Spring's @Scheduled support.

Purpose: Demonstrates enabling the task scheduler and running a fixed-rate job.

Implementation:

  • App: Annotated with @SpringBootApplication and @EnableScheduling. Defines run() annotated with @Scheduled(initialDelay = 1000, fixedRate = 10000) to print Calendar.getInstance().getTime() to System.out.

Execution Flow: @EnableScheduling registers ScheduledAnnotationBeanPostProcessor. One second after startup (initialDelay = 1000), run() executes and repeats every 10 seconds (fixedRate = 10000) on Spring's default single-threaded task scheduler.

How to Run:

mvn -pl enable-scheduling spring-boot:run

Key Takeaways: @EnableScheduling activates @Scheduled method scanning; fixedRate schedules based on task start intervals, whereas fixedDelay waits after task completion.


i18n

Concept: Internationalization (i18n) of REST responses using MessageSource and Locale.

Purpose: Resolves localized messages from messages*.properties bundles based on the incoming HTTP request's Accept-Language header.

Implementation:

  • Application: Standard @SpringBootApplication.
  • HelloController: Autowires MessageSource and exposes GET / accepting Locale locale, returning messageSource.getMessage("error.notfound", null, locale).
  • Resource bundles: messages.properties (error.notfound=Resource not available) and messages_es.properties (error.notfound=Recurso no disponible).

Execution Flow: Spring Boot auto-configures MessageSource for messages on the classpath and uses AcceptHeaderLocaleResolver by default. A request with Accept-Language: es resolves messages_es.properties, while other locales fall back to messages.properties.

How to Run:

mvn -pl i18n spring-boot:run

Verify with curl:

curl -H "Accept-Language: es" http://localhost:8080/
curl -H "Accept-Language: en" http://localhost:8080/

Key Takeaways: Spring Boot automatically discovers messages*.properties at the classpath root and binds the resolved Locale directly into controller method parameters.


Embedded Servers, Packaging & SSL

context-path-server-port

Concept: Programmatic customization of the embedded servlet container port and context path.

Purpose: Demonstrates changing the server port and base URL path in Java using WebServerFactoryCustomizer.

Implementation:

  • CustomizationBean: @Component implementing WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>. Overrides customize(...) to call server.setPort(9000) and server.setContextPath("/springexamples").
  • Application: Standard SpringApplication startup.
  • context-path-server-port/src/main/resources/application.properties: Contains commented-out server.port=9000 and server.contextPath=/springexamples (note server.contextPath was the Spring Boot 1.x property name; Boot 2.x uses server.servlet.context-path).

Execution Flow: During embedded server initialization, Spring Boot applies CustomizationBean.customize(...) to the Tomcat factory before starting the server on port 9000 under /springexamples.

How to Run:

mvn -pl context-path-server-port spring-boot:run

Key Takeaways: WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> is the Spring Boot 2.x interface for programmatic server configuration (replacing Boot 1.x EmbeddedServletContainerCustomizer).


server-customization

Concept: Reference template for Tomcat/Jetty factory bean customization and server properties.

Purpose: Serves as a minimal placeholder showing commented-out TomcatServletWebServerFactory and JettyServletWebServerFactory @Bean methods and Jetty thread/post-size properties.

Implementation:

  • App: Active code runs SpringApplication.run(App.class, args) on default Tomcat settings; tomcatServerFactory() and jettyServerFactory() beans (configuring port 9000, /myapp, and 404 ErrorPage) are commented out.
  • server-customization/src/main/resources/application.properties: Contains commented-out server.port, server.servlet.context-path, server.jetty.acceptors, server.jetty.max-http-post-size, and server.jetty.selectors.

Execution Flow: As committed, the application boots a default embedded Tomcat server on port 8080 with no custom controllers.

How to Run:

mvn -pl server-customization spring-boot:run

Key Takeaways: Registering a ConfigurableServletWebServerFactory bean (such as TomcatServletWebServerFactory or JettyServletWebServerFactory) lets you configure ports, context paths, and custom ErrorPage mappings in code.


embedded-jetty-server

Concept: Swapping Spring Boot's default embedded Tomcat container for Eclipse Jetty.

Purpose: Shows the Maven dependency exclusion and replacement required to run a Spring Boot Web application on Jetty.

Implementation:

Execution Flow: Because Tomcat classes are absent from the classpath and Jetty classes are present, ServletWebServerFactoryAutoConfiguration selects JettyServletWebServerFactory and boots Jetty on port 8080.

How to Run:

mvn -pl embedded-jetty-server spring-boot:run

Key Takeaways: Switching embedded servlet containers in Spring Boot requires only excluding spring-boot-starter-tomcat and adding spring-boot-starter-jetty (or Undertow).


packaging-war

Concept: Configuring a Spring Boot project to build a deployable WAR archive.

Purpose: Demonstrates Maven WAR packaging with spring-boot-starter-tomcat marked as provided.

Implementation:

Execution Flow: mvn package produces a .war archive with Tomcat placed in WEB-INF/lib-provided so it remains executable via java -jar while avoiding servlet API clashes in external containers. Note that external container deployment without SpringBootServletInitializer requires adding extends SpringBootServletInitializer (see Practical Observations).

How to Run:

mvn -pl packaging-war package
mvn -pl packaging-war spring-boot:run

Key Takeaways: <packaging>war</packaging> combined with <scope>provided</scope> on spring-boot-starter-tomcat prepares the artifact for WAR packaging, and SpringBootServletInitializer is needed when deploying to a standalone Tomcat/servlet container.


ssl-https

Concept: Enabling HTTPS with a JKS keystore and adding an HTTP-to-HTTPS redirect connector on Tomcat.

Purpose: Demonstrates configuring SSL on port 8443 and redirecting plain HTTP traffic from port 8080.

Implementation:

  • SSLConfig: Defines a ServletWebServerFactory bean (TomcatServletWebServerFactory) that adds two additional connectors: redirectConnector() (http on 8080, redirectPort=8443) and createSslConnector() (https on 8443, Http11NioProtocol, loading keystore.jks with alias tomcat and configured keystore/truststore passwords).
  • HelloController: Maps / returning "Greetings from Spring Examples !!".
  • ssl-https/src/main/resources/application.properties: Configures server.port=8443, security.require-ssl=true (a Spring Boot 1.x property), and server.ssl.* keystore settings.

Execution Flow: Tomcat binds the configured HTTP (8080) and HTTPS (8443) connectors using keystore.jks. Because both application.properties (server.port=8443) and SSLConfig.createSslConnector() (connector.setPort(8443)) bind port 8443, see Practical Observations and Limitations before running.

How to Run:

mvn -pl ssl-https spring-boot:run

(Requires resolving the duplicate 8443 connector binding or running with a non-conflicting configuration; keystore uses demo credentials that should be replaced outside local testing.)

Key Takeaways: Adding a secondary HTTP connector with setRedirectPort(8443) works alongside Spring Security requiresSecure() (or server-level SSL configuration) to handle HTTP-to-HTTPS redirection.


Web View Templates

All four template modules share the same dependency pattern for static assets (org.webjars:bootstrap:3.3.6, bootstrap-datepicker:1.0.1, jquery:1.9.1) and a HomeController mapping / to view "home" with title ("Hi buddy") and message ("Welcome to SprinExamples.com").

template-freemarker

Concept: Server-side HTML rendering with Apache FreeMarker.

Purpose: Demonstrates configuring a custom FreeMarker template directory and rendering home and error views.

Implementation:

Execution Flow: GET / populates ModelMap and resolves "home" to classpath:/ftl/home.ftl via FreeMarkerViewResolver. Unhandled errors resolve to error.ftl.

How to Run:

mvn -pl template-freemarker spring-boot:run

Key Takeaways: spring.freemarker.templateLoaderPath moves templates from the default classpath:/templates/ directory to a custom location like classpath:/ftl/.


template-thymeleaf

Concept: Server-side HTML rendering with Thymeleaf.

Purpose: Demonstrates Spring Boot's zero-config Thymeleaf integration using standard templates/ paths.

Implementation:

Execution Flow: GET / invokes HomeController.home(ModelMap) and ThymeleafViewResolver renders classpath:/templates/home.html.

How to Run:

mvn -pl template-thymeleaf spring-boot:run

Key Takeaways: Thymeleaf works out of the box with spring-boot-starter-thymeleaf when .html files are placed in src/main/resources/templates/.


template-mustache

Concept: Logic-less server-side templating with Mustache and custom compiler defaults.

Purpose: Demonstrates customizing Mustache.Compiler to supply a fallback value for missing model keys.

Implementation:

  • App: Defines a @Bean Mustache.Compiler configured with MustacheEnvironmentCollector and .defaultValue("Some Default Value").
  • HomeController: Populates title and message for home.
  • Templates: home.mustache ({{title}}, {{message}}) and error.mustache ({{status}}, {{error}}).

Execution Flow: MustacheAutoConfiguration picks up the custom Mustache.Compiler bean and renders templates/home.mustache on GET /, falling back to "Some Default Value" for any unresolved Mustache tag.

How to Run:

mvn -pl template-mustache spring-boot:run

Key Takeaways: Defining a custom Mustache.Compiler bean overrides Spring Boot's default compiler behavior (such as null-key handling).


template-jsp

Concept: Rendering JavaServer Pages (JSP) with JSTL in Spring Boot.

Purpose: Shows the specific Maven dependencies, WEB-INF layout, and view resolver properties required to run JSPs on embedded Tomcat.

Implementation:

  • template-jsp/pom.xml: Adds javax.servlet:jstl and marks spring-boot-starter-tomcat and org.apache.tomcat.embed:tomcat-embed-jasper as provided.
  • App: Extends SpringBootServletInitializer and overrides configure(...).
  • template-jsp/src/main/resources/application.properties: Sets spring.mvc.view.prefix=/WEB-INF/jsp/, spring.mvc.view.suffix=.jsp, server.error.whitelabel.enabled=false, and server.error.include-stacktrace=always.
  • Views: home.jsp (uses JSTL core taglib) and error.jsp (renders ${timestamp}, ${error}, ${status}, ${message}, ${exception}, ${trace}).

Execution Flow: InternalResourceViewResolver maps "home" to /WEB-INF/jsp/home.jsp, compiled at runtime by tomcat-embed-jasper. Disabling the whitelabel error page routes errors to error.jsp.

How to Run:

mvn -pl template-jsp spring-boot:run

(Note: JSPs in Spring Boot do not work with executable JARs using Undertow or certain fat-JAR setups; running via spring-boot:run or WAR deployment ensures src/main/webapp is resolved.)

Key Takeaways: JSP requires tomcat-embed-jasper, jstl, explicit spring.mvc.view.prefix/suffix properties, and src/main/webapp instead of src/main/resources/templates.


REST APIs, Clients & Reactive WebFlux

rest-jersey-example

Concept: Building a JAX-RS CRUD REST API in Spring Boot using Jersey.

Purpose: Demonstrates JAX-RS (@Path, @GET, @POST, @PUT, @DELETE, @Consumes, @Produces) as an alternative to Spring MVC @RestController.

Implementation:

  • JerseydemoApplication: Extends SpringBootServletInitializer.
  • JerseyConfig: @Component extending Jersey's ResourceConfig, registering UserResource.class.
  • UserResource: JAX-RS endpoint at @Path("/users"):
    • GET /users -> Users JSON list
    • POST /users -> validates firstName/lastName, assigns ID size + 1, returns 201 with Content-Location
    • GET /users/{id} -> returns user JSON (200) or 404
    • PUT /users/{id} -> updates firstName/lastName and returns 200 (note: line 65 checks if(user == null) rather than if(temp == null))
    • DELETE /users/{id} -> removes user (200) or 404
  • UserDB: Static HashMap<Integer, User> preloaded with 3 users.
  • User & Users: JAXB-annotated POJOs.

Execution Flow: Jersey's ServletContainer handles incoming requests under /users, delegates to UserResource, and mutates the static in-memory UserDB map.

How to Run:

mvn -pl rest-jersey-example spring-boot:run

Key Takeaways: In Spring Boot + Jersey, endpoints must be explicitly registered on a ResourceConfig subclass (JerseyConfig) rather than relying solely on Spring's @RestController scanning.


rest-hateoas

Concept: Adding HATEOAS hypermedia _links to Jersey JAX-RS resources using Spring HATEOAS.

Purpose: Demonstrates combining Jersey endpoints with ResourceSupport models and ControllerLinkBuilder self-links.

Implementation:

  • rest-hateoas/pom.xml: Combines spring-boot-starter-jersey and spring-boot-starter-hateoas.
  • User, Users, and Report: Extend org.springframework.hateoas.ResourceSupport (Report is present in model/ though not referenced by UserResource).
  • UserResource: GET /users and GET /users/{id} use ControllerLinkBuilder.linkTo(UserResource.class).slash(user.getUserId()).withSelfRel() and attach the Link via user.add(...).
  • JerseyConfig and UserDB.

Execution Flow: GET /users and GET /users/{id} fetch records from UserDB, compute hypermedia self-links with ControllerLinkBuilder, attach them to User (ResourceSupport), and serialize the JSON response.

How to Run:

mvn -pl rest-hateoas spring-boot:run

Key Takeaways: Extending ResourceSupport allows domain models to carry HAL/hypermedia links built dynamically with ControllerLinkBuilder.


swagger-ui

Concept: Auto-generating interactive OpenAPI/Swagger 2 documentation for Spring MVC REST APIs.

Purpose: Configures Springfox Swagger2 and exposes the Swagger UI web interface.

Implementation:

  • swagger-ui/pom.xml: Adds io.springfox:springfox-swagger2:2.8.0 and io.springfox:springfox-swagger-ui:2.8.0.
  • Swagger2UiConfiguration: Annotated with @Configuration and @EnableSwagger2; implements WebMvcConfigurer. Defines a Docket bean filtering out org.springframework.boot internal controllers via Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")), and registers resource handlers for swagger-ui.html and /webjars/**.
  • HelloController: @GetMapping("/") annotated with @ApiOperation(value = "Get hello world message ", response = String.class).

Execution Flow: On startup, Springfox scans mapped controllers, builds the Swagger 2 specification JSON (available at /v2/api-docs), and serves the interactive UI at /swagger-ui.html.

How to Run:

mvn -pl swagger-ui spring-boot:run

Then open http://localhost:8080/swagger-ui.html.

Key Takeaways: Filtering out org.springframework.boot keeps Spring Boot's internal BasicErrorController out of your public Swagger API specification.


resttemplate

Concept: Configuring a pooled Apache HttpClient-backed RestTemplate and testing it with MockRestServiceServer.

Purpose: Shows connection pooling, SSL self-signed trust strategy, timeouts, keep-alive headers, idle connection eviction, and slice testing for REST clients.

Implementation:

  • HttpClientConfig: @Configuration + @EnableScheduling. Configures PoolingHttpClientConnectionManager (max 50 connections, TrustSelfSignedStrategy), ConnectionKeepAliveStrategy (reads Keep-Alive timeout header or defaults to 20000 ms), CloseableHttpClient (CONNECT_TIMEOUT=30000, REQUEST_TIMEOUT=30000, SOCKET_TIMEOUT=60000), and a @Scheduled(fixedDelay = 10000) Runnable (idleConnectionMonitor) that closes expired/idle connections (30 s).
  • RestTemplateConfig: Creates HttpComponentsClientHttpRequestFactory, RestTemplate, and a ThreadPoolTaskScheduler (poolSize=50).
  • UserService & UserServiceImpl: Calls restTemplate.getForObject("http://localhost:8080/users", String.class).
  • Application: Imports HttpClientConfig and RestTemplateConfig via @Import (the call to userService.testUserService() in run is commented out).
  • resttemplate/src/main/resources/application.properties: Sets server.port=9000, server.contextPath=/springexamples, and spring.main.allow-bean-definition-overriding=true.
  • UserServiceTest: Uses @RestClientTest(UserServiceImpl.class), @AutoConfigureWebClient(registerRestTemplate = true), and MockRestServiceServer to assert the request to http://localhost:8080/users returns <users></users>.

Execution Flow: In test mode, @RestClientTest binds MockRestServiceServer to the auto-configured RestTemplate so UserServiceImpl.testUserService() executes without a live HTTP server. In runtime mode, HttpClientConfig starts the connection pool and background eviction task.

How to Run:

mvn -pl resttemplate test
mvn -pl resttemplate spring-boot:run

Key Takeaways: Production RestTemplate instances should wrap a configured HTTP client pool (PoolingHttpClientConnectionManager) with explicit connect/socket timeouts and idle-connection cleanup, and can be verified in isolation with @RestClientTest.


spring-webflux-demo

Concept: Reactive non-blocking REST API backed by Reactive MongoDB, Project Reactor (Mono/Flux), and @WebFluxTest.

Purpose: Demonstrates annotation-based Spring WebFlux controllers, SSE streaming, reactive MongoDB repositories, and WebTestClient testing with JUnit 5.

Implementation:

  • WebfluxFunctionalApp: Entry point (@SpringBootApplication). (Despite the class name, routes are annotation-based in EmployeeController rather than RouterFunction beans.)
  • MongoConfig: Extends AbstractReactiveMongoConfiguration with @EnableReactiveMongoRepositories(basePackages = "com.howtodoinjava.demo.dao"). Creates MongoClients.create() and ReactiveMongoTemplate using mongodb.dbname (testdb) and mongodb.port (27017 injected via @Value).
  • AppConfig & WebFluxConfig: PropertyPlaceholderConfigurer for application.properties and @EnableWebFlux.
  • Employee: MongoDB @Document (id, name, salary) annotated with @Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS).
  • EmployeeRepository: Extends ReactiveMongoRepository<Employee, Integer> with @Query("{ 'name': ?0 }") Flux<Employee> findByName(String name).
  • IEmployeeService & EmployeeService: Delegates reactive operations to EmployeeRepository (create calls .subscribe()).
  • EmployeeController: Exposes POST /create (and /), GET /{id}, GET /name/{name}, GET / (MediaType.TEXT_EVENT_STREAM_VALUE), PUT /update, and DELETE /delete/{id}.
  • logback.xml: Console appender logging org.springframework at DEBUG and root at ERROR.
  • EmployeeControllerTest: JUnit 5 @WebFluxTest(controllers = EmployeeController.class) with @Import(EmployeeService.class), @MockBean EmployeeRepository, and WebTestClient (testCreateEmployee, testGetEmployeesByName, testGetEmployeeById, testDeleteEmployee). Note: testDeleteEmployee sends webClient.get().uri("/delete/{id}", 1) while the controller maps @DeleteMapping("/delete/{id}")—see Practical Observations and Limitations.

Execution Flow: Incoming reactive HTTP requests are handled on Netty's event loop, returning Mono<Employee> or Flux<Employee> streams from ReactiveMongoRepository without blocking threads. GET / streams results as text/event-stream.

How to Run:

  • Running the application requires a local MongoDB instance on localhost:27017 (testdb):
    mvn -pl spring-webflux-demo spring-boot:run
  • WebFlux controller slice tests (mocked repository):
    mvn -pl spring-webflux-demo test

Key Takeaways: Reactive endpoints return Mono (0..1) and Flux (0..N) publishers and require non-blocking data drivers (ReactiveMongoRepository); @WebFluxTest paired with WebTestClient and @MockBean tests reactive routes without starting MongoDB.


Data Persistence & Testing

rest-crud-hibernate

Concept: CRUD REST API with Spring Data JPA, Hibernate, H2 database, SQL initialization scripts, and @DataJpaTest.

Purpose: Demonstrates full-stack entity mapping, repository abstraction, custom 404 exception handling, H2 file persistence, and JPA slice testing.

Implementation:

  • DemoApplication: Standard @SpringBootApplication.
  • EmployeeEntity: JPA @Entity mapped to TBL_EMPLOYEES (id with GenerationType.IDENTITY, firstName, lastName, email non-null).
  • EmployeeRepository: Extends JpaRepository<EmployeeEntity, Long>.
  • EmployeeService: Implements getAllEmployees(), getEmployeeById(Long), createOrUpdateEmployee(EmployeeEntity), and deleteEmployeeById(Long), throwing RecordNotFoundException (@ResponseStatus(HttpStatus.NOT_FOUND)).
  • EmployeeController: @RestController under /employees exposing GET /employees, GET /employees/{id}, POST /employees (binds EmployeeEntity parameters without @RequestBody), and DELETE /employees/{id} (returns HttpStatus.FORBIDDEN).
  • Database scripts & config: schema.sql, data.sql (inserts 2 rows), and application.properties (jdbc:h2:file:C:/temp/test, H2 console at /h2, spring.jpa.hibernate.ddl-auto=none, SQL formatting enabled).
  • Templates: list-employees.html and add-edit-employee.html (Thymeleaf UI pages targeting /edit, /delete/{id}, /createEmployee, though the current EmployeeController is a @RestController at /employees).
  • Tests: DemoApplicationTests (@SpringBootTest) and EmployeeRepositoryTest (@DataJpaTest).

Execution Flow: On startup, Spring Boot executes schema.sql and data.sql against the H2 datasource. Requests to /employees pass through EmployeeController -> EmployeeService -> EmployeeRepository -> Hibernate/H2.

How to Run:

mvn -pl rest-crud-hibernate test
mvn -pl rest-crud-hibernate spring-boot:run

(Note: application.properties configures jdbc:h2:file:C:/temp/test, which is Windows-path specific when running the full app.)

Key Takeaways: @DataJpaTest spins up an embedded in-memory database and scans only JPA entities and repositories, making repository tests fast without loading web controllers.


unit-testing

Concept: Comparing isolated unit tests (JUnit 5 + Mockito) with full integration tests (@SpringBootTest + TestRestTemplate + @Sql).

Purpose: Demonstrates testing both a @RestController directly with mocked dependencies and end-to-end over HTTP with an in-memory H2 database.

Implementation:

  • SpringBootDemoApplication: Standard @SpringBootApplication.
  • Employee & Employees: JPA entity mapped to tbl_employees (GenerationType.AUTO) and JSON list wrapper.
  • EmployeeRepository: Extends CrudRepository<Employee, Long>.
  • EmployeeController: Exposes GET /employees (returns Employees) and POST /employees (@RequestBody Employee, saves entity, builds URI via ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"), returns 201 Created with Location header).
  • CustomExceptionHandler & ErrorResponse: @ControllerAdvice handling ServletRequestBindingException (400) and generic Exception (500).
  • EmployeeControllerUnitTests: JUnit 5 @ExtendWith(MockitoExtension.class) using @Mock EmployeeRepository, @InjectMocks EmployeeController, and MockHttpServletRequest bound to RequestContextHolder so ServletUriComponentsBuilder works outside a servlet container.
  • EmployeeControllerIntegrationTests: @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) with @LocalServerPort, TestRestTemplate, and @Sql({ "schema.sql", "data.sql" }) loading 3 rows before testAllEmployees().
  • Test SQL & config: application.properties (jdbc:h2:mem:testdb), schema.sql, data.sql.

Execution Flow: EmployeeControllerUnitTests executes controller methods purely in memory without starting Spring. EmployeeControllerIntegrationTests boots the entire application on a random port, runs schema.sql/data.sql, and makes real HTTP calls via TestRestTemplate.

How to Run:

mvn -pl unit-testing test

Key Takeaways: Use @ExtendWith(MockitoExtension.class) for fast controller logic tests (binding RequestContextHolder when testing URI builders) and @SpringBootTest(webEnvironment = RANDOM_PORT) + @Sql to verify serialization, routing, and persistence together.


Security, AOP, Scheduling, Email, i18n & Remoting

aop

Concept: Cross-cutting method execution profiling using Spring AOP and @Aspect.

Purpose: Measures and logs method execution times across the com.howtodoinjava.aop package using @Around advice.

Implementation:

Execution Flow: Spring AOP wraps DomainService in a proxy. Calls to getDomainObjectById pass through LoggingAspect.profileAllMethods(ProceedingJoinPoint), which starts a StopWatch, invokes proceed(), stops the timer, and logs the elapsed milliseconds.

How to Run:

mvn -pl aop test

Key Takeaways: @Around advice with ProceedingJoinPoint and StopWatch cleanly separates timing/profiling logic from business services without modifying service methods.


email

Concept: Sending plain-text, pre-configured template, attachment, and inline HTML emails with JavaMailSender.

Purpose: Demonstrates Spring Boot's mail auto-configuration and MimeMessageHelper.

Implementation:

  • Application: Implements CommandLineRunner and calls emailService.sendMail(...) and emailService.sendPreConfiguredMail(...) on startup.
  • EmailConfig: @Configuration declaring a @Bean SimpleMailMessage emailTemplate() with sample recipient, sender, subject, and body.
  • EmailService: @Service("emailService") injecting JavaMailSender and SimpleMailMessage. Provides four methods:
    • sendMail(to, subject, body)
    • sendPreConfiguredMail(message)
    • sendMailWithAttachment(to, subject, body, fileToAttach) using MimeMessagePreparator and MimeMessageHelper(..., true)
    • sendMailWithInlineResources(to, subject, fileToAttach) embedding an inline image via cid:identifier1234
  • email/src/main/resources/application.properties: Configures spring.mail.host=smtp.gmail.com, port=25, STARTTLS, timeouts (5000 ms), and placeholder credentials (spring.mail.username / spring.mail.password).

Execution Flow: Because Application implements CommandLineRunner, starting the app immediately attempts to connect to the configured SMTP server and send two emails.

How to Run: Update spring.mail.host, spring.mail.port, spring.mail.username, and spring.mail.password in email/src/main/resources/application.properties (and update the target address in Application) before running:

mvn -pl email spring-boot:run

Key Takeaways: Use SimpleMailMessage for plain-text emails and MimeMessagePreparator + MimeMessageHelper (multipart=true) for attachments and inline cid: HTML resources.


oauth2

Concept: Securing an application with an embedded OAuth2 Authorization Server, Resource Server, and Spring Security form login.

Purpose: Demonstrates AuthorizationServerConfigurerAdapter, ResourceServerConfigurerAdapter, and WebSecurityConfigurerAdapter working together in a single Spring Boot application.

Implementation:

  • SpringOauth2ResourceServerApplication: @SpringBootApplication extending WebSecurityConfigurerAdapter.
  • OAuth2AuthorizationServer: @EnableAuthorizationServer configuring /oauth/token_key (permitAll()), /oauth/check_token (isAuthenticated()), form client auth, and an in-memory client (clientapp, BCryptPasswordEncoder-encoded demo secret, grant types password, authorization_code, refresh_token, scope read_profile_info, resourceId oauth2-resource, redirect URI http://localhost:8081/login, token validities 5000s / 50000s).
  • OAuth2ResourceServer: @EnableResourceServer permitting / and requiring authentication on /api/v1/**.
  • SecurityConfig: @Order(1) WebSecurityConfigurerAdapter securing /login and /oauth/authorize with form login, defining an in-memory USER account (humptydumpty) and a BCryptPasswordEncoder bean.
  • RestResource & UserProfile: Controller mapped at /api/users/me reading the authenticated User from SecurityContextHolder. (Note: OAuth2ResourceServer secures /api/v1/** while RestResource exposes /api/users/me.)
  • SpringOauth2ResourceServerApplicationTests: @SpringBootTest contextLoads() test.

Execution Flow: When a client requests authorization at /oauth/authorize, SecurityConfig (@Order(1)) prompts for user login via form login, issues an authorization code to the redirect URI, and exchanges it at /oauth/token via OAuth2AuthorizationServer for a bearer token.

How to Run:

mvn -pl oauth2 test
mvn -pl oauth2 spring-boot:run

(Replace the hardcoded demo credentials in OAuth2AuthorizationServer and SecurityConfig before any non-local deployment.)

Key Takeaways: When combining form-based login (SecurityConfig) with @EnableResourceServer in the same app, @Order(1) ensures the form-login filter chain handles /login and /oauth/authorize before the resource server filter chain intercepts API paths.


spring-rmi

Concept: Exposing and consuming remote Java services over Spring RMI and Caucho Hessian.

Purpose: Groups four independent client/server Spring Boot modules under spring-rmi/pom.xml to compare binary Java RMI (RmiServiceExporter/RmiProxyFactoryBean) with HTTP-based Hessian remoting (HessianServiceExporter/HessianProxyFactoryBean).

spring-rmi/rmi-server
spring-rmi/rmi-client
spring-rmi/hessian-server
spring-rmi/hessian-client
  • HessianClientApplication: Declares HessianProxyFactoryBean pointing to http://localhost:8080/hellohessian for HelloWorld, then calls helloWorld.sayHelloWithHessian("Sajal") inside main().
  • application.properties: Sets server.port = 9090 so it does not collide with hessian-server on 8080.
  • Uses com.caucho:hessian:4.0.62.

Execution Flow: Start the server module first so the RMI registry (1099) or HTTP Hessian endpoint (8080/hellohessian) is listening; then launch the matching client module, which invokes the remote method during main() and prints the server's response.

How to Run:

# Terminal 1 (RMI)
mvn -pl spring-rmi/rmi-server spring-boot:run
# Terminal 2 (RMI)
mvn -pl spring-rmi/rmi-client spring-boot:run

# Terminal 1 (Hessian)
mvn -pl spring-rmi/hessian-server spring-boot:run
# Terminal 2 (Hessian)
mvn -pl spring-rmi/hessian-client spring-boot:run

Key Takeaways: RmiServiceExporter uses Java RMI over TCP (1099), while HessianServiceExporter exposes a binary protocol over HTTP (BeanNameUrlHandlerMapping using the bean name "/hellohessian" as the URL path). Note that rmi-client's pom.xml sets its <parent> directly to SpringExamples rather than spring-rmi, though spring-rmi/pom.xml lists all four as <modules>.


Core Spring Boot Concepts

Application Startup & Auto-Configuration

SpringApplication.run(...) creates the ApplicationContext, applies environment properties (application.properties), runs ApplicationContextInitializers, and triggers @EnableAutoConfiguration (bundled inside @SpringBootApplication). Auto-configuration inspects classpath libraries and user beans (@ConditionalOnClass, @ConditionalOnMissingBean) to configure Tomcat, Jetty, Jackson, JPA, Thymeleaf, or WebFlux automatically.

Inversion of Control (IoC), Spring Beans & Component Scanning

Spring's IoC container instantiates, wires, and manages objects ("beans") rather than application code creating dependencies with new. @ComponentScan (part of @SpringBootApplication) scans the main class's package and all subpackages for stereotypes (@Component, @Service, @Repository, @Controller, @RestController, @Configuration). Explicit factory methods annotated with @Bean inside @Configuration classes register third-party or customized objects.

Dependency Injection

Dependencies are supplied by the container via @Autowired fields (used across controllers and services in this repo) or bean method parameters (such as CommandLineRunner run(ApplicationContext appContext) in get-loaded-beans-info).

Application Runners (CommandLineRunner)

CommandLineRunner defines void run(String... args) and executes once the ApplicationContext is fully initialized. It is suited for startup verification, seed loading, or CLI execution.

Embedded Servers & Customization

spring-boot-starter-web embeds Tomcat by default. Exclusions in pom.xml swap it for Jetty, while WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> or TomcatServletWebServerFactory beans customize ports, context paths, SSL connectors, and error pages.

Scheduling

@EnableScheduling activates background polling/cron execution for @Scheduled methods. fixedRate runs on a steady cadence from invocation start; fixedDelay pauses for the specified duration after the previous execution returns.

Logging

Spring Boot routes logging through SLF4J + Logback by default and exposes logging.level.*, logging.file, and logging.pattern.* properties, while also supporting explicit logback.xml configuration.

Spring AOP

Spring AOP creates dynamic proxies around target beans to intercept method calls matching an AspectJ pointcut expression (execution(...)). @Around advice wraps the target invocation using ProceedingJoinPoint.proceed().

REST Architecture (Spring MVC, JAX-RS, HATEOAS, Client)

  • Spring MVC: @RestController + @GetMapping/@PostMapping/@PutMapping/@DeleteMapping + ResponseEntity + @ControllerAdvice global exception handling (rest-crud-hibernate, unit-testing).
  • JAX-RS (Jersey): Standard @Path, @Produces, @Consumes, and Response registered via ResourceConfig (rest-jersey-example).
  • HATEOAS: Embedding navigable Link objects into payloads (ResourceSupport, ControllerLinkBuilder) in rest-hateoas.
  • Client side: RestTemplate backed by Apache HttpClient connection pooling (resttemplate).

Spring Security & OAuth2

Spring Security builds a chain of servlet filters (WebSecurityConfigurerAdapter) to authenticate requests and enforce authorization rules. @EnableAuthorizationServer exposes /oauth/authorize and /oauth/token for issuing bearer tokens, while @EnableResourceServer validates bearer tokens on protected API routes.

Database Integration (Hibernate & JPA)

@Entity maps Java classes to relational tables (TBL_EMPLOYEES). Extending JpaRepository or CrudRepository provides CRUD methods without boilerplate SQL, backed by Hibernate and an H2 datasource.

Reactive Programming & Spring WebFlux

WebFlux runs on non-blocking Netty I/O using Project Reactor types (Mono for 0–1 item, Flux for 0–N items). Instead of blocking JDBC calls, it pairs with ReactiveMongoRepository and supports Server-Sent Events (MediaType.TEXT_EVENT_STREAM_VALUE).

Testing Strategies

The repository exercises four distinct Spring testing levels:

  1. Pure unit tests (@ExtendWith(MockitoExtension.class), @Mock, @InjectMocks): EmployeeControllerUnitTests
  2. JPA slice tests (@DataJpaTest): EmployeeRepositoryTest
  3. Web client / WebFlux slice tests (@RestClientTest + MockRestServiceServer, @WebFluxTest + WebTestClient + @MockBean): UserServiceTest, EmployeeControllerTest
  4. Full integration tests (@SpringBootTest(webEnvironment = RANDOM_PORT) + TestRestTemplate + @Sql): EmployeeControllerIntegrationTests

Important Annotations Reference

Annotation Purpose Where It Is Used
@SpringBootApplication Marks the main configuration class; enables auto-configuration and component scanning. Root entry class in every application module
@Configuration Declares a class as a source of @Bean definitions. EmailConfig, SSLConfig, HttpClientConfig
@Bean Registers the returned object as a managed bean in the ApplicationContext. get-loaded-beans-info, template-mustache, spring-rmi
@Component Generic stereotype marking a class for component scanning. ApplicationStartupRunner, CustomizationBean, JerseyConfig
@Service Specialization of @Component for business-layer beans. DomainService, EmployeeService, EmailService
@Repository Marks a DAO/repository bean and enables persistence exception translation. EmployeeRepository, EmployeeRepository (unit-testing)
@Controller / @RestController Marks Spring MVC web controllers (@RestController adds @ResponseBody). HomeController, EmployeeController
@Autowired Injects matching beans by type into fields or parameters. HelloController, OAuth2AuthorizationServer
@Import Explicitly imports additional @Configuration classes into the context. Application (resttemplate), EmployeeControllerTest
@Value Injects externalized property values (e.g., ${mongodb.dbname}). MongoConfig
@EnableScheduling / @Scheduled Enables Spring's task scheduler and marks periodic execution methods. App (enable-scheduling), HttpClientConfig
@Aspect / @Around Defines an AOP aspect and around-advice intercepting matching join points. LoggingAspect
@Entity / @Table / @Id / @GeneratedValue / @Column JPA object-relational mapping annotations. EmployeeEntity, Employee
@Document / @EnableReactiveMongoRepositories / @Query Maps MongoDB documents and configures reactive repositories/queries. Employee, MongoConfig, EmployeeRepository
@Scope Controls bean lifecycle scope (request scope with TARGET_CLASS proxy). Employee (webflux)
@ControllerAdvice / @ExceptionHandler / @ResponseStatus Centralizes exception-to-HTTP-response mapping. CustomExceptionHandler, RecordNotFoundException
@RequestMapping / @GetMapping / @PostMapping / @PutMapping / @DeleteMapping Maps HTTP methods and paths to controller handler methods. EmployeeController, EmployeeController (webflux)
@PathVariable / @RequestBody Binds URI template variables and deserializes HTTP request bodies. EmployeeController (unit-testing)
@Path / @GET / @POST / @PUT / @DELETE / @PathParam / @Consumes / @Produces Standard JAX-RS annotations for Jersey REST endpoints. UserResource (rest-jersey-example), UserResource (rest-hateoas)
@EnableAuthorizationServer / @EnableResourceServer / @Order Enables Spring Security OAuth2 endpoints and orders security filter chains. OAuth2AuthorizationServer, OAuth2ResourceServer, SecurityConfig
@EnableSwagger2 / @ApiOperation Enables Springfox Swagger 2 scanning and documents API operations. Swagger2UiConfiguration, HelloController
@EnableWebFlux Explicitly activates Spring WebFlux configuration. WebFluxConfig
@SpringBootTest / @DataJpaTest / @WebFluxTest / @RestClientTest Configures full or sliced Spring test contexts. src/test in aop, oauth2, rest-crud-hibernate, unit-testing, spring-webflux-demo, resttemplate
@MockBean / @ExtendWith / @Mock / @InjectMocks / @Sql Test mocking, JUnit 5 extension wiring, and test database script execution. EmployeeControllerTest, EmployeeControllerUnitTests, EmployeeControllerIntegrationTests

Configuration Reference

Server & Banner Settings

Template & View Settings

  • spring.freemarker.templateLoaderPath=classpath:/ftl/: template-freemarker.
  • spring.mvc.view.prefix=/WEB-INF/jsp/ and spring.mvc.view.suffix=.jsp: template-jsp.

Database Settings

  • File-backed H2 (rest-crud-hibernate): spring.datasource.url=jdbc:h2:file:C:/temp/test (Windows path; change on Linux/macOS or switch to jdbc:h2:mem:testdb), spring.h2.console.enabled=true, spring.h2.console.path=/h2, spring.jpa.hibernate.ddl-auto=none, spring.jpa.show-sql=true (application.properties).
  • In-memory H2 (unit-testing): spring.datasource.url=jdbc:h2:mem:testdb, spring.h2.console.enabled=true (application.properties).
  • Reactive MongoDB (spring-webflux-demo): mongodb.port=27017, mongodb.dbname=testdb (application.properties).

Logging Settings

  • logger-configuration: logging.level.org.springframework=DEBUG, logging.level.com.springexamples=DEBUG, logging.file=${java.io.tmpdir}/application.log, and custom logging.pattern.console / logging.pattern.file.
  • aop: logging.pattern.console=%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n.
  • spring-webflux-demo: XML-based Logback STDOUT appender.

Mail, Security & SSL Settings (Change Before Running)

  • Email (email/src/main/resources/application.properties): Configures spring.mail.host=smtp.gmail.com, spring.mail.port=25, STARTTLS, and placeholder spring.mail.username / spring.mail.password. Replace the placeholders and recipient address before running.
  • SSL/HTTPS (ssl-https): application.properties and SSLConfig reference keystore.jks with placeholder demo passwords. Generate your own keystore and update credentials before non-local use.
  • OAuth2 (oauth2): OAuth2AuthorizationServer and SecurityConfig use hardcoded demo credentials in memory. Replace with externalized or persistent credential storage for real applications.

Installation and Execution

Prerequisites

  • JDK: Java 8 (JDK 1.8) is configured in pom.xml. Verify with:
    java -version
  • Maven: Apache Maven 3.x+ (root README.md originally mentioned Eclipse Photon and Maven; standard Maven 3.5+ works cleanly with Spring Boot 2.1.8.RELEASE). Verify with:
    mvn -version
  • Optional external services (module-specific):
    • Local MongoDB on port 27017 when running spring-webflux-demo (not required for mvn -pl spring-webflux-demo test).
    • Valid SMTP account credentials when running email.

Building and Running

Clone and inspect:

git clone <repository-url>
cd SpringExamples

Compile all modules without running tests:

mvn clean compile

Run a specific module:

Linux / macOS / Git Bash:

mvn -pl minimum-setup spring-boot:run

Windows PowerShell:

mvn -pl minimum-setup spring-boot:run

Build an individual module JAR/WAR and run it directly:

mvn -pl swagger-ui package -DskipTests
java -jar swagger-ui/target/swagger-ui-0.0.1-SNAPSHOT.jar

(On Windows CMD/PowerShell, java -jar swagger-ui\target\swagger-ui-0.0.1-SNAPSHOT.jar.)

Run tests for a specific module:

mvn -pl unit-testing test
mvn -pl rest-crud-hibernate test
mvn -pl resttemplate test
mvn -pl spring-webflux-demo test

Troubleshooting

  • Port 8080 already in use: Stop the previous Spring Boot module before starting another, or override the port on the command line:
    mvn -pl minimum-setup spring-boot:run -Dspring-boot.run.arguments=--server.port=8085
  • Windows H2 path on Linux/macOS (rest-crud-hibernate): Update spring.datasource.url in rest-crud-hibernate/src/main/resources/application.properties from jdbc:h2:file:C:/temp/test to a local path or jdbc:h2:mem:testdb.
  • spring-rmi client failures: Ensure rmi-server or hessian-server is running before starting rmi-client or hessian-client, as both clients execute a remote call immediately inside main().
  • Java version mismatch (JDK 11+): Spring Boot 2.1.8.RELEASE targets Java 8; modules like rest-hateoas and spring-webflux-demo rely on JAXB (javax.xml.bind), which was removed from the JDK in Java 11 (only spring-webflux-demo declares an explicit jaxb-api dependency). Running on JDK 8 avoids module-path errors.

Learning Roadmap

All modules are independent Maven subprojects; you can study any module on its own. For structured learning or revision, follow this progression:

  1. Spring Boot Foundations: minimum-setup -> main-class -> get-loaded-beans-info -> disable-spring-boot-banner -> custom-spring-boot-banner -> command-line-runner
  2. Configuration, Logging & Runtime Customization: logger-configuration -> context-path-server-port -> server-customization -> embedded-jetty-server -> packaging-war
  3. Core Application Features: enable-scheduling -> i18n -> aop -> email
  4. Server-Side Web Templates: template-thymeleaf -> template-freemarker -> template-mustache -> template-jsp
  5. REST APIs, Documentation & Clients: swagger-ui -> rest-jersey-example -> rest-hateoas -> resttemplate
  6. Data Persistence & Testing: rest-crud-hibernate -> unit-testing
  7. Reactive, Security & Remoting: spring-webflux-demo -> ssl-https -> oauth2 -> spring-rmi

Interview Preparation

1. What does @SpringBootApplication actually replace? It is a convenience meta-annotation combining @SpringBootConfiguration (a @Configuration variant), @EnableAutoConfiguration (triggers classpath-driven bean registration), and @ComponentScan (scans the annotated class's package and subpackages). See minimum-setup.

2. Why does main-class need <start-class> in pom.xml? spring-boot-maven-plugin inspects bytecode for a main method during repackaging. Having both MainClassOne and MainClassTwo creates ambiguity, which <start-class> resolves explicitly.

3. How do you switch embedded servlet containers from Tomcat to Jetty? Exclude spring-boot-starter-tomcat from spring-boot-starter-web and add spring-boot-starter-jetty. Auto-configuration checks for container classes on the classpath via @ConditionalOnClass. See embedded-jetty-server/pom.xml.

4. How does WebServerFactoryCustomizer differ from application.properties for server configuration? server.port and server.servlet.context-path handle declarative values cleanly, whereas WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> allows programmatic logic (conditional ports, custom ErrorPages, or adding multiple Tomcat connectors as in SSLConfig).

5. What is the difference between @RestController and Jersey @Path resources in Spring Boot? @RestController routes through Spring MVC's DispatcherServlet. Jersey (spring-boot-starter-jersey) uses JAX-RS (@Path, @GET, Response) and requires explicit registration on a ResourceConfig subclass (JerseyConfig).

6. How does RestTemplate avoid exhausting sockets under load? By replacing the default SimpleClientHttpRequestFactory with HttpComponentsClientHttpRequestFactory backed by Apache PoolingHttpClientConnectionManager, explicit connect/socket timeouts, a ConnectionKeepAliveStrategy, and a scheduled monitor closing expired/idle connections. See HttpClientConfig.

7. When should you use @ExtendWith(MockitoExtension.class), @DataJpaTest, @WebFluxTest, or @SpringBootTest?

8. Why does EmployeeControllerUnitTests set RequestContextHolder.setRequestAttributes(...)? EmployeeController.addEmployee uses ServletUriComponentsBuilder.fromCurrentRequest(), which reads the current HTTP request from a ThreadLocal in RequestContextHolder. In a pure unit test without Tomcat/MockMvc, that ThreadLocal is empty unless populated with a MockHttpServletRequest.

9. How does @Around advice work in Spring AOP? Spring creates a runtime proxy around the target bean (DomainService). The advice method receives a ProceedingJoinPoint, runs setup logic (such as starting StopWatch), delegates to the target via proceed(), and executes post-processing (logging elapsed time) before returning the result. See LoggingAspect.

10. What changes when moving from Spring MVC + JPA to Spring WebFlux + Reactive MongoDB? Controllers return non-blocking Mono<T> / Flux<T> publishers rather than concrete objects, repositories extend ReactiveMongoRepository instead of JpaRepository, and blocking JDBC drivers are replaced by reactive database drivers so event-loop threads are never blocked. See spring-webflux-demo.

11. Why does SecurityConfig in oauth2 specify @Order(1)? Both SecurityConfig (WebSecurityConfigurerAdapter) and OAuth2ResourceServer (ResourceServerConfigurerAdapter) register SecurityFilterChains. Assigning @Order(1) to SecurityConfig ensures /login and /oauth/authorize are matched by form-login security before the resource server's default filter order (Order(3)).


Practical Observations and Limitations

The items below are direct observations from inspecting the current source files (distinct from future enhancements):

  1. Framework & Dependency Age: The repository targets Spring Boot 2.1.8.RELEASE and Java 8 (1.8). Spring Boot 2.1.x reached end-of-life, and spring-security-oauth2-autoconfigure (2.1.8.RELEASE) and Springfox 2.8.0 are legacy stacks superseded by Spring Authorization Server / Spring Security OAuth2 Resource Server and Springdoc OpenAPI.
  2. Legacy JUnit 3 Placeholder Tests: Modules including command-line-runner, context-path-server-port, custom-spring-boot-banner, disable-spring-boot-banner, embedded-jetty-server, enable-scheduling, get-loaded-beans-info, logger-configuration, main-class, minimum-setup, packaging-war, rest-hateoas, rest-jersey-example, server-customization, ssl-https, swagger-ui, and all four template-* modules contain boilerplate JUnit 3 AppTest classes (assertTrue(true)) rather than Spring Boot context or MVC assertions.
  3. Code Bugs & Mismatches Observed in Source:
  4. Demo Credentials & OS-Specific Paths: email, oauth2, and ssl-https contain placeholder/demo credentials intended strictly for local walkthroughs, and rest-crud-hibernate hardcodes C:/temp/test in application.properties.

Future Improvements

  • Fix the verified source issues listed above (the extra ) in LoggingAspect, webClient.delete() in EmployeeControllerTest, temp == null check in rest-jersey-example, entity.getId() == null guard in rest-crud-hibernate, and /api/v1/** route alignment in oauth2).
  • Replace the legacy JUnit 3 AppTest placeholders with real @SpringBootTest / MockMvc tests across the basic and template modules.
  • Externalize demo credentials in email, oauth2, and ssl-https via environment variables or profile-specific property files.
  • Add a shared spring-rmi-api module for HelloWorld and HelloWorldRMI interfaces instead of duplicating them in both server and client modules.
  • Upgrade a separate branch or follow-up repository to Spring Boot 3.x / Java 17+ (jakarta.*, Springdoc OpenAPI, and current Spring Security OAuth2).

Conclusion

This repository serves as a hands-on reference across 29 Spring Boot 2.1.8.RELEASE modules spanning core configuration, embedded servers, four template engines, REST (MVC, Jersey, HATEOAS, RestTemplate, WebFlux), JPA/Hibernate and reactive MongoDB persistence, AOP, OAuth2, SSL/HTTPS, scheduling, email, i18n, remoting, and layered testing. Documenting both the intended patterns and the exact quirks present in the codebase makes it reliable both as a technical showcase and as a long-term revision guide.

This repository hosts the projects and their source codes written for various tutorials written in howtodoinjava.com.

About

A collection of practical Spring Boot examples covering REST APIs, Spring Security, Hibernate & JPA, WebFlux, OAuth2, AOP, database integration, testing, and more. A hands-on reference for learning, understanding, and revising the Spring ecosystem.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages