❌

Normal view

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

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 :

Spring Boot Notes

By: Sugirtha
16 December 2024 at 19:04

What is Spring Framework?
Before we proceed with the definition let’s first understand what is framework.

Framework in software industry, is an environment where we can see collection of reusable software components or tools which are used to build the applications more efficiently with minimal code and time. It makes the developers life easier.

For example, If we are going to travel and stay in some place: furnished flat will be preferable than setting-up a new home. All available ready-made to pick-up and use. Another example LibreOffice Draw where you can draw, paint or creating logo. Here We will have set of drawing tools, just pick up and use it.

Definition:
Spring is a comprehensive framework, provides a broad set of tools and solutions for almost all kind of application development, whether you are building a small standalone application or a complex enterprise system, in particular web applications.

What is Spring Boot?
Spring Boot is a layer on top of Spring that simplifies application development, making the developer to focus mostly on the business logic and leaving all boiler plate codes to the spring boot framework.

Spring vs SpringBoot:
The main difference is in Spring the developer have the higher responsibility (or must be an Advanced Developer) to handle all work step by step (obviously will take more time) whereas with SpringBoot, we can do the same stuff very easily, quickly and safely (We can do with Spring also, but here SpringBoot will takes care of lot of tasks and minimize the coder’s work)

Ex. Spring – Birthday party event arranging by parents. (Each activity should be taken care of, like venue, invitation, cakes, decoration, food arrangements, return gifts etc.)

Spring Boot – An event organizer will take care of everything, so the parents just concentrate on the child and guests (like business logic) – whatever they want event organizer(spring boot) will assist by providing it.

What are Spring Boot’s Advantages?
Spring Boot is a layer on top of Spring that simplifies application development by providing the following:

  1. Faster Setup (Based on the dependencies and annotations).
  2. Simplifies development by Auto Configuration, application.properties or application.yml
  3. Embedded web servers with our finished product (.jar/.war)-eliminates the need for an external server like Tomcat to run the application, during deployment.
  4. Production-Ready features (Ex. Health checks-monitor application’s health, logging etc.)
  5. Simplified Deployment.
  6. Opinionated defaults. (TBD)
  7. Security features.
  8. Community and Ecosystem

Spring Framework’s main advantages are,
– Inversion of Control
– Dependency Injection

IoC (Inversion of Control):
The core principle of the Spring Framework. Usually the program flow or developer will control the execution here as the name suggests, control reversed, ie framework controls the flow. Ex. The event organizer having everything whatever the party or parent needs. It makes the developers with minimal code and better organized.

It makes everything ready to build the application instead searching or creating whenever required . My understanding here is,

  1. It scans the dependencies – based on that creates the required bean, checks the required .jar files are available in the class path.
  2. Through dependency injection passing beans as parameter to another bean when @Autowired detected.

Spring Boot starts and initializes the IoC container (via ApplicationContext – its the container for all beans).IoC scans the classpath for annotated classes like @Component, @Service, @Controller, @Repository.It creates beans (objects) for those classes and makes them available for dependency injection.Spring Boot scans application.properties or application.yml, applying those configurations to the beans or the application as needed.

Dependency Injection (DI):
–A design pattern that reduces the connection between the system components making the code more modular, maintainable and testable. It avoids the tight coupling between the classes and make the classes loosely coupled.

Coupling here is one class depends on another class.

For ex. In the same birthday party, if the parents arranged the setup one one theme (Dora-Bujju) for the kid and later the kid changed its mind set and asking for another theme (Julie – Jackie Chan). Now its a wastage of time and money, and parent’s frustration also. Instead, if they tell the organizer to change the theme (as its their work and having some days also) – its easily getting updated.

In Dependency Injection, we can consider like one class wants to use another class, then it should not use its object (bean) directly inside the body (Tight coupling). Future modification is getting tougher here, instead, just pass the bean (object) as a parameter (injecting that bean) into the required class (Constructor DI). In case if the injected bean (passed object as a parameter) wants to get changed in the future, just replace it with another bean(object) in the parameter section.


To Be Continued…

Reference: https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html

❌
❌