Reading view

There are new articles available, click to refresh the page.

spring Boot Introduction -II

Step:1 Open Eclipse
If you Don not install ,install
https://www.eclipse.org/downloads/

Step:2 Install Spring Tools (Spring Tool Suite 4) Plugin
1.Go to menu:
Help-> Eclipse marketplace
2.Type Spring tool In search bar
Spring Tools 4 (aka Spring Tool Suite 4)
then install. Restart Eclipse.

Step:3 create spring boot project
File->New-> Spring starter Project.

Demo1 obj1 = new Demo(); // tightly couple
Demo1 obj1; // loosely couple

Now not need any dependencies , now I skip dependencies.

Image description

Jar,War,Dependencies,Pom.xml,Maven,Gradel,Spring,Spring Boot,yml,Application properties,Tomcat..etc to read this Blog:
https://dev.to/prasanth362k/spring-boot-1-2-class-14h0

Group:Package name
Artifact: Project Name

Image description

Project Structure:-

Image description

Demo1 is project name

src/main/java:

This folder contains your java source code:

  • @SpringBootApplication main class
  • Controllers (@RestController)
  • Services (@Service)
  • Repositories (@Repository)
  • Model classes (@Entity)

src/main/resources

This folder stores all configuration and static files like:

  • application.properties or application.yml
  • static/ (HTML, CSS, JS)
  • templates/ (Thymeleaf or JSP)
  • .sql or .xml files (if needed)

this location configure Database url,Db username/password,server port number.

src/test/java

This used for writing Junit test cases to check if controller/Api is working?,Service logic is correct?, function returns should give correct output.it helps tester and developer find bugs early.

In real time first we done testing the project then deployment.

JRE System Library [JavaSE-17]

This Library provide all the core java classes (like String,List,System.out.println) you project needs.without library won't understand basic java code

For Example-

System.out.println("Hello World");  // Needs java.lang classes from JRE

why it's need?
java compiler version ( project built in using java 17),Runtime version ( you app will run run on java 17), this both need java 17 or higher version for spring boot .that need to your project.

Image description

Image description

Maven Dependencies

This file contain .jar file(libraries) downloaded form maven(internet) based on you what you add dependency from pom.xml .

why and what Maven dependencies and JRE System Library [JavaSE-17] both contain jar file inside package and inside .class file.

Maven Dependencies:

Image description

JRE System Library [JavaSE-17]:

Image description

.jar -> is a compressed file format or Zip folder for .class file,.jar contain .class, .properties,xml related. it user for java application not for web application(war) , can be executable to run with java -var app.jar(main class) , inside .jar you see .compile files.

.class , created after compiling .java,platform indepenedent(can run any osusing jvm),it is not human readable(byte code(plain text)),it is single file not a zip folder

target/

maven stores all compiled code and build files here.After mvn install, .class and .jar files go here.his is auto-generated – don't modify manually.

pom.xml

The main configuration file for Maven:
Add dependencies (Spring Web, JPA, Lombok)

In this blog i demonstrate how to call method without object new keyword only class reference not create object like.Before 2 thing definitely to know one for what is tightly coupling and loose coupling why to use then what is spring container please read my previews blog

By Default Main program start this file

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.example.demo.service.SMSNotificationService;



@SpringBootApplication
public class DemoApplication {

    private NotificationService notificationService;

    public static void main(String[] args) {
        // before SpringApplication.run(DemoApplication.class, args);
        ConfigurableApplicationContext context  = SpringApplication.run(DemoApplication.class, args);// after 
        //it is tigtely couple relation to avoid like without new key word
        SMSNotificationService sms =context.getBean(SMSNotificationService.class);
        //SMSNotificationService sms ; // = new  SMSNotificationService();
        //SMSNotificationService sms;
        sms.send_message("abcd ","1234");
    }

}

Step:2
I created SMSNotificationService class

package com.example.demo.service;


import org.springframework.stereotype.Component;

import com.example.demo.NotificationService;

@Component
public class SMSNotificationService implements NotificationService{

    @Override
    public void send_message(String to ,String message)
    {
        System.out.println("Sending SMS "+to +" : "+message);

    }
}


Step:3 created Interface

package com.example.demo;

public interface NotificationService {

    //abstract method 
    void send_message(String to ,String message);

}

Program Explanation:

SpringApplication is a Built in spring boot class ,it is helps to create environment for your project .
it does 3 thing: start your spring boot application , create the spring container when run this method SpringApplication.run(DemoApplication.class, args), DemoApplication.class, args why to use you are tell to the spring boot where to begin otherwise spring boot do not know where to start you said start from main.then why args , to pass to arguments in command line like: java -jar app.jar --server.port=9090
,args will contain --server.port=9090, so spring boot can read setting from command line. that all , then i already told SpringApplication.run(DemoApplication.class, args); it give Spring container just like environment(சூழல்)(to create object inside the environment), we create environment like spring container where will be stored that place is ConfigurableApplicationContext (in Built interface)context (reference variable)

SMSNotificationService sms = context.getBean(SMSNotificationService.class);

we Already marked SMSNotificationService @Component annotation ,which tell spring please create object of this class and manages,SpringApplication.run(....) when run this method , start this app and return ConfigurableApplicationContext, this is the spring Container(environment) that manage the all object(beans) ,we already know that ,already created object , now just get the bean(object) of class SMSNotificationService.class from spring container ,then store the variable sms , then call method sms.send_message("abcd ","1234");

context is a reference to the Spring container,getBean(inbuild function)

**
Inversion of control(IoC) and Spring Container and Dependency Injection(DI) lets connect with together?**

  • IoC is a design principle/idea that says:
  • you should not create objects manually using new,instead spring will manage them ,Spring fallow the principle using technique is called DI.Spring container is the environment the create ,store, and manages all thes beans(objects),these object created and stored heap memory,DI achived using Constructor Injection ,Field Injection,Setter Injection.To inject dependencies spring use the @Autowired annotation
    .

  • If you Do not mention @componet on top of class , spring can not create and store object in the spring container.

  • @Component creates one object inside Spring container (by default singleton). by default singleton mean, by default, Spring creates only one object per class → this is called singleton scope.

  • spring by default create only one object per class , can we create multiple? yes

We learned 2 annotation in this blog:-

@springBootApplicaion
point your mouse arrow int this annotation the press f3 you will some info.
Inside you see lot of annotations combines , in this annotation 3 is important:

1.@Configuration: spring tells this class provide object(bean) , spring should register them spring container.@bean tells spring please call method,take return value and store it spring container.(Do not need to call method manually , automatically call)

Example:-

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

2.@EnableAutoConfiguration

Tells Spring boot will automatically configure beans based on what is in the classpath For example , you add spring web in pom.xml configure Tomcat server , web settings(DispatcherServlet ), set port automatically you do not do manually ,this automatically configure.
"DispatcherServlet is the front controller in Spring MVC.
It handles all incoming web requests and routes them to the correct @Controller or @RestController methods."

  1. @ComponentScan

Spring scan the current package and sub package @Component,@Service,@Controller,
@Repository automatically create objects(beans) and store them container.Before i said if you mention top of the class @Component object created and store in spring container , @Service,@Controller,
@Repository internally @Component you can point you mouse cursor in annotation and press f3 .
it will create objects only for classes :

  • @Component
  • @Service
  • @Controller
  • @Repository

mvt vs mvc

spring & Spring Boot

What is framework?

  • A framework is like ready made toolset or structure ,it helps you build application easily , without starting from scratch.

what is spring?

  • Spring Framework is a java-based opens-source framework , it is used to build enterprise level, scalable, maintainable application.
  • spring provide infrastructure support for building java apps by managing dependencies injection , configuration, connecting to databases, handle web request and so on.
  • Need External Server (Tomcat)
  • Developed by Rod Johnson in 2002.

  • Spring Follows principle Dependency injection(like without new keyword create the object, spring container(object memory location) ,to use @Autowired) and Aspect-Oriented programming(AOP),MVC(Model-view-Controller)

  • AOP: is a programming concept to used to separate common function like logging ,security,transactions from main logic of you application. simple, write common code(logging, security, transactions) and automatically apply you app or application , without rewrite it everywhere

  • Deployment : Build WAR, needs external server

  • Configuration: Manual xml based configuration it is older style ,you define everything in xmf flie.spring 2.5 version you can use also annotation so spring support both XML and annotation , but need more setup. in Spring boot no need xml Configuration you just add dependencies in pom.xml,it will auto configure everything ,start the application , scan your classes with annotation like @Restcontroller ,@Service ..etc.

spring Example:-

applicationContext.xml or beans.xml

<bean id="studentService" class="com.example.StudentService"/>
<context:component-scan base-package="com.example"/>


spring boot dependency injection Example:-

pom.xml 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


before you added dependency in pom.xml ,now Spring boot code now you can use annotations @ annotation:-

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello!";
    }
}

<bean id="myBean" class="com.example.MyBean"/>

Annotation-based:-
you use java annotation instead of xml
Common annotations:

@Component, @Service, @Repository, @Controller ...etc

What is annotation:-

Annotation is meta data that mean data about data, data about data mean provide info about to the spring framework,These annotation used to configure,customize, reduce xmL configuration and boilerplate code ( repeated code not a main logic), annotation make developer develop application or app simplify development and maintain and efficient ,time reduce..etc.

How to avoid boilerplate code:-

  1. manual creating beans:-
<bean id="studentService" class="com.example.StudentService"/>

how to avoid : use annotation like @service and @ auto wired ,automatically crate and inject bean(object).

  1. Auto Configuration Automatically set up Db ,server..etc.it make consuming more time and managnet difficulty so, how to avoid:
  • spring boot add automatically configure you application based on dependencies what you added in the pom.xml and some more setting in application.properties or application.yml. like you want project server tomcat , you can inject dependencies your pom.xml(maven) spring automatically download internet you dependencies.

  • In a project you can see src/main/properties under you can see application.properties it used to .

  • Configure application setting like port number changing ,Db config..etc.

3.Getter/setters
How to avoid Getter/setters : Lombok , remove getter/setters , use @data and @Getter ,.etc.

application.yml:-
YAML format for settings

What is Dependencies and Dependencies injection and types:-

Dependency:-
Dependency is a class/object that another need to work.
Example:-

class Engine
{
public void start()
{
sytem.out.println("engine started Let to drive");
}
}
class Car {
    Engine engine = new Engine();  // tightly coup
    engine.start();
 // Engine is a dependency
// Engine class change constructor , you must chage  every place that  uses it.  
}

// car depends on Engine , so Engine dependency of car

What is Dependency Injection (DI)?

  • Dependency Injection is a is a design pattern, do not create the object yourself with new key word(tightly couple) ,spring or spring boot create and inject required object with help of @Component(you can tell spring ,pleas create objects of this class,spring will manage and create bean(object) ),spring container(memory location hold all object (@Componet in top of class use )),@Autowired (connector like tell spring inject(connect) this object here) ,spring container is one of the part of heap memory. Why Heap? Because:
  • All Java objects are stored in the heap memory
  • Spring beans are also Java objects.

Example:

Normal java or spring boot or spring you can create object with new keyword it is manual ,it make depend upon other like called tightly coupled when depender class anything change(parent)like constructor like parameter constructor/overload ,you can change all so depending class(child class) constructor or object values.



class Engine
{
public void start()
{
sytem.out.println("engine started Let to drive");
}
}
class Car {
//Engine engine = new Engine(); // Manual
@Autowired
Engine engine; // Spring injects it

    engine.start();
 // Engine is a dependency
// @Autowired if you want you first  inject dependency  to pom.xml , maven will manage

}

Why to use DI:-

  • Reduce manual object creation
  • Loose Coupling - easy to change

Types of Dependency Injection in Spring?

1. Constructor Injection

Spring passes dependency to the constructor

@Component
class Car {
    private final Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}


2️2.Setter Injection:-

Spring sets dependency using setter method

@Component
class Car {
    private Engine engine;

    @Autowired
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
}


3. Field Injection

Spring injects directly into the field

@Component
class Car {
    @Autowired
    private Engine engine;
}

Aop example:

without AOP( repeating code every where)

public class BankService {

    public void withdraw() {
        System.out.println("Checking permission...");
        System.out.println("Logging: withdraw started");
        System.out.println("Withdrawing money...");
        System.out.println("Logging: withdraw completed");
    }

    public void deposit() {
        System.out.println("Checking permission...");
        System.out.println("Logging: deposit started");
        System.out.println("Depositing money...");
        System.out.println("Logging: deposit completed");


    }

    public void checkBalance() {
        System.out.println("Checking permission...");
        System.out.println("Logging: check balance started");
        System.out.println("Showing balance...");
        System.out.println("Logging: check balance completed");
    }
}

// main logic with extra logic , hard to mange,messy..etc

With AOP (clean and separate)

public class BankService {

    public void withdraw() {
        System.out.println("Withdrawing money...");
    }

    public void deposit() {
        System.out.println("Depositing money...");
    }

    public void checkBalance() {
        System.out.println("Showing balance...");
    }
}
Step 2: Write AOP for Logging and Permission
@Aspect
@Component
public class LoggingAspect {

    // Log before any method in BankService
    @Before("execution(* com.example.BankService.*(..))")
    public void logBefore(JoinPoint jp) {
        System.out.println("Logging: " + jp.getSignature().getName() + " started");
    }

    @After("execution(* com.example.BankService.*(..))")
    public void logAfter(JoinPoint jp) {
        System.out.println("Logging: " + jp.getSignature().getName() + " completed");
    }

    @Before("execution(* com.example.BankService.*(..))")
    public void checkPermission() {
        System.out.println("Checking permission...");
    }
}
// But you didn’t write this logging or permission code inside the withdraw() method — Spring AOP handled it for you.

Is Spring only for Java?

yes, Spring is only for Java and JVM-based languages (like Kotlin, Groovy).
It is not for Python, C++, etc.

Why use Spring?

  • To build robust(Strong,stable,handle errors well,)loosely coupled(classes are independent not tightly coupled , Java applications. Can integrate with JPA/Hibernate, JDBC, Security, etc.

JPA (Java Persistence API)

  • JPA is just a specification (like a set of rules).
  • It defines how Java objects should be saved into a database (ORM – Object Relational Mapping).
  • JPA doesn’t do anything by itself – it needs a real tool to work.

Hibernate

  • Hibernate is a real tool (framework) that follows JPA rules.
  • So, Hibernate is a popular implementation of JPA.
  • It does the actual work of connecting your Java classes to the database. Example:-

Think of:-

JPA = Rulebook

Hibernate = Worker who follows the rulebook

  • sql maually, JDBC, Security, etc.

What is JDBC?

  • JDBC = Java Database Connectivity (manual SQL writing and executing)
    

    When to use:

  • When you want manual control over SQL.
    

    How Spring Integrates:

  • Spring provides Jdbc Template to reduce boilerplate code.

Spring Security:-
What is it?

  • A module in Spring for:
  • Login/Logout
  • User Roles (admin, user, etc.)
  • Password Encryption
  • Authorization (what a user can access)

How Spring Integrates:

  • Add spring-boot-starter-security
  • Configure user roles, login form, URL access rules Example

Tightly coupling:-

class Car {
    Engine engine = new Engine(); // direct object
}

loose coupling

class Car {
    @Autowired
    Engine engine; // Spring will inject it
// you can change the engine ,test the calss , or reuse iit 
}

  • IT save time ,Make code clean and reusable
  • It give tools for web apps ,security ,database,JPA/Hibernate, JDBC.
  • Supports DI, AOP, and MVC, simplifying development.

what is Spring Boot?

  • Spring boot is a simplified version of the Spring Framework. It helps to create spring applications quickly and with less configuration.

  • Spring Boot = spring + Ready made setup(like auto configuration ..etc) +Less code + fast to development like you can create java web apps to fast.

  • Developed by Pivotal (now VMware) in 2014.

  • Deployment : Build JAR with embedded Tomcat/Jetty(server)

Use Case:-

spring : Full control, more configuration setup ,suitable for custom projects
Spring Boot: Fast startup the projects,Rest APIS, Micro-service, ..etc.

Example:

  • without spring: you write 100 lines for setup code.
  • with spring : you write 20 lines.
  • With spring Boot : you write 10 lines

why to use Spring Boot?

  • Reduce boilerplate code( boilerplate code- repeated code , you write agin and again) ,to avoid writing unnecessary code.
  • Easy to start project with pre-configured setups.it useful for beginners.
  • To avoid complex XML configurations.
  • Ideal for micro services architecture

*we will learn some concept or tool or other terminology used in the spring boot project *

What is Maven?

(A Java tool to manage dependencies and build project)

  • Maven is a build and dependency management tool for Java projects.
  • Configuration format : XML (pom.xml)
  • Speed: Slower
  • Used in Spring Boot, standard Java app s
  • Dependency Management: Downloads libraries (JAR files) only from Maven Central repository

- It helps:

  • Download and manage external libraries (like Spring Boot..etc)
  • Build your project (compile, test, package into .jar or .war)
  • Run your project with the required libraries

What is Gradle?

  • Gradle Build & Dependency Management Tool like maven.
  • Configuration format : Groovy or Kotlin DSL (build.gradle)
  • synax: Concise like script based
  • speed: Faster
  • Dependency Management: Can download from Maven Central, JCenter, or custom/private sources.
  • used in : Andriod apps, spring Boot Apps ,large java projects.

What is jar ?

jar = Java ARchive

  • Jar File is a packaged java application(all java files are combined into one file .jar so it easy to run ,share,or deploy ) used to run standalone programs.JAR file is a zip file that contains your Java program

standalone mean:

  • work independently.
  • no need to deploy on separate server tomcat manually.that mean just run the jar file directly using java no need to put in separate server like tomcat.
  • Easy to run,test and move.

Example:

  1. you build you spring boot app like myapp.jar
  2. run using java -jar myapp.jar 3.spring start its own server on port of 8080 by default 4.you open browser ->http://localhost:8080 app is running this is called deployment for JAR
  • Jar file contains all compiled .class files, libraries, and metadata(info about how to run).

  • Runs directly using: java -jar app.jar

  • used in Spring Boot, microservices, and CLI apps.Running desktop or back end apps.Standalone Java applications

  • jar not need install server separately , include tomcat server run app directly
    Tools -> Maven/Gradle to build .jar

what is WAR?

WAR = Web Application Archive

  • A WAR file is a packaged Java web application(means java web project with contain HtmL,CSS,Java code,etc) that zipped into one .war file to be run on a webserver) used to deploy on web servers like Tomcat in deploy. Deploy mean putting your application on a sever so users can access it.

  • WAR Contains: .class files + HTML, CSS, JS, JSP, WEB-INF folder, etc.

Example:-

1.you build you app -> myapp.war ( create you web app)

2.you copy to C:\tomcat\webapps\myapp.war (after placed your web app in the server tomcat)
3.Start tomcat
4.open browser and paste => http://localhost:8080/myapp (server run your app and it make available in the browser)
now deployed and running

Deploy -> Putting your app on a server to run
WAR file -> The package you give to the server
Tomcat -> The server that runs your web app.

  • used for Deploying java apps to web server(Apache Tomcat) .Web-based applications (Servlet, JSP, deployed to server)

  • Tools -> Maven/Gradle to build .war

What is pom.xml in Spring Boot ?

(XML file used by Maven to define project setup)
POM = Project Object Model

  • pom.xml it is a XML file(your required dependency placed or add into pom.xml) used by maven tool ,that to tool manage the dependencies in you project. pom.xml tells maven what is project name(artifactId),package name (groupId),what version,What dependencies (JARs) to download,What plugins or settings to use.

What is XML in pom.xml?

XML = Extensible Markup Language
It is used to store structured data.
it use tags likevalue
XML is platform-independent and readable by humans and machines. that mean do not depend on any operating system ,can be used or support on every platform like Windows, linux,mac,android,server...etc

What is a Dependency in pom.xml?

  • I want to use some external java library or tool like spring boot ,jpa,hibernate, please download and include my project. like simply say maven is a tool it mange dependencies in the project,that dependencies placed in pom.xml for example you add dependencies in pom.xml spring tell maven tool download dependencies form internet file like jar file , that jar file combination package and class available.

Example:-

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
// this dependency say  i want to use spring boot for build web application, maven download required library the you add project  @RestController, @GetMapping, etc.

What Happens When You Use Maven?

When you run:
mvn clean install

Maven will:

  1. Read pom.xml
  2. Download all dependencies (JAR files) from the internet (Maven Central)
  3. Compile the code
  4. Run tests
  5. Create a .jar or .war file to run your app

Where Are the JAR Files Stored?

Maven downloads all .jar files into:

C:\Users\YourName\.m2\repository   (Windows)
or
~/.m2/repository                   (Linux/macOS)
  • JAR in Maven Downloaded from the internet and stored in .m2

java is WORA feature write once anywhere ,platform independence , windows, linux.
500 .class to files to :Zip : in java caller jar

.yaml/.yml

YAML Ain’t Markup Language:Easy to read and write.

  • Used in : Configuration files (application.yml)in Spring Boot, Docker (docker-compose.yml), Kubernetes (deployment.yml), Ansible, etc.
  • Feature : Human-readable data serialization language , indentation-based.

  • Structure: Based on indentation (like Python)

  • Supports: Key-value pairs, lists, nested structures.

  • No tags, no brackets

  • Real-time use: Configure properties like ports, DB, paths.

data serialization language mean:
IT means it help store data in structured ,readable format.
IT can represent data like string,number,list,object..etc.
That data can be converted programming object/variable into a file format like YAML,JSON,XML,binary file so it can be stored or send.

Example:-

Your Java Serialization Code:

import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.File;

public class SimpleSerialize {
    public static void main(String[] args) throws Exception {
        User user = new User();
        user.name = "Prasanth";
        user.age = 24;

        YAMLMapper mapper = new YAMLMapper();
        mapper.writeValue(new File("user.yml"), user); // Serialization
    }
}

Output in user.yml (YAML format):

name: "Prasanth"
age: 25

reverse code YAML yo JAVA object = deserilation

What is Deserialization?

  • Mean stored convert data format like YAML or JSON or XML(human readable format) back into java/python object or variable.

Example of YAML configuration:

server:
  port: 8080
spring:
  application:
    name: MySpringBootApp
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: user
    password: password
logging:
  level:
    org.springframework: INFO
    com.example.myapp: DEBUG
  • YAML is a language to store and share data in a clean and readable format,used for configuration.

JSON
JSON-JavaScript Object Notation

  • A lightweight, human-readable data format
  • Commonly used for data exchange between client & server. for example spring Boot can automatically convert java object to Json responsce)(Serialization) and JSON to Java object(post)request input (Deserialization) using a library called Jackson by default.
  1. Spring Boot uses Jackson
  • Spring Boot has built-in support for JSON vice versa the Jackson library.
  • Converts (serializes) Java objects → JSON
  • Converts (deserializes) JSON → Java objects
    
  • Happens automatically using annotations like @RequestBody and @ResponseBody (or @RestController)

  • Key Annotations

Annotation Purpose
@RequestBody JSON → Java object (deserialization)
@ResponseBody Java object → JSON (serialization)
@RestController Combines @Controller + @ResponseBody

  • Jackson default Json Processor it is auto configured.

Q1. How does Spring Boot handle JSON?

Using Jackson library (automatically)
Q2. How do you send/receive JSON in REST API? @RequestBody, @ResponseBody, or @RestController
Q3. How do you customize JSON fields? Use @JsonProperty, @JsonIgnore, etc.
Q4. What if the JSON format is wrong?

Spring throws HttpMessageNotReadableException

Important Points

  • Jackson is auto-configured in Spring Boot → no setup needed.
  • JSON input should match Java class field names (case-sensitive).
  • Use validation annotations like @NotNull, @Size with @valid.
  • You can control JSON output with @JsonInclude, @JsonIgnore, etc.
    
  • Real-time use REST APIs, mobile/web apps
    (frontend-backend data exchange)

Tomcat:-
Tomcat is server that run you java web application(WAR) also embedded(include) inside spring Boot Jar apps not java application((JAR)not need install server manually).

  • Spring helps developer connect their web application to number data base.
  • It support relational databases and non relational database
  1. What is a Relational Database (RDBMS)?

RDBS is a Structured data - it mean Data
mean:

  • Data is Stored fixed format in tables(Column and rows) like Excel sheet.Every row must follow the same pattern. like Columns define the pattern(schema) so row must follow it and fill same columns with valid data. or you can not skip columns unless NULL is allowed or it has default value.Note you can not suddenly add 4 the value in the table ,that why structured .
  • Uses Sql (structure Query language) to query and manage data Example:-
CREATE TABLE student (
  id INT,
  name VARCHAR(50),
  age INT DEFAULT 18
);

INSERT INTO student (id, name) VALUES (1, 'Prasanth');

if you try this ,it will fail
INSERT INTO students (id, name) VALUES (2, 'Rahul');

// because RDBMS is Structured data must fallow this rules(column(schema(rule)))the rows.

Image description

above the table:

  • Every row must have 3 values: id, name, and age
  • You can’t suddenly add a 4th value in one row
  • You can’t skip columns unless NULL is allowed. This is called structured data.

Examples of RDBMS:

  • MySQL
  • PostgreSQL
  • Oracle
  • SQL Server

Real-World Use:

  • Banking systems
  • Employee or customer records
  • E-commerce product databases

What is a Non-Relational Database (NoSQL)?

  • Stores data in a flexible format — not in rows and columns.
    No fixed schema — you don’t need to define table structure first.

  • Good for handling unstructured or changing data

Stores data as:

  • JSON-like documents (MongoDB)
  • Key-value pairs (Redis)
  • Graphs (Neo4j)
  • Wide-columns (Cassandra)

Currently using Tools and version:-
Eclipse IDE - 2025-06
Java - Java 21 (LTS)
Springboot -3.5.3
Firefox -v140.0.2
Ubuntu -Ubuntu 22.04 LTS
Tomcat 10.1.42
Database -PostgreSQL 15+

How to add Third party jar add in you project ?

your project right click ,choose bulid path configure build path libraries class-path add-external Jar

How to inject dependency in pom.xml different way ?
https://mvnrepository.com/ you can search your required dependencies(version) paste you in pom.xml.
(Or)
install spring tool for Eclipse https://spring.io/tools( we will see later how to install and use)
(Or)
In Eclipse ->Help-> market place -> search spring latest version.

apachi poi => https://poi.apache.org/

  • Apachi poi is a Java library used to read, write, and modify data microsft office files and generate reports ,Automatic document like:

  • Excel (XLS/XLSX)

  • Word (DOC/DOCX)

  • PowerPoint (PPT/PPTX)

if you want your project you can add this dependencies based on project purpose or need.

Spring boot other some important point:

Spring boot
opinionated view of the Spring platform and third-party libraries so you can get started with minum fuses:- That mean

Spring Boot is opinionated framework , spring boot give default setup like (server(Tomcat),db,JSON..etc) setting,libraries,configurations..etc you can start with basic setup,so you don’t have to decide everything yourself create application faster with less configuration, best for beginners ,if you want decide everything yourself go to spring.

Features

  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated 'starter' dependencies to simplify your build configuration
  • Automatically configure Spring and 3rd party libraries whenever possible
  • Provide production-ready features such as metrics, health checks, and externalized configuration
  • Absolutely no code generation and no requirement for XML configuration

Image description

Finally we came conclusion part of this spring boot blog we will upcoming blog
spring boot projects to Travel...

W

How to change spring boot banner and set to the spring profile

How to change spring boot banner in Eclipse IDE?

Step 1: Open your spring Boot Project in Eclipse
Step 2: Open src/main/resources Folder in eclipse

  • In the project Explorer (left side)

expand:

Image description

step 3: Right click resource folder -> New -> file -> Give name LOWER Case Letter only.

Example: banner.txt
then click Finish.

like

src/main/resources/banner.txt

step 4: Add custom banner content

open your created file paste your custom test or ASCLL art.

Example:-

Image description

IF you want your own ASCLL text:

https://patorjk.com/software/taag

Step 5: Right click main class(@SpringBootApplication)

Runs As -> Java Application

IF you Do not Want Banner:-

Step 1: Open application.properties in your project.

Location src/main/resource in Double click application.properties add below line.

spring.main.banner-mode=off

What is a Spring Profile?

In Spring Boot , a profile is a to define different configuration for different environment

For example:

dev (development)
test (testing)
prod (production)

Above mention each profile separate beans(objects) or you configuration setting tells that where you app is running.

Why use Profile?

just think like:

in development ,you want to connect to local database.
int production , you want to connect to live database.

Spring Profile help you switch easily between configuration without changing main code.

How to Set a spring Profile:-

1. create separate Property Files:-

go to:

src/main/resources/

Right click resources folder -> new -> file

create files like:-

application-dev.properties

application-prod.properties

inside file type your configuration details

2. In application.properties

=> application.properties

spring.profiles.active=dev

3.Run the Application :

Right-click main class → Run As → Java Application

Spring boot annotation used in entity class

Class based Annotation:

  • @Entity – used to indicates the class is below to JPA entites.
  • @Table – is used to indicates the table name.
  • @MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {

    private String firstName;
    private String lastName;
    
    // Constructors, getters, setters, other fields...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
  4. This promotes code reusability and maintains a clean and structured entity hierarchy.

Primary Keys

  • Define a primary key using @Id.
  • Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // other fields, getters, setters
}

Associations

It says the relationship between two entity class.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
    private List<Employee> employees;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Constructors, getters, setters, other fields...
}

Cascading Operations

  • Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
  • Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // Constructors, getters, setters, other fields...
}
  1. CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database

When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.

Author author = new Author();
author.setName("J.K. Rowling");

Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);

Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);

author.setBooks(Arrays.asList(book1, book2));

// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);

Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.

Validation

Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class.
Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Title is required")
    @Size(max = 100, message = "Title must be at most 100 characters")
    private String title;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    private List<Comment> comments;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Text is required")
    @Size(max = 500, message = "Text must be at most 500 characters")
    private String text;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

    // Constructors, getters, setters, other fields...
}

Auditing

  • Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
  • Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class Auditable {
    @CreatedBy
    protected String createdBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    protected String lastModifiedBy;

    @LastModifiedDate
    protected LocalDateTime lastModifiedDate;

    // Getters and setters...
}
  1. @EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
  2. @MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.

By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.

Enums and Enumerated Types

  • Use Java enums for fields with predefined values.
  • Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private TaskStatus status;
    // other fields, getters, setters
}

public enum TaskStatus {
    TODO, IN_PROGRESS, DONE
}

Reference:

Spring boot annotation used in entity class

Class based Annotation:

  • @Entity – used to indicates the class is below to JPA entites.
  • @Table – is used to indicates the table name.
  • @MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {

    private String firstName;
    private String lastName;
    
    // Constructors, getters, setters, other fields...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
  4. This promotes code reusability and maintains a clean and structured entity hierarchy.

Primary Keys

  • Define a primary key using @Id.
  • Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // other fields, getters, setters
}

Associations

It says the relationship between two entity class.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
    private List<Employee> employees;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Constructors, getters, setters, other fields...
}

Cascading Operations

  • Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
  • Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // Constructors, getters, setters, other fields...
}
  1. CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database

When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.

Author author = new Author();
author.setName("J.K. Rowling");

Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);

Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);

author.setBooks(Arrays.asList(book1, book2));

// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);

Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.

Validation

Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class.
Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Title is required")
    @Size(max = 100, message = "Title must be at most 100 characters")
    private String title;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    private List<Comment> comments;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Text is required")
    @Size(max = 500, message = "Text must be at most 500 characters")
    private String text;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

    // Constructors, getters, setters, other fields...
}

Auditing

  • Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
  • Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class Auditable {
    @CreatedBy
    protected String createdBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    protected String lastModifiedBy;

    @LastModifiedDate
    protected LocalDateTime lastModifiedDate;

    // Getters and setters...
}
  1. @EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
  2. @MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.

By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.

Enums and Enumerated Types

  • Use Java enums for fields with predefined values.
  • Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private TaskStatus status;
    // other fields, getters, setters
}

public enum TaskStatus {
    TODO, IN_PROGRESS, DONE
}

Reference:

Deploy our Spring boot application for free.

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

Deploy our Spring boot application for free.

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

❌