Spring Boot Tutorial for Beginners [2025]

Spring Boot Tutorial for Beginners [2025]

Welcome to the Ultimate Spring Boot Course

Course Overview

  • This course aims to teach everything from basic to advanced concepts in Spring Boot, enabling learners to build real-world applications confidently.
  • The structure is divided into two parts: fundamentals and building web applications/APIs, with hands-on examples and exercises throughout.
  • The instructor, M. Hamadani, has over 20 years of experience and has taught millions through his YouTube channel and online school.

Prerequisites for the Course

  • A solid understanding of Java is essential; familiarity with object-oriented programming (OOP) concepts like classes, methods, and interfaces is required. If new to Java, a refresher course is recommended.
  • Knowledge of relational databases and SQL basics such as tables, primary keys, foreign keys, and writing queries is necessary; an SQL course is suggested for those needing improvement in this area.

Course Structure Explained

Part One: Fundamentals of Spring Boot

  • The first part covers foundational knowledge including what Spring Boot is and its advantages as a framework. It also includes setting up the development environment and creating the first project.
  • Key topics include dependency injection—understanding how Spring Boot manages objects—and database integration using Spring Data JPA for efficient data access patterns essential for real-world applications.

Learning Approach

  • Students are encouraged to follow lessons sequentially due to the cumulative nature of content; skipping may lead to missing important information. Exercises are included after lessons for better retention of concepts learned.

Utilizing GitHub Repository

Source Code Management

  • A GitHub repository contains organized source code where each commit corresponds to a lesson; students can view exact code changes made during lessons by accessing specific commits or tags for sections.
  • While knowledge of Git isn't mandatory for taking the course, it’s highly recommended as an essential skill for developers; a complete Git course is available on the instructor's website for those interested in mastering it further.

Getting Started with Spring Framework

Introduction to Spring Framework

Understanding the Spring Framework and Spring Boot

Overview of Spring Framework Modules

  • The Spring framework consists of various modules, each designed for specific tasks, categorized into different layers.
  • Core modules manage dependency injection and object management; web layer modules handle web requests and responses (HTML or JSON).
  • Data layer modules facilitate database interactions (SQL, NoSQL, in-memory), while AOP (Aspect-Oriented Programming) adds cross-cutting features like logging and security.
  • Testing modules are available for Spring components, emphasizing the modularity that allows developers to select necessary components.

Introduction to Spring Boot

  • Spring Boot simplifies development by reducing configuration overhead associated with the traditional Spring framework.
  • It provides sensible defaults and ready-to-use features, enabling rapid application development from idea to implementation in minutes rather than hours.

The Broader Spring Ecosystem

  • The Spring ecosystem includes projects like:
  • Spring Data: Simplifies database access.
  • Spring Security: Adds authentication/authorization capabilities.
  • Spring Batch: Facilitates batch processing.
  • Spring Cloud: Supports microservices and distributed systems.
  • Spring Integration: Eases messaging and system integration.

Setting Up Your Development Environment

Installing Java Development Kit (JDK)

  • To start building applications with Spring Boot, download the latest JDK version from a reliable source. At the time of recording, JDK 23 is current but future versions will also be applicable for learning purposes.
  • After installation, verify your setup by running java -version in your terminal.

Choosing an Integrated Development Environment (IDE)

  • IntelliJ IDEA is recommended due to its built-in tools that enhance productivity when developing with Spring Boot. Alternatives include VS Code or Eclipse.
  • IntelliJ IDEA's smart editor offers code completion features that streamline coding processes significantly.

Installing Build Automation Tools

  • Maven is chosen as the build automation tool for this course due to its popularity. IntelliJ IDEA has Maven integrated; other IDE users may need separate installations from Apache’s website or via package managers like Homebrew for Mac or Chocolatey for Windows.

Creating a New Spring Boot Project

Using Start.spring.io

Project Setup and Structure in Spring Boot

Project Metadata Configuration

  • The project metadata includes the group, which identifies the organization owning the project. A reverse domain name format is used (e.g., com.example becomes com.example). In this case, it is changed to com.codewithMH.
  • The artifact name represents the project's name; it is set to "store" as the course focuses on building an online store. The description remains unchanged.
  • Package name combines group and artifact names but will not be altered. The package type selected for this project is JAR, and Java version 23 will be utilized.

Generating a Spring Boot Project

  • Instead of using the website to create a new Spring Boot project, IntelliJ IDEA allows users to generate projects directly within the IDE. This feature is exclusive to IntelliJ IDEA Ultimate Edition.
  • Users are advised to use IntelliJ IDEA Ultimate Edition for professional development due to its comprehensive features compared to the Community Edition.

Project Creation Steps

  • During project setup, specify details such as project name ("store"), location on your machine, and optionally create a Git repository for version control.
  • Select Java as the language and Maven as the build tool. Group ID is set to com.codewithMH, while artifact and package names remain unchanged.

Understanding Project Structure

  • Upon creating a Spring Boot project, various folders are generated:
  • IDEA folder: Contains configuration files specific to IntelliJ.
  • Maven wrapper: Ensures consistent builds across different environments without requiring global installation of Maven.

Key Files in Maven Projects

  • Important files include:
  • pom.xml: Central configuration file for Maven projects that defines dependencies and other settings in XML format.
  • Source folder: Contains actual code with subfolders for main application code (src/main/java) and test code (src/test/java).

Application Properties Configuration

  • Within src/main/resources, there’s an application.properties file where key-value pairs can be defined (e.g., server port, database settings).
  • The main application class (StoreApplication.java) serves as the entry point with a standard main method calling SpringApplication.run().

Understanding Spring Boot Dependencies

Introduction to Dependencies

  • Dependencies are essential third-party libraries or frameworks used in applications, such as embedded web servers like Tomcat and libraries for handling web requests, building APIs, and processing JSON data.

Starter Dependencies in Spring Boot

  • Spring Boot simplifies dependency management by using starter dependencies, which are curated collections of commonly used libraries that have been tested together by the Spring development team.
  • For example, adding the spring-boot-starter-web dependency automatically includes compatible versions of necessary libraries.

Using Maven Central Repository

  • Maven Central is a public repository where developers can find dependencies for their projects, similar to npm for JavaScript or pip for Python.
  • To use a dependency from Maven Central, you need to copy specific code into your project's POM file based on the build tool being used (e.g., Apache Maven).

Adding Dependencies to Your Project

  • In a typical project setup with Apache Maven, you will have a <dependencies> tag in your POM file where you list all required dependencies.
  • After adding a new dependency code snippet into the POM file, it may require synchronization with the local repository to resolve any errors related to missing versions.

Simplifying Dependency Management

  • An easier method to add dependencies involves using IntelliJ's context menu (Command + N on Mac or Control + N on Windows), allowing users to search and select desired dependencies directly.
  • Once selected and added, if there are version issues again, reloading the project through the Maven icon resolves these problems by downloading necessary files into the local repository.

Understanding Local and Central Repositories

  • The local repository stores downloaded dependencies on your machine (e.g., located at ~/.m2/repository on Mac), while central repositories reference external sources like Maven Central.

Exploring Starter Dependencies

  • Starter dependencies include various sub-dependencies that work together; for instance, spring boot starter web includes components for JSON processing and an embedded Tomcat server.

Best Practices in Dependency Versioning

  • It is recommended not to specify versions directly within your POM file but rather allow Spring Boot's parent project (spring boot starter parent) to manage versioning automatically.

Understanding Spring Boot Dependency Management

Benefits of Dependency Management in Spring Boot

  • Maven simplifies the pom.xml file by allowing developers to omit version numbers for dependencies, which streamlines project management.
  • Upgrading Spring Boot automatically updates all dependency versions to their tested compatible counterparts, enhancing stability and reducing manual effort.

Introduction to Spring MVC

  • The lesson introduces the creation of a controller for handling homepage requests and serving HTML files, emphasizing the importance of understanding Spring MVC as the foundation for web request handling.
  • Spring MVC stands for Model View Controller, a framework that separates application components (model, view, controller), making applications easier to manage and scale.

Components of Spring MVC

  • Model: Represents application data and business logic; typically connected to databases or other data sources. In Spring Boot, it can be a simple Java class.
  • View: The user interface rendered in the browser using HTML, CSS, or JavaScript. Views can be static files or dynamically generated with tools like Thymeleaf.
  • Controller: Acts as an intermediary that handles incoming requests from users, interacts with the model for data retrieval, and determines what view should be displayed.

Creating Your First Controller

Setting Up the Home Controller

  • A new Java class named HomeController is created within the project structure to handle web traffic.
  • The class is annotated with @Controller, indicating its role as a web controller responsible for receiving HTTP requests.

Defining Request Mapping

  • A method named index is defined within HomeController, which will respond when a request is made to the root URL of the website.
  • The method uses @RequestMapping annotation with an argument representing the URL pattern ("/"), linking it directly to incoming requests at that endpoint.

Building and Running Your Application

Creating Views

  • The method returns "index.html" as the view name that should be displayed in response to user requests.
  • An HTML file named index.html is created in a new folder called "static," containing basic content ("Hello World") within an H1 tag.

Running Applications in IntelliJ

  • Instructions are provided on how to run the application using IntelliJ IDEA by clicking on a play icon or using keyboard shortcuts (Ctrl + R).

Alternative Method Using Maven

Debugging Spring Boot Applications

Running the Application with Maven Wrapper

  • The speaker explains how to run a Spring Boot application using the Maven wrapper, specifically by typing spring Das Boot:run instead of the usual command.
  • A character named John Smith is introduced as a self-proclaimed "Rockstar developer" who claims to write bug-free code, highlighting that debugging is essential for all developers.

Introducing and Identifying Bugs

  • The lesson demonstrates introducing a bug by creating a private method getViewName() that returns "index" instead of "index.html", which is unnecessary but serves the purpose of debugging.
  • After running the application, an error occurs due to the absence of a view called "index", prompting further investigation into debugging techniques.

Basic Debugging Techniques

  • The simplest way to debug is shown through print statements; adding System.out.println(viewName) helps identify that "index" is not valid.
  • The speaker suggests removing print statements and utilizing IntelliJ's debugging tools for more effective troubleshooting.

Using Breakpoints in Debugging

  • To start debugging in IntelliJ, breakpoints are introduced as markers that pause execution at specific lines. This allows for step-by-step execution.
  • By clicking on the debug button (Ctrl + D), users can rerun their application in debug mode and observe where execution halts.

Analyzing Variables During Debugging

  • Once paused at a breakpoint, users can execute code line by line using shortcuts like F8, allowing them to inspect variable values in real-time.
  • If variables do not appear automatically, expressions can be added manually to check their values during execution.

Resuming Execution and Further Debugging Steps

  • Users learn how to resume program execution until something renders in the browser using specific buttons or shortcuts (Option + Command + R on Mac).
  • If bugs remain unfound, restarting the debugging session allows stepping into methods (using F7), providing deeper insight into potential issues within those methods.

Finalizing Changes and Automatic Restart Feature

  • After identifying issues with string literals returned from methods, changes are made before stopping the debugger and removing breakpoints to avoid cluttering future sessions.

Spring Boot Development Tools Setup

Adding Spring Boot Dev Tools Dependency

  • To add the Spring Boot Dev Tools dependency, use command + n on Mac or control + n on Windows to select and search for the dependency.
  • Remove the version number from the dependency as it is part of the Spring framework; allow the parent element to determine its version.
  • Add an optional tag set to true, indicating that this dependency is only used during development and will not be packaged for production.

Configuring IntelliJ Settings

  • Modify two settings in IntelliJ: enable "Build project automatically" under Compiler settings.
  • Allow automake to start even if a developed application is currently running by checking the appropriate box in advanced settings.

Testing Application Restart

  • After making changes in code, observe that the application restarts automatically after a short delay, although it's slower compared to environments like Node or React.
  • The speaker prefers manually restarting using control + R, but acknowledges that enabling automatic restart can facilitate quicker testing.

Configuring Application Properties

Understanding Application Properties File

  • Configuration settings such as server port and database credentials are managed in application.properties located in the resources folder.
  • Standard properties include spring.application.name and server.port, which defaults to 8080 but can be changed as needed.

Using Custom Properties

  • Custom properties can also be defined (e.g., app.page-size) for specific application needs.

Implementing Dependency Injection

Introduction to Dependency Injection

  • Dependency injection is a core feature of Spring Framework aimed at making code cleaner and easier to maintain through decoupling components.

Real-world Example of Dependency Injection

Understanding Dependency Management in E-commerce Applications

Challenges with Order Service and Payment Service Dependencies

  • Modifying the order service code requires recompilation and retesting, which can affect other classes dependent on it.
  • The order service is tightly coupled to the Stripe payment service, making isolated testing impossible.
  • An analogy of a restaurant's dependency on a specific chef illustrates the risks of tight coupling; if that chef becomes unavailable, the restaurant faces challenges.

Decoupling Order Service from Payment Providers

  • To avoid tight coupling, the order service should depend on a general payment service interface rather than a specific provider like Stripe.
  • A Java interface acts as a contract defining class capabilities without implementation details, allowing flexibility in payment providers.

Benefits of Using Interfaces for Dependency Injection

  • By implementing an interface for payment services, switching from Stripe to PayPal does not require changes to the order service class.
  • This setup allows for isolated testing of the order service without reliance on any specific payment provider.

Implementing Dependency Injection in Code

  • The next steps involve creating an OrderService class with a method placeOrder, focusing on dependency injection without parameters initially.
  • A StripePaymentService class is introduced with a method processPayment, simplifying parameters to focus on demonstrating dependency management.

Refactoring for Better Design Practices

  • The initial setup shows hardcoded dependencies that prevent isolated testing and complicate future changes (e.g., switching to PayPal).
  • To decouple these classes, an interface named PaymentService is created through refactoring tools in the IDE.

Finalizing Interface Implementation

  • The new interface allows both existing and future payment services (like PayPal) to implement it without affecting the order service directly.

Constructor and Dependency Injection in Order Service

Defining the Constructor

  • The OrderService class is introduced, with a constructor defined to accept a PaymentService as a dependency.
  • A private field for PaymentService is declared within the class to store the injected service for later use.

Utilizing Payment Service

  • When creating an instance of OrderService, a specific payment service object (e.g., Stripe) is passed into the constructor.
  • The application transitions from Spring framework to a console application for testing purposes, allowing direct invocation of methods.

Implementing New Payment Services

Creating PayPal Payment Service

  • A new Java class named PaypalPaymentService is created, implementing the PaymentService interface.
  • Methods from the interface are implemented using IntelliJ's auto-generate feature, ensuring compliance with interface requirements.

Extending Functionality without Modification

  • By adding support for PayPal without altering existing code in OrderService, adherence to the Open/Closed Principle is demonstrated.
  • This principle states that classes should be open for extension but closed for modification, reducing risks of bugs when adding new features.

Understanding Object-Oriented Principles

Importance of Open/Closed Principle

  • The Open/Closed Principle allows developers to add functionality while minimizing changes to existing codebases.
  • It’s emphasized that principles should guide development rather than dictate it; misuse can lead to over-engineering.

Practical Application of Principles

  • Developers are cautioned against applying principles blindly; they should be used sensibly and contextually based on project needs.

Setter Injection Methodology

Implementing Setter Injection

  • An alternative method for dependency injection via setters is introduced in the OrderService.
  • IntelliJ provides shortcuts to generate setter methods efficiently, which can then be repositioned according to coding conventions.

Managing Dependencies Effectively

  • The setter method allows setting payment services post-construction but raises concerns about potential null pointer exceptions if not set properly.

Understanding Dependency Injection in Spring

The Importance of Dependency Management

  • The order service must function independently without external dependencies, emphasizing that a payment service is a required dependency rather than an optional one.
  • Manually creating and passing the payment service to the order service can become cumbersome as applications scale, especially when services like PayPal have their own dependencies.

Introduction to Spring Framework

  • The Spring framework automates object creation and dependency injection through its Inversion of Control (IoC) container, which manages application objects.
  • Beans are regular Java objects managed by Spring; they are created, injected with dependencies, and have their lifecycle managed by the framework.

Understanding Inversion of Control (IoC)

  • IoC refers to transferring control over object creation and dependency management from the developer to the Spring framework.
  • The ApplicationContext serves as the IoC container where managed objects (beans) are stored.

Managing Beans in Spring

  • To retrieve a bean like orderService, developers use the getBean method from the ApplicationContext instead of manual instantiation.
  • If Spring cannot find a qualifying bean definition for orderService, it indicates that it does not know how to create an instance of this class.

Configuring Bean Management with Annotations

  • Annotating classes with @Component informs Spring to manage them; this is essential for classes like orderService.
  • Specialized annotations such as @Service, @Repository, and @Controller provide clarity on class roles within an application.

Handling Dependencies with Interfaces

  • When encountering errors related to missing beans (e.g., for interfaces), developers must annotate implementing classes (like PayPal payment service).
  • Using either @Component or @Service allows Spring to recognize these classes as beans.

Utilizing @Autowired Annotation

  • The @Autowired annotation simplifies dependency injection; if there’s only one constructor, it's no longer necessary but still common in older codebases.
  • If multiple constructors exist in a class, using @Autowired becomes mandatory for proper initialization of dependencies.

Constructor Behavior in Dependency Injection

  • Introducing a default constructor without proper annotations can lead to null pointer exceptions due to uninitialized dependencies.

Understanding Constructor Issues in Spring Applications

Common Errors with Auto-Wiring

  • The discussion begins with the introduction of a payment service and the addition of a second parameter (int X) to the constructor. Removing the @Autowired annotation leads to an error indicating that the class does not contain a matching constructor for auto-wiring.
  • Upon running the application, a BeanCreationException is encountered, specifically stating an error in creating a bean named "order service." This type of exception is common in Spring applications.
  • To resolve this issue, it is necessary to reintroduce the @Autowired annotation back into the class along with its dependencies. After making this change, running the application again resolves the problem.

Final Steps and Course Promotion

  • The speaker suggests removing any unnecessary constructors and annotations before moving on to subsequent lessons. They emphasize that understanding these concepts is crucial for effective development in Spring.

Turn any video into a summary like this

YouTube links, meetings, lectures. With transcripts, search, and chat.

Video description

Master Spring Boot and build amazing backends with Java! 🚀 This beginner-friendly tutorial covers everything you need to learn Spring Boot 3. 🚀 Want to dive deeper? - Get the full course: https://mosh.link/spring-boot-fundamentals - Subscribe for more videos like this: https://goo.gl/6PYaGF 💡 Related tutorials https://youtu.be/EWd3_I4X32g?si=IbbN5SMYQrQJe-ek 👉 Interested in trying IntelliJ IDEA Ultimate? https://jb.gg/intellij-idea-for-mosh 👉 JetBrains has given me a 100% discount code! Use 'Spring_with_Mosh' to enjoy IntelliJ IDEA Ultimate for 3 months completely free! Redeem it here until April 1, 2026: https://jb.gg/redeem 💡 Related tutorials https://youtu.be/eIrMbAQSU34?si=Uw0R6GZ4DM0sanYR https://youtu.be/7S_tz1z_5bA?si=RvQs6awyciFtDeel ✋ Stay connected: - Full Courses: https://codewithmosh.com - Twitter: https://twitter.com/moshhamedani - Facebook: https://www.facebook.com/programmingwithmosh/ - Instagram: https://www.instagram.com/codewithmosh.official/ - LinkedIn: https://www.linkedin.com/school/codewithmosh/ 📖 Table of Content 0:00:00 Welcome 0:01:12 Prerequisites 0:02:02 Course Structure 0:03:44 Source Code 0:05:01 Getting Started 0:05:48 Introduction to Spring Boot 0:08:30 Setting Up the Development Environment 0:11:55 Creating a Spring Boot Project 0:15:38 Understanding the Project Structure 0:19:37 Dependency Management 0:27:28 Building Your First Spring Controller 0:31:41 The Ultimate Spring Boot Course 0:32:16 Running Spring Boot Applications 0:34:40 Debugging Spring Boot Applications 0:40:34 Automatic Restarts 0:44:12 Configuring Application Properties 0:46:49 Dependency Injection 0:47:48 What is Dependency Injection? 0:55:30 Constructor Injection 1:00:25 Setter Injection 1:03:05 The Spring IoC Container 1:05:58 Configuring Beans Using Annotations 1:10:59 What's Next #springboot #java #backend