0% found this document useful (0 votes)
77 views26 pages

A Step-by-Step Guide To Setting Up Your First Application

The document provides a step-by-step guide to setting up a basic Spring Boot application. It covers prerequisites, project setup using Spring Initializr, importing the project into an IDE, basic Maven commands, and the pom.xml file structure.

Uploaded by

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

A Step-by-Step Guide To Setting Up Your First Application

The document provides a step-by-step guide to setting up a basic Spring Boot application. It covers prerequisites, project setup using Spring Initializr, importing the project into an IDE, basic Maven commands, and the pom.xml file structure.

Uploaded by

twinkle dhake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

From Zero to Spring Boot Hero: A Step-by-Step Guide to Setting up

Your First Application.

Introduction
Hi guys! In this article, we will create a basic “Welcome” example in the easiest way. So
that you can use it as a template for your upcoming projects.

There are lots of different ways to do that of course, but we are going to use the easiest
one available.

Let’s get started!

Prerequisites
● Basics of Spring framework and Spring Boot.
● Basic Knowledge of Java programming language.
● Java development kit (JDK) installed and set up on your computer.
● Apache Maven installed in your system.
● Postman installed in your system.
● Install the Java IDE of your preference. In my case, I am using IntelliJ.

Verify Java & Maven Installations:


➢ To verify if Java is installed and configured correctly on your system, open
the terminal and type in the command java -version to see the version
of Java installed.

1
➢ To verify if Maven is installed and configured correctly on your system,

open the terminal and type in the command mvn -version to see the

version of Maven installed.

Project Setup using Web based Spring Initializr


We are going to use Spring Initializr, which is a tool that automatically creates
the base project for us with the selected language, version, and dependencies.

❖ Open Spring Initializr in your web browser.

❖ Choose the Maven project option.

❖ Select Java as the language.

❖ Leave the default Spring Boot version selected.

❖ Choose the Java version according to the installed version on your

computer.

❖ In the dependencies section, add Spring Web to your project's

dependencies.

❖ Select the JAR packaging option and click on the generate button to

download the project as a ZIP file.

❖ Extract the ZIP file to a designated folder.

2
Import the code to IDE
❖ Launch your IDE, go to files, and open the project. Navigate to the folder

where you extracted your project and click Ok to open.

❖ Intellij will now automatically download all your dependencies for your

project. If for some reason your dependencies are not downloaded, select

Maven on the ride side of your IDE and refresh your IDE.

❖ This will RESTART your IDE and re-initiate download to your dependencies.

If your project was imported successfully your IDE should look something

like this:

3
Maven Intro:
Maven is a build automation and project management tool primarily used for

Java-based projects. It simplifies the process of managing dependencies,

compiling source code, and packaging the application into a deployable format.

Basic Maven commands:

mvn clean:

● The clean command removes the compiled output and other build
artifacts from the previous build, ensuring a clean project state
before starting a new build.

4
mvn compile:

● The compile command compiles the source code of your Java


project, generating the corresponding bytecode. It also resolves and
downloads any required dependencies from remote repositories.

mvn test:

● The test command executes the unit tests present in your project. It
ensures that your code behaves as expected and helps identify any issues
or bugs.

mvn package:

● The package command creates a deployable artifact, such as a JAR (Java


Archive) file or a WAR (Web Application Archive) file. It includes the
compiled code and any resources required for the application to run.

mvn install:

● The install command installs the project's artifact into the local Maven
repository. Other projects can then use this artifact as a dependency,
simplifying the management of dependencies across multiple projects on
your local machine.

mvn clean install:

● The clean install command combines both the clean and install
commands. It cleans the project and its dependencies, compiles the code,
runs the tests, and installs the resulting artifact into the local repository.

5
pom.xml File in Spring Projects: Understanding the Backbone of Dependency
Management and Build Configuration

The pom.xml file is an essential part of a Spring project that uses Apache Maven
as its build tool. It stands for "Project Object Model" and is an XML file that
contains information about the project, its dependencies, and the build process
configuration. Let's break down its components:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>Greetings</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Greetings</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>20</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

6
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

● Project Information:

❖ Group ID: It identifies the organization or group to which the


project belongs.

❖ Artifact ID: It specifies the unique identifier for the project.

❖ Version: It denotes the version of the project.

● Project Dependencies:

❖ Dependencies: This section lists the external libraries and


frameworks required by the project. Each dependency is defined
with its group ID, artifact ID, and version.

❖ Dependency Management: This section allows you to manage the


versions of dependencies used across multiple modules within a
multi-module project.

<dependencies>
// Add all dependencies here
</dependencies>

● Build Configuration:

❖ Build Plugins: Plugins extend the functionality of Maven. They can


be used for various purposes, such as compiling source code,

7
running tests, creating executable JARs, generating documentation,
etc. Plugins are defined with their group ID, artifact ID, and version.

❖ Build Profiles: Profiles provide a way to customize the build process


for different environments or scenarios. They allow you to specify
different sets of dependencies, build plugins, or other
configurations based on specific conditions.

<build>
</build>

● Build Lifecycle:

❖ Maven defines a set of build phases (e.g., compile, test, package,


install, deploy) that execute in a predefined order. These phases are
executed by invoking specific Maven commands, such as mvn clean
install. The pom.xml file specifies the default build phases and can
be customized to include additional or modified build steps.

● Project Reporting

❖ Reporting Plugins: Maven supports various reporting plugins that


generate reports on different aspects of the project, such as code
coverage, test results, documentation, and more. These plugins are
configured in the pom.xml file and can be executed to generate
reports.

Project files structure


The folder structure typically follows the standard Maven project structure. Let's
go through the main components of this folder structure:

● src/main/java:

❖ This folder contains the Java source code files of your project.

❖ The package structure is usually organized based on the project's


group ID and artifact ID defined in the pom.xml file.

8
❖ It is in this folder that you will create your Spring Boot application
class with the @SpringBootApplication annotation.

● src/main/resources:

❖ This folder contains non-Java resources used by your application.

❖ Configuration files, such as application.properties or


application.yml, are typically placed here. These files store various
settings for your application, such as database connection details,
logging configuration, or custom properties.

❖ Additionally, you can store static files, templates, and other


resources used by your application in this folder.

● src/test/java:

❖ This folder holds the Java source code files for unit tests and
integration tests.

❖ The package structure here often mirrors the structure of the main
source code.

❖ You can create test classes and methods using testing frameworks
like JUnit or TestNG to verify the behavior of your application.

● target:

❖ This folder is automatically generated when you build your project


using Maven or IntelliJ IDEA.

❖ It contains the compiled Java classes, packaged JAR or WAR files,


and other build artifacts.

❖ This folder is typically excluded from version control, as its contents


can be regenerated from the source code.

9
Enable Logging

❖ The logger is used to record different log levels, such as info, warning,

error and trace to provide information and trace the execution flow of the

service.

❖ logger.info();

● Description: Provides informational messages about the

application's progress and important events.

Example: logger.info("Text to log");

❖ logger.debug();

● This method is used to log a message with the DEBUG log level.The

DEBUG log level is typically used for debug-level logging statements.

These statements are used during development or troubleshooting

to provide additional information that helps in understanding the

flow and behavior of the application.

10
Example: logger.debug("Debug message");

❖ logger.error();

● This method is used to log a message with the ERROR log level.The

ERROR log level is used for logging error-level statements. It is

typically used to capture and report critical errors or exceptions

that impact the functionality of the application. These log

statements represent severe issues that require attention and

possibly immediate action.

Example: logger.error("Error message");

❖ logger.warn();

● The WARN log level is used for logging warning-level statements. It

is typically used to indicate potential issues, non-critical errors, or

situations that require attention but may not immediately impact

the functionality of the application.Messages logged with the WARN

log level alert developers or operators about conditions that may

lead to problems or undesired behavior. These log statements

serve as early warnings to take corrective actions or investigate

potential issues.

Example: logger.warn("Warning message");

❖ logger.trace();

● This line logs a trace-level message with the text. The trace()

method is used for more detailed and low-level logging, often used

for debugging or tracking the flow of the application.

Example: logger.trace(" Trace execution flow");

11
Adding Service layer
❖ In the root package of our application create a package with the name

“service”. In the “service” package created above, create a class with the

name “GreetingService”.

❖ The service class is annotated with @Service, indicating that it is a

Spring-managed service bean.

❖ Our service layer contains a logger instance created using the

“LoggerFactory.getLogger()” method from the SLF4J (Simple Logging

Facade for Java) library.

❖ The “message()” method logs information using the logger and returns a

string message: "Welcome to SpringBoot".

package com.example.Greetings.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service

public class GreetingService {


final Logger logger=
LoggerFactory.getLogger(GreetingService.class);

public String message(){


logger.info("I'm up!");
logger.info("Status: 200 ok");
logger.trace("Greeting Service executed!");
return "Welcome to SpringBoot";
}
}

12
Creating a Test Controller

❖ In a Spring Boot application, a controller is a key component responsible


for handling incoming requests, processing them, and returning
appropriate responses. It acts as an intermediary between the client
(typically a web browser or API consumer) and the business logic of the
application.

❖ An overview of what a controller does in a Spring Boot application:

➢ Request Mapping:

● The controller class is annotated with @RestController,


indicating that it is a Spring MVC controller that handles web
requests.

● The @RequestMapping("/api") annotation sets the base


path for all the controller's request mappings to "/api".

➢ Handling Requests:

● When an incoming request is received for a mapped URL, the


Spring Boot framework routes the request to the appropriate
controller method based on the URL mapping.

● The controller method executes the business logic required


to process the request. It may call service classes, perform
data access operations, or interact with other components of
the application.

➢ Data Processing:

● The controller method processes the request data, performs


any necessary validation or transformations, and prepares
the data for further processing.

● It may invoke service classes or delegate to other


components to perform the required operations, such as

13
retrieving data from a database, updating records, or
executing business logic.

➢ Generating Responses:

● After processing the request, the controller method


constructs an appropriate response based on the
application's requirements.

● The response can be in various formats, such as JSON, XML,


HTML, or plain text, depending on the request and the
expected response type.

● The controller method returns the response using the


appropriate return type, such as ResponseEntity<T>,
ModelAndView, or the @ResponseBody directly.

❖ For our endpoint, in the root package of the project create a package with
the name “controller”. In the controller package we created above, create
a Java class with the name “GreetingController”.

❖ The @RequestMapping("/api") annotation sets the base path for all the
controller's request mappings to "/api".

❖ The @Autowired annotation injects an instance of the “GreetingService”


into the controller.

❖ The @GetMapping("/welcome") annotation maps HTTP GET requests to


the "/api/welcome" endpoint to the “greeting()” method.

❖ The “greeting()” method calls the “message()” method of the


“GreetingService” and returns the result as a response.

14
package com.example.Greetings.controller;

import com.example.Greetings.service.GreetingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class GreetingController {

@Autowired
public GreetingService service;

public static final Logger logger=


LoggerFactory.getLogger(GreetingController.class);
@GetMapping("/welcome")
public @ResponseBody String greeting(){
logger.info("Greeting Controller executed!");
return service.message();

}
}

Configuration with application.properties

To access the “application.properties” file in your Spring Boot project, navigate to


the “src/main/resources” directory. Inside this directory, you should find the
“application.properties” file. This file contains the configuration settings,
including the logging configuration, server port specification which you can
modify to customize the behavior of your application.

server.port=8090
logging.level.root=INFO
logging.level.com.example.Greetings.service=TRACE

15
➢ server.port=8090:

● This property sets the port on which the server will listen for
incoming requests. In this case, the value is set to 8090. Therefore,
the server will be accessible at http://localhost:8090.

➢ logging.level.root=INFO:

● This property configures the logging level for the root logger. The
root logger serves as the parent logger for all other loggers in the
application. By setting it to INFO, log messages with the INFO level
and higher (e.g., WARN, ERROR) will be logged.

➢ logging.level.com.example.Greetings.service=TRACE:

● This property sets the logging level specifically for the


“com.example.Greetings.service” component's logger. By setting it
to TRACE, the logger will capture all log messages, including DEBUG,
INFO, WARN, and ERROR, for this component. This level of logging
can provide detailed information about the execution flow within
the “GreetingService”.

Testing the "Welcome" Application


❖ Testing is a crucial part of software development as it ensures the
reliability and correctness of our code. In this section, we will explore how
to write a test program to validate the functionality of our "Welcome"
application in Spring Boot.

❖ The web dependency in Spring Boot provides testing facilities through the
MockMvc framework. It allows you to test your web layer (controllers)
without starting a full web server. This makes it efficient and convenient
for unit testing your controllers in isolation. The dependency provided
below enables testing in a Spring Boot application.

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

16
The Importance of Testing

❖ Before we dive into writing tests, let's discuss why testing is essential.
Testing allows us to catch bugs and errors early in the development
process, ensuring that our application works as expected. It also provides
a safety net when making changes or refactoring code, as we can easily
verify that existing functionality remains intact.

❖ Additionally, writing tests promotes good coding practices, such as


modular and loosely coupled code, which leads to better maintainability
and scalability of the application. It also boosts confidence in our code,
especially when working in a team or collaborating with other developers.

Writing a Test Program

To perform testing in Spring Boot, we can leverage the testing capabilities


provided by the Spring Testing Framework and JUnit. Let's create a simple test
program to verify the functionality.

❖ Start by creating a new package “controller” inside the root package of the
test/java folder of your application.

❖ Create a java class “GreetingsTestController” inside the “controller”


package.

GreetingsTestController:

❖ This class is a JUnit test class for testing the GreetingController in


the com.example.Greetings.controller package.

❖ The @WebMvcTest annotation is used to indicate that this test


focuses on testing the web layer of the application and specifically
the MVC controller.

❖ In the test class, there are a couple of important annotations used:

● @Autowired: This annotation is used to inject dependencies.


In this case, it is used to inject the MockMvc instance, which
allows us to perform HTTP requests and receive responses
for testing.

● @MockBean: This annotation is used to create a mock bean


of the GreetingService class, which is a dependency of the
GreetingController. It allows us to define the behavior of the
mock bean for testing purposes.

17
● @Test annotation is used to mark a method as a test
method.

❖ The testGreeting() method is the actual test case.

● It configures the behavior of the mock greetingService using


when().thenReturn() from Mockito. In this case, it sets up the
greetingService to return "Welcome to SpringBoot" when its
message() method is called.

● It performs a GET request to the "/api/welcome" endpoint


using the MockMvc instance.

● It asserts that the response status is isOk() (HTTP 200) and


the response content is "Welcome to SpringBoot".

● The andDo(print()) method is used to print the request and


response details to the console for debugging purposes.

package com.example.Greetings.controller;

import com.example.Greetings.service.GreetingService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import
org.springframework.test.web.servlet.request.MockMvcRequestBuilder
s;
import
org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.mockito.Mockito.when;


import static
org.springframework.test.web.servlet.result.MockMvcResultHandlers.
print;

18
@WebMvcTest(GreetingController.class)
public class GreetingsTestController {
private static final Logger logger =
LoggerFactory.getLogger(GreetingsTestController.class);

@Autowired
private MockMvc mockMvc;

@MockBean
private GreetingService greetingService;

@Test
public void testGreeting() throws Exception {
logger.info("Running GreetingControllerTest...");

when(greetingService.message()).thenReturn("Welcome to
SpringBoot");

mockMvc.perform(MockMvcRequestBuilders.get("/api/welcome"))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk())

.andExpect(MockMvcResultMatchers.content().string("Welcome to
SpringBoot"));
}
}

❖ GreetingsApplicationTests:

❖ This class is the main test class for the com.example.Greetings


package.

❖ It is annotated with @SpringBootTest, which is used to indicate that


this is a Spring Boot test and the application context should be
loaded for the test.

❖ The contextLoads() method is an empty test method that serves as


a placeholder for testing the application context. It ensures that the
Spring Boot application context can be successfully loaded without
any errors.

19
❖ @Test annotation is used to mark a method as a test method.

package com.example.Greetings;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class GreetingsApplicationTests {

@Test
void contextLoads() {
}

These test classes demonstrate how to write unit tests for a Spring Boot
application's controller using the MockMvc framework. The
GreetingsTestController class specifically focuses on testing the behavior of the
GreetingController by mocking its dependencies, while the
GreetingsApplicationTests class ensures the successful loading of the application
context. These tests help ensure the correctness and stability of the application
by validating the expected behavior of the controller and verifying the overall
application setup.

Running the Test Program

To run our test program run the “GreetingsApplicationTest” class. After a


successful run your console should look something like this:

20
Running the application
To test our application, run the application by clicking the green play button on
the top right of your screen. After a successful run your console should look
something like this:

We can also run the application from the terminal. To run a Spring Boot
application from the terminal in Ubuntu, you can follow these steps:

● Build the project:


❖ Open a terminal and navigate to the root directory of your Spring Boot
project.

❖ Open a terminal and navigate to the root directory of your Spring Boot
project.

❖ Make sure you have Apache Maven installed. If not, you can install it
by running the command: sudo apt install maven.

❖ Navigate to the project directory & run the command:

❖ mvn clean package to build the project.

❖ mvn test to run the test.

❖ Maven will compile the source code, run tests, and create an
executable JAR file in the target directory.

● Running the application from terminal:


❖ Navigate to the project directory:

cd <path-to-your-project-folder>.

21
❖ Use the java -jar command followed by the name of the generated JAR
file to run the application. For example:

java -jar target/my-application.jar.

❖ Spring Boot will start the application, and you should see the logs in
the terminal indicating that the application is running.

NOTE :

❖ Make sure your Spring Boot project is set up correctly, including the
necessary dependencies and the main application class with the proper
“@SpringBootApplication” annotation.

❖ If you encounter any issues, check your project's dependencies, ensure


the correct version of Java is installed, and verify that the application is
correctly configured.

After running the test program on terminal ,it should look something like this:

Also, after running your application on terminal ,it should look something like
this:

22
Test APIs Endpoint
Next, open your browser and enter the following URL:
localhost:8090/api/welcome. You should see the “Welcome to SpringBoot”
message on your browser:

To test your application and observe its functionality, you can also use a popular
tool called Postman. Follow these steps to test your application:

❖ Launch Postman: Open the Postman application on your computer.

❖ Set the request method: Choose the HTTP method as "GET" from the

dropdown menu.

❖ Set the request URL: Enter the URL for your API endpoint in the request

URL field. In this case, it would be http://localhost:8090/api/welcome.

❖ Send the request: Click on the "Send" button to send the GET request to

the specified endpoint.

❖ Observe the response: Postman will display the response received from

the server. In this case, you should see the "Welcome to SpringBoot"

message as the response.

23
When you hit the URL in Postman or a browser, the content logged using the

logger in your application will appear in the console. The console output will

typically display log messages based on their respective log levels. Here's an

explanation of how the content in the logger will appear in the console:

➢ Console Output Levels:

● Log messages with the log level set to "INFO" will be displayed in

the console's standard output. These messages typically provide

general information about the application's execution flow.

● Log messages with the log level set to "TRACE" will also be

displayed in the console's standard output. These messages

provide more detailed information and are useful for debugging or

tracing the application's internal operations.

➢ Format of Console Output:

● The console output typically includes a timestamp indicating when

the log message was generated.

24
● It may also include the name of the logger or the class generating

the log message, providing information about the source of the

message.

● The log message itself, such as "I'm up!", "Status: 200 ok", or

"Greeting Service executed!", will be displayed in the console.

The console might display log messages like:

Conclusion

➢ In this project, we built a simple Welcome API using Spring Boot. The code
consisted of a service class and a controller class , which worked together
to handle HTTP requests and provide a welcome message.

➢ We explored the functionality of the logger, which played a crucial role in


capturing and recording log messages at different levels such as "info"
and "trace". The logger helped us monitor the application's execution,
track important events, and troubleshoot any issues that might arise.

➢ Additionally, we discussed the application.properties file, which allowed


us to configure aspects of the application, including the server port and
logging levels. By adjusting these properties, we could customize the
behavior and verbosity of our application according to our requirements.

25
➢ In addition to the mentioned points, we also learned about the test
program features provided by Spring Boot. These testing capabilities
enable us to ensure the correctness and stability of our codebase through
automated testing.

To further explore the project and access the complete source code, you can
find it on GitHub.

Thank you for following along with this post, and I hope it has provided you with
valuable insights into building a Welcome API in Spring Boot!

26

You might also like