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

Docker Ep 6: Running ‘Hello, World!’ with BusyBox: A Docker Adventure

Once upon a time in the city of Athipati, there was a young coder named Arivanandham. Arivanandham had recently heard whispers of a magical tool called Docker, which promised to simplify the process of running applications. Eager to learn more, Arivanandham decided to embark on a quest—a quest to run the famous “Hello, World!” using the mysterious BusyBox Docker image.

Today, we’re going to take our first step by creating and running a container. And what better way to start than with a tiny yet powerful image called BusyBox? Let’s dive in and explore how to run our first container using BusyBox.

Step 1: Discovering BusyBox on Docker Hub

Our journey begins at the Docker Hub, the vast library of images ready to be transformed into containers. Let’s search for “BusyBox” on Docker Hub.

Upon searching, you’ll find the official BusyBox repository at the top. BusyBox is renowned for its compact size—about 1 megabyte—which makes it an excellent choice for quick downloads and speedy container spins.

Step 2: Exploring BusyBox Tags

Before we proceed, let’s check out the Tags tab on the BusyBox page. Tags represent different versions of the image. We’re going to pick tag 1.36 for our container. This specific tag will be our guide in this Docker adventure.

Step 3: Setting Up Your Docker Environment

To start, we need to open a terminal. If you’re on Docker for Mac, Docker for Windows, or Linux, you can simply open your default terminal. If you’re using Docker Toolbox, open the Docker Quickstart Terminal.

Step 4: Checking Local Images

When you instruct Docker to create a container, it first checks your local system to see if the image is already available. Let’s verify what images we currently have:

docker images

If this is your first time, you’ll see that there are no images available yet. But don’t worry; we’re about to change that.

Step 5: Running Your First Container

Now, let’s run our first container! We’ll use the docker run command, specifying the BusyBox image and tag 1.36. We’ll also tell Docker to execute a simple command: echo "Hello, World!".

docker run busybox:1.36 echo "Hello, World!"

Here’s what happens next:

  • Docker checks for the BusyBox 1.36 image locally.
  • If it’s not found, Docker will download the image from the remote repository.
  • Once the image is downloaded, Docker creates and runs the container.

And just like that, you should see the terminal output:


Hello, World!

Congratulations! You’ve just run your first Docker container.

Step 6: Verifying the Image Download

Let’s run the docker images command again:

docker images

You’ll now see the BusyBox 1.36 image listed. The image has a unique ID, confirming that it’s stored locally on your system.

Step 7: Running the Container Again

Now that we have the BusyBox image locally, let’s run the same container again:

docker run busybox:1.36 echo "Hello, World!"

This time, notice how quickly the command executes. Docker uses the local image, skipping the download step, and instantly spins up the container.

Step 8: Exploring the Container’s File System

Let’s try something new. We’ll list all the contents in the root directory of the BusyBox container:

docker run busybox:1.36 ls /

You’ll see Docker output the list of all directories and files at the root level of the container.

Step 9: Running a Container in Interactive Mode

To dive deeper, we can run the container in an interactive mode, which allows us to interact with the container as if it were a tiny, isolated Linux system. We’ll use the -i (interactive) and -t (pseudo-TTY) flags:


docker run -it busybox:1.36

Now you’re inside the container! Try running commands like ls to see the contents. You can even create a new file:


touch a.txt
ls

You’ll see a.txt listed in the output. To exit the container, simply type exit.

Step 10: Understanding Container Lifecycle

It’s important to note that once you exit a container, it shuts down. If you run the container again using the same command, Docker spins up a brand-new instance. The file you created earlier (a.txt) won’t be there because each container instance is ephemeral, meaning it doesn’t retain data from previous runs unless you explicitly save it.

And there you have it! You’ve successfully created, explored, and understood your first Docker container using the BusyBox image. This is just the beginning of what you can achieve with Docker. As you continue your journey, you’ll discover how containers can simplify development, testing, and deployment, all while keeping your environment clean and isolated.

Docker Ep 5 : THE Bakery, Recepies, Dough & Cookies – Registry, Repository, Images, Containers

In the bustling town of Tambaram, there was a famous factory known for its delicious cookies. This factory had a unique and modern way of making and distributing its cookies, using a system inspired by Docker’s architecture.

The Recipe Registry

At the heart of the cookie-making process was the Recipe Registry, a giant digital library that stored all the cookie recipes. This registry was like a magical cookbook, holding secrets to every type of cookie imaginable: chocolate chip, oatmeal raisin, and even double fudge delight.

  • Purpose: The Recipe Registry ensured that everyone had access to the latest and greatest recipes. Bakers from all around the world could upload new recipes or download existing ones to make their own cookies.

The Cookie Repository

Each type of cookie had its own Cookie Repository within the Recipe Registry. These repositories were specialized sections where all the different variations of a particular cookie recipe were stored.

  • Example: The chocolate chip cookie repository contained recipes for classic, vegan, gluten-free, and extra gooey versions. Each version was labeled with a tag, like classic, vegan, or gooey.

The Image: A Perfect Cookie Dough

In the factory, the term “Image” referred to the perfect cookie dough that was ready to be baked into cookies. Each image was a complete package containing the recipe, ingredients, and instructions needed to make the cookies.

  • Characteristics: Just like a Docker image, the cookie dough was consistent and repeatable. No matter how many times you used the recipe, you always got the same delicious dough, ready to be baked.

The Container: Freshly Baked Cookies

Once the cookie dough was prepared, it was placed into a Container, representing a batch of freshly baked cookies. Each container was like a magical oven that turned the dough into cookies.

  • Isolation: Each container baked cookies independently, ensuring that the flavor and quality were perfect every time. Bakers could create multiple containers from the same dough image, producing countless batches of cookies.

The Cookie Delivery System

With the help of the Recipe Registry, Cookie Repository, Images, and Containers, the factory had an efficient Cookie Delivery System. This system allowed the factory to distribute its cookies all over Tambaram and beyond.

  • Scalability: If a bakery needed more cookies, they simply created more containers using the same dough image, ensuring everyone had enough cookies to enjoy.

Let’s try directly in to the concepts,

Registry

  • Definition: A Docker Registry is a storage and content delivery system that holds Docker images.
  • Purpose: It is used to manage where Docker images are stored and distributed from.
  • Examples: Docker Hub (the default public registry), Amazon ECR, Google Container Registry, and Azure Container Registry.
  • Functionality: Registries can be public or private. They store Docker images and provide an interface to push (upload) or pull (download) these images to and from repositories.

Docker Hub is the default public registry used by Docker. Here are examples of Docker Hub registry links:

  • Official Image: docker pull nginx

Community Image: docker pull username/repository:tag

Repository

  • Definition: A Docker Repository is a collection of related Docker images, usually providing different versions of the same application or service.
  • Purpose: Repositories organize and manage multiple images of an application or service.
  • Structure: A repository may contain multiple tagged versions of an image. For example, myapp:latest and myapp:v1.0 might be two tags in the same repository.
  • Functionality: Users can push images to a repository and pull images from a repository. Tags are used to differentiate between different versions of an image.

Official Repositories

Community Repositories

User-Specific Repositories

Images

  • Definition: A Docker Image is a lightweight, standalone, executable package that includes everything needed to run a piece of software: code, runtime, libraries, environment variables, and configuration files.
  • Purpose: Images are used to create containers. They provide a portable and consistent runtime environment.
  • Immutability: Images are immutable; once created, they do not change. If updates are needed, a new image version is created.
  • Layers: Images are built up from a series of layers, where each layer represents an instruction in the image’s Dockerfile.

For example, Dockerfile will comprises of the layers of instructions. https://hub.docker.com/layers/library/postgres/12.20-bullseye/images/sha256-2092f4af9ad9fff76e8d0b7c04d8c62b561e44c21a850d4a028124426046f6fa?context=explore

Sample dockerfile for postgres, https://github.com/docker-library/postgres/blob/805329e7a64fad212a5d4b07abd11238a9beab75/17/bookworm/Dockerfile

Containers

  • Definition: A Docker Container is a runnable instance of a Docker image. It is a lightweight, standalone, and executable package of software that includes everything needed to run it.
  • Purpose: Containers provide a consistent environment for applications, allowing them to run reliably regardless of where they are deployed.
  • Isolation: Containers are isolated from each other and the host system, but they can communicate with each other through well-defined channels.
  • Lifecycle: Containers can be created, started, stopped, moved, or deleted using Docker commands.

Relationship Between Concepts

  • Registry and Repository: A Docker registry can host multiple repositories. Each repository can contain multiple images with different tags.
  • Repository and Images: A repository serves as a namespace for images. For example, myrepo/myapp can contain different image tags like v1.0, v2.0, etc.
  • Images and Containers: Containers are running instances of images. You can run multiple containers from the same image.

The Tale of Magic Kitchen : A Docker Architecture

Setting the Scene

Once upon a time in the bustling town of Pettai, there was a famous restaurant called ArRahman Hotel. This wasn’t just any ordinary restaurant; it had a Magic Kitchen. The Magic Kitchen had the ability to create different kinds of meals almost instantly, without any confusion or delay. Let’s explore how the restaurant achieved this magical feat.

The Magic Kitchen (Docker Engine)

The heart of the restaurant was the Magic Kitchen, which had a unique power. Just like the Docker Engine, it could take orders and prepare meals consistently and efficiently. The kitchen knew how to handle everything without mixing ingredients or creating chaos, no matter how many orders came in.

The Docker engine comprises of dockerd (docker daemon), Docker Client (docker), REST Api, Container Runtime, Image Management, Networking, Volume management, Security mechanisms, Plugins & Extensions.

The Recipe Book (Docker Images)

In the Magic Kitchen, the chefs relied on a special Recipe Book. This Recipe Book contained detailed instructions on how to prepare each dish. These instructions are like Docker Images.

Each image is a blueprint for creating a meal (or application), containing everything needed to cook it up: the ingredients, the cooking method, and any special tools required.

The Prepped Ingredients – (Docker Containers)

When an order came in, the chefs would use the Recipe Book to gather prepped ingredients from the pantry. These ingredients are similar to Docker Containers. Containers are the actual meals created from the recipes, ready to be served. They are isolated from each other, ensuring that the flavors (or code) don’t mix and cause unwanted results.

The Pantry (Docker Registry)

The Magic Kitchen had a vast pantry where all the ingredients were stored. This pantry represents the Docker Registry. It holds all the images (recipes) that the kitchen might need, ready to be pulled and used whenever required. The registry ensures that every meal is prepared with the correct ingredients.

The Chefs (Docker Daemon)

The chefs in the Magic Kitchen are like the Docker Daemon. They are responsible for reading the recipes, pulling the necessary ingredients from the pantry, and preparing the meals in containers. They handle the entire process, ensuring everything runs smoothly and efficiently.

The Customers (Developers and Users)

The patrons of ArRahman’s are the Developers and Users. They come to the restaurant with various demands, and the kitchen satisfies them quickly and reliably. Developers can focus on creating new recipes without worrying about the cooking process, while users enjoy consistent and delicious meals every time.

The Special Dining Areas (Docker Networks and Volumes)

ArRahman also had special dining areas with unique themes and settings, ensuring each meal was experienced perfectly. These are like Docker Networks and Volumes. Networks allow different containers to communicate, much like guests chatting over dinner. Volumes store data persistently, like special utensils or decor kept for regular guests.

So atlast the docker architecture is,

❌