0% found this document useful (0 votes)
6 views74 pages

BE Java Unit-4

The document outlines a syllabus for a unit on Spring Boot and Modern Web Development, covering topics such as RESTful API creation, data access with JPA, and application deployment using Docker. It details learning objectives, the evolution of Java web development, and key concepts like Inversion of Control and Dependency Injection. Additionally, it explains the architecture of Spring Boot, ORM principles, and the use of Spring Data JPA for database interactions.

Uploaded by

kapilbelbase169
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views74 pages

BE Java Unit-4

The document outlines a syllabus for a unit on Spring Boot and Modern Web Development, covering topics such as RESTful API creation, data access with JPA, and application deployment using Docker. It details learning objectives, the evolution of Java web development, and key concepts like Inversion of Control and Dependency Injection. Additionally, it explains the architecture of Spring Boot, ORM principles, and the use of Spring Data JPA for database interactions.

Uploaded by

kapilbelbase169
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

Unit-4 :- Spring Boot and Modern Web Development

Er. Pushpak Kumar Mahato


Syllabus
Spring Boot and Modern Web Development (16 hours)
 Spring Boot fundamentals; Dependency injection and inversion of control;
Creating RESTful APIs with Spring Boot
 Data Access with Spring
 Overview of ORM and JPA
 Building a repository layer with spring data JPA
 CRUD operations and transactional management
 API Development and Security
 REST API design principles
 Handling exceptions in spring boot
 Overview of spring security for authentication and authorization
 Deployment and Project Work
 Docker and containerization
 Packaging and deploying a Spring Boot application
Learning Objectives

After this unit, we will be able to:


 Understand Spring Boot architecture
 Build RESTful APIs
 Use JPA & Hibernate for DB access
 Implement CRUD operations
 Secure APIs using Spring Security
 Containerize apps using Docker
 Deploy Spring Boot applications
 Build real-world backend projects
The Evolution of Java Web Dev

From Servlets & JSP to Spring Framework and Spring Boot


 Early Era (Servlets & JSP)
 Manual configuration in [Link]
 Tight coupling between UI and backend logic
 Hard to maintain large applications

 Spring Framework Era


 Introduced Dependency Injection (DI) & Inversion of Control (IoC)
 Initially heavy XML configuration → called “XML Hell”
 Later replaced by Annotation-based config (@Controller, @Service, @Autowired)

 Spring Boot Era (Modern Java Web Dev)


 Convention over Configuration
 Auto-configuration + embedded servers (Tomcat/Jetty)
 No [Link], minimal setup, faster development
 Production-ready features out-of-the-box (security, monitoring, configs)
What is Spring Boot?

 Framework built on top of Spring Framework


 Used to build standalone web applications
 Provides:
 Auto-configuration
 Embedded servers
 Production-ready features

 “Convention over configuration”


 Spring Boot follows default smart settings instead of forcing developers to write heavy configurations.
 “Spring Boot transforms complex enterprise Java development into fast, simple, and production-ready
application development.”

Spring Boot = Spring Framework + Automation + Speed + Simplicity


Why Spring Boot?

 Problems in traditional Spring:


 Too much XML
 Complex configuration
 Server setup required

 Spring Boot solves:


 No XML config
 No server deployment
 Faster development
 Easy production setup
Features of Spring Boot

 Auto Configuration
 Embedded Tomcat/Jetty
 Starter dependencies
 Production-ready Actuator
 Microservice support
 REST API ready
Spring Boot Architecture

 Layers:
 Controller Layer
 Service Layer
 Repository Layer
 Database Layer

 Flow:
Client → Controller → Service → Repository → DB
Inversion of Control (IoC)

 Inversion of Control (IoC) is a software design principle in which the control of


object creation, lifecycle, and dependency management is transferred from the
application code to a framework/container.
 Traditional approach: Object A creates Object B.
 IoC approach: The Framework creates and manages Object B.
 Benefit: Loose coupling and easier testing.
Before Spring
UserService s = new UserService();

With spring
@Autowired
UserService s;
 Spring provides an IoC Container:
 ApplicationContext
 BeanFactory

 Responsibilities:
 Create objects (Beans)
 Manage object lifecycle
 Inject dependencies
 Manage configuration
 Handle scopes (singleton, prototype, etc.)
Dependency Injection (DI)

 Dependency Injection (DI) is a design pattern and technique used to implement IoC,
where dependencies are provided to an object from the outside instead of the
object creating them.
 DI is the implementation of IoC.
 Objects "ask" for dependencies rather than creating them.
 The Spring Container (ApplicationContext) acts as the "Assembler."

 Benefits:
 Loose coupling
 Easy testing
 Clean code
 Maintainability
Types of DI in Spring

 Constructor Injection: (Recommended) Ensures required


dependencies are not null.
 Setter Injection: Good for optional dependencies.
 Field Injection: Use @Autowired (Quick but harder to unit test).
Constructor Injection

 Dependencies are provided through the constructor of the class.


 Spring forces required dependencies to be available when the object is created.
 This is the "Gold Standard." Dependencies are provided through the class constructor.
Because the dependencies are passed at the moment of object creation, you can mark
them as final, ensuring the class is immutable and the dependencies are never null.

 Why Recommended?
 Dependencies can’t be null
 Object is always in a valid state
 Best for unit testing (easy to pass mock objects)
 Works perfectly with final fields
 Preferred by Spring & industry best practices
Dependency Dependent class (Constructor Injection)
@Component @Component
public class Engine { public class Car {
public void start() {
[Link]("Engine started"); private final Engine engine;
}
} @Autowired // optional since Spring 4.3+
public Car(Engine engine) {
[Link] = engine;
}

public void drive() {


[Link]();
[Link]("Car is moving");
}
}
Setter Injection

 Good for Optional Dependencies


 Spring uses the no-args constructor to create the bean and then calls "setter" methods
to inject dependencies.
 When to Use Setter Injection
 Dependency is optional
 Dependency may change at runtime
 Avoids long constructors

 Problems with Setter Injection


 Object can exist in incomplete state
 Dependency can be forgotten → NullPointerException
 Not ideal for mandatory dependencies
@Component
public class NotificationService {
private EmailService emailService;

@Autowired
public void setEmailService(EmailService emailService) {
[Link] = emailService;
}
}
Field Injection

 Quick but NOT Recommended

 This is the most "magical" but controversial method. You simply annotate the private field
with @Autowired, and Spring uses reflection to force the dependency into the field.

 Why People Use It


 Very short and clean
 Less boilerplate code
 Common in demos & quick prototypes

 Why It’s NOT Recommended


 Cannot make fields final
 Hard to unit test (needs Spring context)
 Hidden dependencies
 Violates good OOP design
@Component
public class Car {

@Autowired
private Engine engine;

public void drive() {


[Link]();
[Link]("Car is moving");
}
}
Compare

Feature Constructor Setter Field


Recommended? Yes (Primary) Yes (Optional) No (Avoid)
Immutability Supported (final) Not supported Not supported
Testing Ease Very Easy Easy Difficult
Safety High (No Nulls) Medium Low
Spring Boot Annotations

 The "Big Three" Core Annotations


 @SpringBootApplication: The "All-in-One" entry point that triggers Auto-Configuration,
Component Scanning, and marks the class as a Configuration source.
 @RestController: A specialized controller for REST APIs that combines @Controller and
@ResponseBody, ensuring return types are automatically converted to JSON/XML.
 @Autowired: The "Connector" that tells Spring to automatically find and inject the required
dependency (bean) into a class field, constructor, or setter.

 Stereotype Annotations (The "Specialized Beans")


 @Component: The generic "Mother" annotation that marks a Java class as a Spring-
managed bean so the container can detect it.
 @Service: A specialized version of @Component used to signify that a class contains
Business Logic and complex calculations.
 @Repository: A specialized version of @Component used for Data Access (DAO) that
also provides automatic translation of database-specific exceptions.
Creating First Spring Boot App

Steps:
 Spring Initializr
 Select dependencies:
 Spring Web

 Generate project
 Run main class
 Open browser: localhost:8080
Data Access with Spring

What is ORM?
 ORM = Object Relational Mapping
 In the world of software development, Object-Relational Mapping (ORM) is the bridge
that connects two very different "worlds": the Object-Oriented world of languages like
Java, C#, or Python, and the Relational world of databases like MySQL, PostgreSQL, or
Oracle.
 Think of it as a translator that allows you to interact with your database using the language
you already speak (code) instead of writing raw SQL queries.

 Maps:
Java Objects ↔ Database Tables
 Example:
Class → Table
Object → Row
Variable → Column
The "Impedance Mismatch" Problem

 Before ORM, developers had to write "Boilerplate" code to map


database rows to objects. This was a headache because:
 Classes use nesting and inheritance.
 Tables use flat rows and columns.
 Data Types often don't match perfectly between a language and a database.

 An ORM tool provides a layer that maps a Class to a Table, a Field to


a Column, and an Instance (Object) to a Row.
 The Mapping (Metadata)
 You tell the ORM how your code relates to the database, usually via Annotations or
XML.
•Class User $\rightarrow$ Table users
•Property id $\rightarrow$ Primary Key Column u_id

 The Persistence API


 Instead of writing INSERT INTO users..., you call a method like
[Link](userObject). The ORM library automatically generates the SQL and
executes it.
 Language Integrated Query
 Most ORMs allow you to write queries using the object-oriented syntax (like HQL in
Hibernate or LINQ in .NET), which the ORM then converts into optimized SQL.
 The Good
 Productivity: You write much less code.
 Maintainability: If you rename a database column, you often only have to change it in one place (the
mapping).
 Security: ORMs automatically handle "SQL Injection" protection by using parameterized queries.

 The Not-So-Good
 Learning Curve: You have to learn the framework's "magic."
 Efficiency: For extremely complex queries (reports with 10+ joins), a human can usually write faster SQL than
an ORM generator.
 "N+1" Problem: If not configured correctly, ORMs can accidentally make hundreds of tiny database calls
instead of one big one.
Compare

ORM (Hibernate/Entity
Feature Plain SQL (JDBC/[Link])
Framework)
Code Volume High (Lots of boilerplate) Low (Clean and concise)
SQL Knowledge Must be an expert Basic knowledge is enough
Database Portability Hard (SQL varies by DB) Easy (Change a config setting)
Slight overhead due to
Performance Maximum control/speed
abstraction
JPA Overview

 JPA = Java Persistence API


Standard ORM specification in Java
 If ORM is the "concept" of mapping objects to tables, then JPA (Java Persistence
API) is the official "rulebook" or set of standards for how to do it in the Java ecosystem.
 To put it simply: JPA is a specification (an interface), while Hibernate is an
implementation.
 Implementation:
 Hibernate
 EclipseLink

•JPA (Java Persistence API): The specification (the "rules").


•Hibernate: The most popular implementation (the "engine").
 Think of JPA as a blueprint for a car. It tells you that a car must have a steering wheel,
an engine, and four wheels. However, we can't drive a blueprint. We need a company
like Hibernate, EclipseLink, or TopLink to actually build the car based on those
blueprints.
 JPA (The API): A collection of interfaces and annotations (residing in the
[Link] package).
 Hibernate (The Provider): The actual engine under the hood that writes the SQL and
talks to the database.
Key Components of JPA

 A. Entity
 An Entity is a simple Java class (POJO) that represents a table in our database. You
mark it with the @Entity annotation.

@Entity
public class Product {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String name;
private Double price;
}
 B. Entity Manager

 The EntityManager is the heart of JPA. It is the interface used to interact with the
persistence context. We use it to:
 Persist: Save a new object ([Link](obj))
 Find: Retrieve an object by ID ([Link](Class, id))
 Remove: Delete an object ([Link](obj))
 Merge: Update an existing object ([Link](obj))
 C. JPQL (Java Persistence Query Language)
 Instead of writing SQL against database tables, JPA allows us to write JPQL against
our Java entities.
 SQL: SELECT * FROM tbl_users WHERE u_name = 'Gemini'
 JPQL: SELECT u FROM User u WHERE [Link] = 'Gemini'
 Notice that JPQL uses the Class name (User) and Field name (name) rather than the
database table/column names.
The JPA Lifecycle

 JPA manages objects in different states. Understanding this is crucial for avoiding bugs
where data doesn't save when we expect it to:
 New (Transient): The object is created but not yet associated with a database row or
an EntityManager.
 Managed (Persistent): The EntityManager is "watching" the object. Any changes we
make to the object's fields will be automatically synced to the database when the
transaction ends.
 Detached: The object exists, but the EntityManager is no longer tracking it. Changes
won't be saved automatically.
 Removed: The object is scheduled to be deleted from the database.
JPA Annotations

 @Entity
Marks a class as a JPA entity (a table in the database).
 @Table
Maps the entity to a specific table in the database. Optional — if not provided, table
name = class name.
 @Id
Marks a field as the primary key of the table.
 @GeneratedValue
Specifies that the primary key will be auto-generated (identity, sequence, or auto
strategy).
 @Column
Maps a field to a column in the table. Optional — if not provided, column name = field
name.
Why Hibernate?

No Vendor Lock-in: If we write our code strictly using JPA annotations and interfaces,
we can theoretically switch from Hibernate to EclipseLink without changing our business
logic.
 Standardization: Every Java developer knows JPA. It creates a common language for
data persistence.
 Integration with Spring: Spring Data JPA builds on top of this, making it even easier
by allowing us to create repositories just by defining interfaces.
Comparision

Feature JPA Hibernate


An ORM Framework
What is it? A Specification (Interface)
(Implementation)
Ownership Part of Jakarta EE (Standard) Open Source (JBoss/Red Hat)
Can it run? No, it needs a provider Yes, it is the engine
[Link]
Key Class [Link]
er
@Entity // Marks this class as a JPA entity
@Table(name = "employees") // Maps to 'employees' table
public class Employee {

@Id // Primary key


@GeneratedValue(strategy = [Link]) // Auto-increment
private Long id;

@Column(name = "full_name", nullable = false, length = 100) // Maps to 'full_name' column


private String name;

@Column(nullable = false) // Column name defaults to 'salary'


private Double salary;

@Column(length = 50) // Optional column config


private String department;
}
Repository Layer

 Purpose:
 Database access
 CRUD operations
 Query handling
Spring Data JPA

 Features:
 No SQL required
 Auto CRUD methods
 Auto query generation
 Paging & sorting
 Repository abstraction

public interface StudentRepository extends JpaRepository<Student, Long> {


}
CRUD Operations

 save(): Inserts a new record into the database or updates an existing one if the ID is already
present.
 findById(): Retrieves a single entity by its primary key, returning an Optional to prevent
NullPointerException if the record isn't found.
 findAll(): Fetches all available records from the database table and returns them as a List.
 deleteById(): Removes the specific record associated with the provided primary key from the
database.
 existsById(): Returns a boolean (true/false) indicating whether a record with the specified ID
exists in the database without fetching the full object.

 Custom Queries with @Query


 Using JPQL (Java Persistence Query Language).
 Using Native SQL for complex performance-tuning.
 The CRUD Cycle
 Create (save), Read (findById), Update (save with existing ID), Delete (delete).
Transaction Management

 @Transactional
 Ensures:
 Data consistency
 Rollback on error
 ACID properties
 Atomicity ("All or Nothing")
 Consistency ("Follow the Rules")
 Isolation ("Don't Interrupt")
 Durability ("Built to Last")
API Development and Security

REST API Design Principles


 Stateless
 Resource-based URLs
 HTTP methods
 JSON format
 Proper status codes
HTTP Status Codes

 200 OK
 201 Created
 400 Bad Request
 401 Unauthorized
 403 Forbidden
 404 Not Found
 500 Server Error
Exception Handling

 Problems:
 Server crashes
 Bad error messages
 No standard response
 Solution:
 Global Exception Handling
@ControllerAdvice: A global "interceptor" for errors.
@ExceptionHandler: Mapping specific errors to HTTP status codes.
Example:-
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<String> handle(Exception e){
return [Link](500).body([Link]());
}
}

 Designing a Standard Error Response


 Fields: Timestamp, Message, Status Code, Path.
 Consistent JSON structure for frontend consumption.
Spring Security Overview
Spring Security provides:
 Authentication
 Authorization
 Role management
 JWT security
 Password encryption

The "Big Picture": Authentication (Who are you?) vs. Authorization (What can you do?).
Authentication (Who are you?)

Authentication is the process of verifying a user's identity. In Spring Security, this is


managed by the AuthenticationManager.
 How it works: When a user submits credentials, Spring Security creates an
Authentication object. This object travels through a chain of filters to be validated
against a data source (like a database or LDAP).
 Flexibility: It supports multiple "flows," including Form Login, OAuth2/OIDC
(Google/GitHub login), and Basic Auth.
 The Context: Once authenticated, the user's details are stored in the
SecurityContextHolder, allowing the app to "remember" who is logged in for the
duration of the request.
Authorization (What can you do?)

 Once we know who you are, Authorization decides if you have permission to access a
specific resource (like a URL or a method).
 Access Control: You can restrict access based on specific conditions. For example:
 Web Layer: Restricting URLs (e.g., /admin/** is only for admins).
 Method Layer: Using annotations like @PreAuthorize to secure specific Java functions.

 The Voter System: Spring uses "Access Decision Voters." If the bouncer (the voter)
sees you don't have the right "ticket," it throws an AccessDeniedException.
Role-Based Access Control (RBAC)

 Role management is a subset of authorization. It simplifies permissions by grouping


them into "Roles."
 Roles vs. Authorities: * Authority: A fine-grained action (e.g., READ_PRIVILEGE,
DELETE_USER).
 Role: A high-level bucket (e.g., ROLE_ADMIN, ROLE_USER).

 Hierarchy: Spring Security allows for Role Hierarchy, where an ADMIN can
automatically inherit all permissions of a USER, preventing you from having to assign
every single role to a high-level account.
JWT Security (Modern Stateless Auth)

 JSON Web Tokens (JWT) are the standard for modern, distributed systems (like
Microservices) where you don't want the server to store session data.
 Statelessness: Instead of a session ID stored in a cookie, the server sends a signed
token to the client. The client sends this token in the Authorization header for every
request.
 Security Filter Chain: To use JWT, you typically write a custom filter that intercepts
the request, extracts the token, validates the digital signature, and tells Spring Security,
"This token is valid; let this user through."
Password Encryption

 Storing plain-text passwords is a massive security risk. Spring Security’s


PasswordEncoder interface ensures passwords are never stored in a readable format.
 Hashing vs. Encryption: While often called encryption, it's technically one-way
hashing. You can't "decrypt" the password; you can only compare the hash of the
login attempt with the hash stored in the DB.
 BCrypt: This is the default and recommended implementation. It uses a "salt" (random
data added to the password) and a "work factor" (making the hash slow to compute) to
protect against brute-force and rainbow table attacks.
Deployment and Project Work

What is Containerization?
The "It Works on My Machine" Problem
 In traditional development, an app works on a developer's laptop but fails in production
because of different Java versions, missing environment variables, or OS-specific
settings.
 Containerization solves this by bundling the application code together with its
dependencies, libraries, and configuration files into a single "container."
 In a containerized environment, an application is isolated from the host operating
system. It doesn't know (or care) what else is running on the server.
 The Image: This is a read-only blueprint of your application. It contains the code, the
runtime (like [Link] or Java), and the system tools.
 The Container: This is the "living" instance of the image. When you run an image, it
becomes a container.
 The Engine: Tools like Docker act as the engine that pulls the images and runs
them.
Containers vs. Virtual Machines (VMs)
 This is a classic engineering interview question. Explain the architectural difference:
 VMs: Include a full "Guest OS" for every application. They are heavy, slow to boot
(minutes), and consume GBs of RAM.
 Containers: Share the Host OS Kernel. They only package the app and its
requirements. They are lightweight, boot in seconds, and consume MBs of RAM.
Features
 Portability
 Since the container includes everything the app needs, you can move it from a developer's laptop to a testing
environment, and then to a cloud provider (AWS, Azure, Google Cloud) without changing a single line of code.

 Efficiency (Lightweight)
 Unlike Virtual Machines (VMs), containers do not include a full guest operating system. They share the host's OS
kernel.
 VMs: Might be several gigabytes because they need a whole Windows or Linux OS.
 Containers: Often only a few megabytes, making them start in seconds rather than minutes.

 Isolation
 Each container is a "sandbox." If one container crashes or gets hacked, the others running on the same server remain
unaffected. This is crucial for Microservices, where a large app is broken down into dozens of small, independent
pieces.

 Scalability and Orchestration


 Because containers are so small and fast, you can spin up 100 copies of a web server container during a flash sale
and shut them down immediately after. Tools like Kubernetes are used to manage (orchestrate) these thousands of
containers automatically.
Introduction to Docker

 If containerization is the concept of shipping goods in standard boxes, Docker is the


company that built the boxes, the cranes to lift them, and the trucks to move them.
 Docker is an open-source platform that automates the deployment of applications
inside lightweight, portable containers. It revolutionized software development by
ensuring that an application behaves the same way regardless of where it is
deployed.
 Docker is the world’s most popular platform for building, running, and managing
containers.
 It turned "containerization" (which existed in Linux for years) into a user-friendly tool
for developers.
Components

 The Dockerfile (The Recipe)


 A Dockerfile is a simple text document that contains all the commands a user could call on the
command line to assemble an image. It defines the base OS, environmental variables, and the steps to
install your app.
 Example: "Use Python 3.9, copy my script, and run pip install.“

 The Image (The Blueprint)


 When you "build" a Dockerfile, it becomes an Image. An image is a read-only, executable package that
includes everything needed to run an application. Images are stored in registries like Docker Hub.

 The Container (The Living Instance)


 A container is a runtime instance of an image. You can have one image (e.g., Ubuntu) and start ten
different containers from it. Each container is isolated and has its own writable layer.
The Docker Architecture (Client-Server)
Docker Client (The Interface)

The Docker Client is how you interact with Docker.


 User Input: As shown in the image, this is where you type commands like docker run
nginx.
 Communication: It doesn't actually do the heavy lifting; instead, it sends these
commands as REST API requests to the Docker Daemon.
 Tools: This can be the Command Line Interface (CLI), an API, or a graphical interface
like Docker Desktop.
Docker Daemon / dockerd (The Brain)

The Docker Daemon is the background service (server) that manages everything.
 Request Handling: It receives the REST API calls from the client via Unix or TCP
sockets.
 Sub-Systems: Inside the Daemon, three major components work together:
 Container Management: Handles the lifecycle (start, stop, delete) of your containers.
 Image Builder: Orchestrates the creation of new images from Dockerfiles.
 Network & Volumes: Manages the virtual "cables" (networking) and "hard drives" (volumes) that
containers use to communicate and store data.
Docker Images & Containers (The Execution)

This section shows the "Build vs. Run" relationship.


 Docker Images: These are stored in local storage. Think of them as read-only
templates or blueprints.
 Creates & Runs: The diagram shows a two-way arrow here. The Daemon uses an
Image to create a Container.
 Docker Containers: These are the "Running Instances." Unlike images, containers
have a writable layer, allowing them to execute the application code in an isolated
environment.
Docker Registry (The Library)

The Registry is a remote storage system for images (like Docker Hub).
 Pull Images: If you try to run an image that isn't on your computer, the Daemon will
"Pull" it from the Registry.
 Push Images: Once you build your own custom image, you can "Push" it to the
Registry so other developers or your production servers can download it.
Dockerfile Fundamentals

A Dockerfile is a text document containing all the commands a user could call on the
command line to assemble an image.
 FROM: The base layer. For Spring Boot, we usually start with a Java Runtime (e.g.,
openjdk:17-jdk-alpine).
 ARG / COPY: We take the .jar file created by Maven/Gradle and copy it into the
container's file system.
 EXPOSE: Informs Docker that the container listens on a specific network port (usually
8080).
 ENTRYPOINT: The command that runs when the container starts.
 Example: java -jar [Link]
Packaging the App (The "Fat JAR")

Before putting the app in Docker, we must package it.


 The Command: mvn clean package (Maven) or ./gradlew build (Gradle).
 The Output: A "Fat JAR" (or Uber-JAR).
 What's inside?: Unlike traditional Java apps, a Spring Boot Fat JAR contains all
project dependencies PLUS an embedded server (Tomcat).
 The Benefit: You don’t need to install a server on the production machine. If Java is
there, the app runs.
Multi-stage Docker Builds

This is an "industry-standard" technique to keep images small and secure.


 Stage 1 (Build): Use a heavy image with Maven/JDK to compile the code and run
tests.
 Stage 2 (Run): Copy only the resulting .jar file into a very light, "slim" image (JRE
only).
 Why?:
 Security: No source code or build tools are left in the production image.
 Size: Reduces image size from ~500MB to ~150MB, making deployments faster.
Externalized Configuration

In engineering, you never hardcode database URLs. You use Environment Variables.
 Profiles: Spring Boot allows [Link] and application-
[Link].
 Priority: Environment variables override properties files.
 Practical Example: On your laptop, the DB is localhost. In Docker, the DB might be a
container named db-container. Spring Boot swaps these automatically based on the
"Active Profile."
Deployment Checklist

What makes an app "Production Ready"?


 Health Checks: Use Spring Boot Actuator. It provides an /actuator/health endpoint
so the cloud (or Docker) knows if your app is alive.
 Logging: Logs should be sent to "Standard Out" (console) so Docker can collect
them.
 Resource Limits: Define how much CPU and RAM the container is allowed to use to
prevent one app from crashing the whole server.
Introduction to CI/CD

 The final step in modern dev is automation.


 Continuous Integration (CI): Every time a student pushes code to GitHub, an
automated server (like GitHub Actions or Jenkins) builds the code and runs tests.
 Continuous Deployment (CD): If the tests pass, the server automatically builds a
Docker image and pushes it to the cloud.
 The Goal: Eliminate manual errors. No more "I forgot to upload the latest file."
 CI/CD (Continuous Integration and Continuous Deployment/Delivery) is the automated
pipeline that takes your source code from a Git repository and moves it through
building, testing, and deployment phases without manual intervention.
Architecture
Continuous Integration (CI)

The goal of CI is to merge all developer code into a shared mainline several times a day
to detect "integration hell" early.
 Code Commit: A developer pushes Java code to GitHub or GitLab.
 Automated Build: A CI tool (like Jenkins, GitHub Actions, or GitLab CI) triggers a build
using a build tool like Maven or Gradle.
 Unit Testing: The pipeline runs tests (e.g., JUnit or TestNG) to ensure the new code
hasn't broken existing functionality.
 Artifact Creation: If tests pass, the build tool packages the code into a JAR or WAR
file.
Continuous Delivery / Deployment (CD)

Delivery is about making sure your code is always in a state where it could be deployed.
 Artifact Creation: If the CI checks pass, the system creates a "build artifact" (like a .jar file
or a Docker image).
 Staging Environment: The code is deployed to a "Staging" or "QA" server. This is a
playground that looks exactly like the real world but isn't accessible to users yet.
 Manual Trigger: In "Delivery," a human (like a Lead Developer) usually clicks a button to
say, "Okay, this looks good. Send it to the real users.“
Deployement is the most advanced stage. There is no "Approve" button.
 Fully Automated: If the code passes all tests in the CI stage and the staging tests, it goes
straight to the live production server.
 High Frequency: Companies like Netflix or Amazon use this to update their websites
hundreds of times a day without the site ever going down.
The CI/CD Pipeline (Step-by-Step)

Imagine you are building a Java Web App. Here is the life of a single code change:
 Commit: You fix a bug and git push to GitHub.
 Trigger: GitHub tells a CI tool (like Jenkins or GitHub Actions), "Hey, new code just
arrived!"
 Build: Jenkins downloads your code and runs mvn clean package.
 Test: Jenkins runs your JUnit tests. If a test fails, you get an email/Slack message, and
the process stops (The "Red Build").
 Secure: A tool like SonarQube scans for security holes.
 Package: The code is turned into a Docker Image.
 Deploy: The Docker Image is sent to a server (like AWS or a Kubernetes cluster).
THE END

You might also like