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.
- Technical Overview
- Repository Architecture
- Module-by-Module Documentation
- Core Spring Boot Concepts
- Important Annotations Reference
- Configuration Reference
- Installation and Execution
- Learning Roadmap
- Interview Preparation
- Practical Observations and Limitations
- Future Improvements
- Conclusion
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 |
Spring Boot Mail (spring-boot-starter-mail / JavaMailSender) |
||
| 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 |
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, configuresmaven-jar-plugin, and declares 29<module>entries. Root .gitignore excludes Maventarget/, 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.*orcom.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"]
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.
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:@RestControllerexposingindex()via@RequestMapping("/")returning"Greetings from Spring Examples !!".AppTest: Boilerplate JUnit 3TestCase(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:runKey Takeaways: @SpringBootApplication combines @Configuration, @EnableAutoConfiguration, and @ComponentScan, eliminating manual web.xml or DispatcherServlet setup.
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:
MainClassOneandMainClassTwo: Both classes are annotated with@SpringBootApplicationand definemain(String[] args).- main-class/pom.xml: Sets
<start-class>com.springexamples.demo.MainClassOne</start-class>under<properties>. AppTest: Boilerplate JUnit 3TestCase.
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:runKey Takeaways: If an artifact contains multiple main methods, <start-class> in pom.xml resolves the ambiguity for Spring Boot repackaging and spring-boot:run.
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 invokesappContext.getBeanDefinitionNames(), sorts the array alphabetically, and prints each bean name toSystem.out.AppTest: Boilerplate JUnit 3TestCase.
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:runKey Takeaways: Injecting ApplicationContext into a CommandLineRunner bean is a straightforward way to debug auto-configuration and verify which beans are active at runtime.
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:
Application: Instantiatesnew SpringApplication(Application.class), callsapp.setBannerMode(Banner.Mode.OFF), and runsapp.run(args).- disable-spring-boot-banner/src/main/resources/application.properties: Also sets
spring.main.banner-mode=off. AppTest: Boilerplate JUnit 3TestCase.
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:runKey Takeaways: Banner.Mode can be CONSOLE, LOG, or OFF, configurable either via SpringApplication.setBannerMode(...) or spring.main.banner-mode.
Concept: Replacing the default Spring Boot startup banner with custom text.
Purpose: Demonstrates classpath banner.txt discovery and Spring Boot version token interpolation.
Implementation:
- custom-spring-boot-banner/src/main/resources/banner.txt: ASCII art banner ending with
${spring-boot.formatted-version}. - custom-spring-boot-banner/src/main/resources/application.properties: Explicitly configures
spring.main.banner-mode=CONSOLE. Application: StandardSpringApplicationstartup.
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:runKey Takeaways: Placing banner.txt in src/main/resources automatically overrides the default banner without Java code changes.
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: ImplementsCommandLineRunner, overridesrun(String... args), and logs"ApplicationStartupRunner run method Started !!".ApplicationStartupRunner:@ComponentimplementingCommandLineRunnerwith its ownrun(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:runKey Takeaways: Multiple CommandLineRunner beans can coexist in the same context; if execution order matters, pair them with @Order.
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: ImplementsCommandLineRunnerusing Apache Commons Logging (LogFactory.getLog(getClass())) to emit oneINFOand oneDEBUGstatement 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, andlogging.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:runKey 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.
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@SpringBootApplicationand@EnableScheduling. Definesrun()annotated with@Scheduled(initialDelay = 1000, fixedRate = 10000)to printCalendar.getInstance().getTime()toSystem.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:runKey Takeaways: @EnableScheduling activates @Scheduled method scanning; fixedRate schedules based on task start intervals, whereas fixedDelay waits after task completion.
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: AutowiresMessageSourceand exposesGET /acceptingLocale locale, returningmessageSource.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:runVerify 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.
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:@ComponentimplementingWebServerFactoryCustomizer<ConfigurableServletWebServerFactory>. Overridescustomize(...)to callserver.setPort(9000)andserver.setContextPath("/springexamples").Application: StandardSpringApplicationstartup.- context-path-server-port/src/main/resources/application.properties: Contains commented-out
server.port=9000andserver.contextPath=/springexamples(noteserver.contextPathwas the Spring Boot 1.x property name; Boot 2.x usesserver.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:runKey Takeaways: WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> is the Spring Boot 2.x interface for programmatic server configuration (replacing Boot 1.x EmbeddedServletContainerCustomizer).
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 runsSpringApplication.run(App.class, args)on default Tomcat settings;tomcatServerFactory()andjettyServerFactory()beans (configuring port9000,/myapp, and404ErrorPage) 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, andserver.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:runKey Takeaways: Registering a ConfigurableServletWebServerFactory bean (such as TomcatServletWebServerFactory or JettyServletWebServerFactory) lets you configure ports, context paths, and custom ErrorPage mappings in code.
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:
- embedded-jetty-server/pom.xml: Excludes
spring-boot-starter-tomcatfromspring-boot-starter-weband addsspring-boot-starter-jetty. Application: Standard@SpringBootApplication.
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:runKey Takeaways: Switching embedded servlet containers in Spring Boot requires only excluding spring-boot-starter-tomcat and adding spring-boot-starter-jetty (or Undertow).
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:
- packaging-war/pom.xml: Sets
<packaging>war</packaging>and scopesspring-boot-starter-tomcatasprovided. Application: Standard@SpringBootApplicationwithmain. (Note: unlike template-jsp and rest-jersey-example,Applicationhere does not extendSpringBootServletInitializer.)HelloController: Maps/to return"Greetings from Spring Examples !!".
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:runKey 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.
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 aServletWebServerFactorybean (TomcatServletWebServerFactory) that adds two additional connectors:redirectConnector()(httpon8080,redirectPort=8443) andcreateSslConnector()(httpson8443,Http11NioProtocol, loading keystore.jks with aliastomcatand 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), andserver.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.
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").
Concept: Server-side HTML rendering with Apache FreeMarker.
Purpose: Demonstrates configuring a custom FreeMarker template directory and rendering home and error views.
Implementation:
- template-freemarker/pom.xml: Includes
spring-boot-starter-freemarkerand WebJars. - template-freemarker/src/main/resources/application.properties: Overrides default loader path to
spring.freemarker.templateLoaderPath=classpath:/ftl/. - Templates: home.ftl (
${title},${message}) and error.ftl (${status},${error}). AppandHomeController.
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:runKey Takeaways: spring.freemarker.templateLoaderPath moves templates from the default classpath:/templates/ directory to a custom location like classpath:/ftl/.
Concept: Server-side HTML rendering with Thymeleaf.
Purpose: Demonstrates Spring Boot's zero-config Thymeleaf integration using standard templates/ paths.
Implementation:
- template-thymeleaf/pom.xml: Includes
spring-boot-starter-thymeleafand WebJars. - Templates: home.html (
th:text="${title}",th:text="${message}") and error.html (th:text="${status}",th:text="${error}"). AppandHomeController.- template-thymeleaf/src/main/resources/application.properties: Empty; relies entirely on Spring Boot defaults.
Execution Flow: GET / invokes HomeController.home(ModelMap) and ThymeleafViewResolver renders classpath:/templates/home.html.
How to Run:
mvn -pl template-thymeleaf spring-boot:runKey Takeaways: Thymeleaf works out of the box with spring-boot-starter-thymeleaf when .html files are placed in src/main/resources/templates/.
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.Compilerconfigured withMustacheEnvironmentCollectorand.defaultValue("Some Default Value").HomeController: Populatestitleandmessageforhome.- 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:runKey Takeaways: Defining a custom Mustache.Compiler bean overrides Spring Boot's default compiler behavior (such as null-key handling).
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:jstland marksspring-boot-starter-tomcatandorg.apache.tomcat.embed:tomcat-embed-jasperasprovided. App: ExtendsSpringBootServletInitializerand overridesconfigure(...).- 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, andserver.error.include-stacktrace=always. - Views: home.jsp (uses JSTL
coretaglib) 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.
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: ExtendsSpringBootServletInitializer.JerseyConfig:@Componentextending Jersey'sResourceConfig, registeringUserResource.class.UserResource: JAX-RS endpoint at@Path("/users"):GET /users->UsersJSON listPOST /users-> validatesfirstName/lastName, assigns IDsize + 1, returns201withContent-LocationGET /users/{id}-> returns user JSON (200) or404PUT /users/{id}-> updatesfirstName/lastNameand returns200(note: line 65 checksif(user == null)rather thanif(temp == null))DELETE /users/{id}-> removes user (200) or404
UserDB: StaticHashMap<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:runKey Takeaways: In Spring Boot + Jersey, endpoints must be explicitly registered on a ResourceConfig subclass (JerseyConfig) rather than relying solely on Spring's @RestController scanning.
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-jerseyandspring-boot-starter-hateoas. User,Users, andReport: Extendorg.springframework.hateoas.ResourceSupport(Reportis present inmodel/though not referenced byUserResource).UserResource:GET /usersandGET /users/{id}useControllerLinkBuilder.linkTo(UserResource.class).slash(user.getUserId()).withSelfRel()and attach theLinkviauser.add(...).JerseyConfigandUserDB.
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:runKey Takeaways: Extending ResourceSupport allows domain models to carry HAL/hypermedia links built dynamically with ControllerLinkBuilder.
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.0andio.springfox:springfox-swagger-ui:2.8.0. Swagger2UiConfiguration: Annotated with@Configurationand@EnableSwagger2; implementsWebMvcConfigurer. Defines aDocketbean filtering outorg.springframework.bootinternal controllers viaPredicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")), and registers resource handlers forswagger-ui.htmland/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:runThen 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.
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. ConfiguresPoolingHttpClientConnectionManager(max50connections,TrustSelfSignedStrategy),ConnectionKeepAliveStrategy(readsKeep-Alivetimeoutheader or defaults to20000ms),CloseableHttpClient(CONNECT_TIMEOUT=30000,REQUEST_TIMEOUT=30000,SOCKET_TIMEOUT=60000), and a@Scheduled(fixedDelay = 10000)Runnable(idleConnectionMonitor) that closes expired/idle connections (30s).RestTemplateConfig: CreatesHttpComponentsClientHttpRequestFactory,RestTemplate, and aThreadPoolTaskScheduler(poolSize=50).UserService&UserServiceImpl: CallsrestTemplate.getForObject("http://localhost:8080/users", String.class).Application: ImportsHttpClientConfigandRestTemplateConfigvia@Import(the call touserService.testUserService()inrunis commented out).- resttemplate/src/main/resources/application.properties: Sets
server.port=9000,server.contextPath=/springexamples, andspring.main.allow-bean-definition-overriding=true. UserServiceTest: Uses@RestClientTest(UserServiceImpl.class),@AutoConfigureWebClient(registerRestTemplate = true), andMockRestServiceServerto assert the request tohttp://localhost:8080/usersreturns<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:runKey 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.
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 inEmployeeControllerrather thanRouterFunctionbeans.)MongoConfig: ExtendsAbstractReactiveMongoConfigurationwith@EnableReactiveMongoRepositories(basePackages = "com.howtodoinjava.demo.dao"). CreatesMongoClients.create()andReactiveMongoTemplateusingmongodb.dbname(testdb) andmongodb.port(27017injected via@Value).AppConfig&WebFluxConfig:PropertyPlaceholderConfigurerforapplication.propertiesand@EnableWebFlux.Employee: MongoDB@Document(id,name,salary) annotated with@Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS).EmployeeRepository: ExtendsReactiveMongoRepository<Employee, Integer>with@Query("{ 'name': ?0 }") Flux<Employee> findByName(String name).IEmployeeService&EmployeeService: Delegates reactive operations toEmployeeRepository(createcalls.subscribe()).EmployeeController: ExposesPOST /create(and/),GET /{id},GET /name/{name},GET /(MediaType.TEXT_EVENT_STREAM_VALUE),PUT /update, andDELETE /delete/{id}.- logback.xml: Console appender logging
org.springframeworkatDEBUGand root atERROR. EmployeeControllerTest: JUnit 5@WebFluxTest(controllers = EmployeeController.class)with@Import(EmployeeService.class),@MockBean EmployeeRepository, andWebTestClient(testCreateEmployee,testGetEmployeesByName,testGetEmployeeById,testDeleteEmployee). Note:testDeleteEmployeesendswebClient.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.
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@Entitymapped toTBL_EMPLOYEES(idwithGenerationType.IDENTITY,firstName,lastName,emailnon-null).EmployeeRepository: ExtendsJpaRepository<EmployeeEntity, Long>.EmployeeService: ImplementsgetAllEmployees(),getEmployeeById(Long),createOrUpdateEmployee(EmployeeEntity), anddeleteEmployeeById(Long), throwingRecordNotFoundException(@ResponseStatus(HttpStatus.NOT_FOUND)).EmployeeController:@RestControllerunder/employeesexposingGET /employees,GET /employees/{id},POST /employees(bindsEmployeeEntityparameters without@RequestBody), andDELETE /employees/{id}(returnsHttpStatus.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 currentEmployeeControlleris a@RestControllerat/employees). - Tests:
DemoApplicationTests(@SpringBootTest) andEmployeeRepositoryTest(@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.
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 totbl_employees(GenerationType.AUTO) and JSON list wrapper.EmployeeRepository: ExtendsCrudRepository<Employee, Long>.EmployeeController: ExposesGET /employees(returnsEmployees) andPOST /employees(@RequestBody Employee, saves entity, builds URI viaServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"), returns201 CreatedwithLocationheader).CustomExceptionHandler&ErrorResponse:@ControllerAdvicehandlingServletRequestBindingException(400) and genericException(500).EmployeeControllerUnitTests: JUnit 5@ExtendWith(MockitoExtension.class)using@Mock EmployeeRepository,@InjectMocks EmployeeController, andMockHttpServletRequestbound toRequestContextHoldersoServletUriComponentsBuilderworks outside a servlet container.EmployeeControllerIntegrationTests:@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)with@LocalServerPort,TestRestTemplate, and@Sql({ "schema.sql", "data.sql" })loading 3 rows beforetestAllEmployees().- 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 testKey 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.
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:
Application: Standard@SpringBootApplication.DomainService:@ServicewithgetDomainObjectById(Long id)that sleeps for a random interval (0–1999ms) and returnsid.LoggingAspect:@Aspect @Componentdefining@Around("execution(* com.howtodoinjava.aop..*(..)))"), using Spring'sStopWatchand Log4j2LogManagerto logExecution time of <Class>.<method> :: <ms> ms. (Note: the pointcut string contains an extra trailing)— see Practical Observations and Limitations.)AopSpringBootTest:@RunWith(SpringRunner.class) @SpringBootTesttest invokingservice.getDomainObjectById(10L).- aop/src/main/resources/application.properties: Configures
logging.pattern.console.
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 testKey Takeaways: @Around advice with ProceedingJoinPoint and StopWatch cleanly separates timing/profiling logic from business services without modifying service methods.
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: ImplementsCommandLineRunnerand callsemailService.sendMail(...)andemailService.sendPreConfiguredMail(...)on startup.EmailConfig:@Configurationdeclaring a@Bean SimpleMailMessage emailTemplate()with sample recipient, sender, subject, and body.EmailService:@Service("emailService")injectingJavaMailSenderandSimpleMailMessage. Provides four methods:sendMail(to, subject, body)sendPreConfiguredMail(message)sendMailWithAttachment(to, subject, body, fileToAttach)usingMimeMessagePreparatorandMimeMessageHelper(..., true)sendMailWithInlineResources(to, subject, fileToAttach)embedding an inline image viacid:identifier1234
- email/src/main/resources/application.properties: Configures
spring.mail.host=smtp.gmail.com,port=25, STARTTLS, timeouts (5000ms), 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:runKey Takeaways: Use SimpleMailMessage for plain-text emails and MimeMessagePreparator + MimeMessageHelper (multipart=true) for attachments and inline cid: HTML resources.
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:@SpringBootApplicationextendingWebSecurityConfigurerAdapter.OAuth2AuthorizationServer:@EnableAuthorizationServerconfiguring/oauth/token_key(permitAll()),/oauth/check_token(isAuthenticated()), form client auth, and an in-memory client (clientapp,BCryptPasswordEncoder-encoded demo secret, grant typespassword,authorization_code,refresh_token, scoperead_profile_info, resourceIdoauth2-resource, redirect URIhttp://localhost:8081/login, token validities5000s /50000s).OAuth2ResourceServer:@EnableResourceServerpermitting/and requiring authentication on/api/v1/**.SecurityConfig:@Order(1)WebSecurityConfigurerAdaptersecuring/loginand/oauth/authorizewith form login, defining an in-memoryUSERaccount (humptydumpty) and aBCryptPasswordEncoderbean.RestResource&UserProfile: Controller mapped at/api/users/mereading the authenticatedUserfromSecurityContextHolder. (Note:OAuth2ResourceServersecures/api/v1/**whileRestResourceexposes/api/users/me.)SpringOauth2ResourceServerApplicationTests:@SpringBootTestcontextLoads()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.
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).
Config: ExportsHelloWorldRMIimplviaRmiServiceExporter(serviceName = "helloworldrmi",serviceInterface = HelloWorldRMI.class) on the default RMI port (1099).HelloWorldRMI&HelloWorldRMIimpl: Greeting service interface and implementation.SpringRmiServerApplication&SpringRmiServerApplicationTests.
SpringRmiClientApplication: Declares aRmiProxyFactoryBeanpointing tormi://localhost:1099/helloworldrmiforHelloWorldRMI. Insidemain(), it retrieves theHelloWorldRMIbean and callssayHelloRmi("Sajal").SpringRmiClientApplicationTests.
HessianConfiguration: Registers@Bean(name = "/hellohessian")returning aHessianServiceExporterexposingHelloWorldImpl.HelloWorld&HelloWorldImpl.HessianServerApplication&HessianServerApplicationTests.- Uses
com.caucho:hessian:4.0.51.
HessianClientApplication: DeclaresHessianProxyFactoryBeanpointing tohttp://localhost:8080/hellohessianforHelloWorld, then callshelloWorld.sayHelloWithHessian("Sajal")insidemain().- application.properties: Sets
server.port = 9090so it does not collide withhessian-serveron8080. - 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:runKey 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>.
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.
- Seen in:
minimum-setup,get-loaded-beans-info,main-class.
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.
- Seen in:
get-loaded-beans-info,EmailConfig,RestTemplateConfig.
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).
- Seen in:
EmployeeController,EmailService,HelloController.
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.
- Seen in:
command-line-runner,logger-configuration,email.
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.
- Seen in:
embedded-jetty-server,CustomizationBean,SSLConfig.
@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.
- Seen in:
App,HttpClientConfig(idleConnectionMonitor).
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 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().
- Seen in:
LoggingAspect,DomainService.
- Spring MVC:
@RestController+@GetMapping/@PostMapping/@PutMapping/@DeleteMapping+ResponseEntity+@ControllerAdviceglobal exception handling (rest-crud-hibernate,unit-testing). - JAX-RS (Jersey): Standard
@Path,@Produces,@Consumes, andResponseregistered viaResourceConfig(rest-jersey-example). - HATEOAS: Embedding navigable
Linkobjects into payloads (ResourceSupport,ControllerLinkBuilder) inrest-hateoas. - Client side:
RestTemplatebacked by Apache HttpClient connection pooling (resttemplate).
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.
@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.
- Seen in:
EmployeeEntity,EmployeeRepository,unit-testing.
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).
- Seen in:
EmployeeController,EmployeeRepository,MongoConfig.
The repository exercises four distinct Spring testing levels:
- Pure unit tests (
@ExtendWith(MockitoExtension.class),@Mock,@InjectMocks):EmployeeControllerUnitTests - JPA slice tests (
@DataJpaTest):EmployeeRepositoryTest - Web client / WebFlux slice tests (
@RestClientTest+MockRestServiceServer,@WebFluxTest+WebTestClient+@MockBean):UserServiceTest,EmployeeControllerTest - Full integration tests (
@SpringBootTest(webEnvironment = RANDOM_PORT)+TestRestTemplate+@Sql):EmployeeControllerIntegrationTests
| 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 |
spring.main.banner-mode(offorCONSOLE):disable-spring-boot-banner,custom-spring-boot-banner.server.port: Configured to8080inoauth2,9000inresttemplate,9090inhessian-client, and8443inssl-https.server.error.whitelabel.enabled=falseandserver.error.include-stacktrace=always:template-jsp.spring.main.allow-bean-definition-overriding=true:resttemplate.
spring.freemarker.templateLoaderPath=classpath:/ftl/:template-freemarker.spring.mvc.view.prefix=/WEB-INF/jsp/andspring.mvc.view.suffix=.jsp:template-jsp.
- File-backed H2 (
rest-crud-hibernate):spring.datasource.url=jdbc:h2:file:C:/temp/test(Windows path; change on Linux/macOS or switch tojdbc: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).
logger-configuration:logging.level.org.springframework=DEBUG,logging.level.com.springexamples=DEBUG,logging.file=${java.io.tmpdir}/application.log, and customlogging.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 LogbackSTDOUTappender.
- Email (
email/src/main/resources/application.properties): Configuresspring.mail.host=smtp.gmail.com,spring.mail.port=25, STARTTLS, and placeholderspring.mail.username/spring.mail.password. Replace the placeholders and recipient address before running. - SSL/HTTPS (
ssl-https): application.properties andSSLConfigreference keystore.jks with placeholder demo passwords. Generate your own keystore and update credentials before non-local use. - OAuth2 (
oauth2):OAuth2AuthorizationServerandSecurityConfiguse hardcoded demo credentials in memory. Replace with externalized or persistent credential storage for real applications.
- 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
27017when runningspring-webflux-demo(not required formvn -pl spring-webflux-demo test). - Valid SMTP account credentials when running
email.
- Local MongoDB on port
Clone and inspect:
git clone <repository-url>
cd SpringExamplesCompile all modules without running tests:
mvn clean compileRun a specific module:
Linux / macOS / Git Bash:
mvn -pl minimum-setup spring-boot:runWindows PowerShell:
mvn -pl minimum-setup spring-boot:runBuild 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- Port
8080already 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): Updatespring.datasource.urlin rest-crud-hibernate/src/main/resources/application.properties fromjdbc:h2:file:C:/temp/testto a local path orjdbc:h2:mem:testdb. spring-rmiclient failures: Ensurermi-serverorhessian-serveris running before startingrmi-clientorhessian-client, as both clients execute a remote call immediately insidemain().- Java version mismatch (JDK 11+): Spring Boot
2.1.8.RELEASEtargets Java 8; modules likerest-hateoasandspring-webflux-demorely on JAXB (javax.xml.bind), which was removed from the JDK in Java 11 (onlyspring-webflux-demodeclares an explicitjaxb-apidependency). Running on JDK 8 avoids module-path errors.
All modules are independent Maven subprojects; you can study any module on its own. For structured learning or revision, follow this progression:
- Spring Boot Foundations: minimum-setup -> main-class -> get-loaded-beans-info -> disable-spring-boot-banner -> custom-spring-boot-banner -> command-line-runner
- Configuration, Logging & Runtime Customization: logger-configuration -> context-path-server-port -> server-customization -> embedded-jetty-server -> packaging-war
- Core Application Features: enable-scheduling -> i18n -> aop -> email
- Server-Side Web Templates: template-thymeleaf -> template-freemarker -> template-mustache -> template-jsp
- REST APIs, Documentation & Clients: swagger-ui -> rest-jersey-example -> rest-hateoas -> resttemplate
- Data Persistence & Testing: rest-crud-hibernate -> unit-testing
- Reactive, Security & Remoting: spring-webflux-demo -> ssl-https -> oauth2 -> spring-rmi
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?
@ExtendWith(MockitoExtension.class)(EmployeeControllerUnitTests): Fast unit tests with no Spring container.@DataJpaTest(EmployeeRepositoryTest): Loads only JPA entities, repositories, and an embedded test DB.@WebFluxTest(EmployeeControllerTest): Loads only reactive web layer components, paired withWebTestClientand@MockBean.@SpringBootTest(webEnvironment = RANDOM_PORT)(EmployeeControllerIntegrationTests): Boots the entire context on a random port for end-to-end HTTP + DB verification.
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)).
The items below are direct observations from inspecting the current source files (distinct from future enhancements):
- Framework & Dependency Age: The repository targets Spring Boot
2.1.8.RELEASEand Java 8 (1.8). Spring Boot 2.1.x reached end-of-life, andspring-security-oauth2-autoconfigure(2.1.8.RELEASE) and Springfox2.8.0are legacy stacks superseded by Spring Authorization Server / Spring Security OAuth2 Resource Server and Springdoc OpenAPI. - 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 fourtemplate-*modules contain boilerplate JUnit 3AppTestclasses (assertTrue(true)) rather than Spring Boot context or MVC assertions. - Code Bugs & Mismatches Observed in Source:
aop/LoggingAspect.java: The@Aroundpointcut expression"execution(* com.howtodoinjava.aop..*(..)))"has an extra closing parenthesis).spring-webflux-demo/EmployeeControllerTest.java:testDeleteEmployee()callswebClient.get().uri("/delete/{id}", 1), whereasEmployeeController.javamaps@DeleteMapping("/delete/{id}").rest-jersey-example/UserResource.java:updateUserchecksif(user == null)instead ofif(temp == null), which can throw aNullPointerExceptionwhen updating a non-existent ID.rest-crud-hibernate/EmployeeService.java:createOrUpdateEmployeepassesentity.getId()torepository.findById(...)without checking fornullfirst;EmployeeController.javareturnsHttpStatus.FORBIDDENfromdeleteEmployeeById; andrest-crud-hibernate/pom.xmlhas<name>context-path-server-port</name>.rest-crud-hibernate: Containslist-employees.htmlandadd-edit-employee.htmlThymeleaf views targeting/editand/createEmployee, whileEmployeeControlleris a@RestControllermapped at/employees.oauth2/OAuth2ResourceServer.javavsRestResource.java: Resource server security protects/api/v1/**, whereasRestResourceis mapped to/api/users/me. Additionally, bothSpringOauth2ResourceServerApplicationandSecurityConfigextendWebSecurityConfigurerAdapter.ssl-https: Configuresserver.port = 8443and Spring Boot 1.xsecurity.require-ssl=true, whileSSLConfigalso adds a connector on port8443.packaging-war/Application.java: Configures<packaging>war</packaging>inpom.xmlwithout extendingSpringBootServletInitializer.context-path-server-portandresttemplate: Reference the Spring Boot 1.x propertyserver.contextPathrather thanserver.servlet.context-path.spring-rmi/rmi-client/pom.xml: Sets<parent>toSpringExamplesinstead ofspring-rmi(unlikermi-server).
- Demo Credentials & OS-Specific Paths:
email,oauth2, andssl-httpscontain placeholder/demo credentials intended strictly for local walkthroughs, andrest-crud-hibernatehardcodesC:/temp/testinapplication.properties.
- Fix the verified source issues listed above (the extra
)inLoggingAspect,webClient.delete()inEmployeeControllerTest,temp == nullcheck inrest-jersey-example,entity.getId() == nullguard inrest-crud-hibernate, and/api/v1/**route alignment inoauth2). - Replace the legacy JUnit 3
AppTestplaceholders with real@SpringBootTest/MockMvctests across the basic and template modules. - Externalize demo credentials in
email,oauth2, andssl-httpsvia environment variables or profile-specific property files. - Add a shared
spring-rmi-apimodule forHelloWorldandHelloWorldRMIinterfaces 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).
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.