A Step-by-Step Guide To Setting Up Your First Application
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.
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.
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
computer.
dependencies.
❖ Select the JAR packaging option and click on the generate button to
2
Import the code to IDE
❖ Launch your IDE, go to files, and open the project. Navigate to the folder
❖ 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
compiling source code, and packaging the application into a deployable format.
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:
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:
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.
● 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:
● Project Dependencies:
<dependencies>
// Add all dependencies here
</dependencies>
● Build Configuration:
7
running tests, creating executable JARs, generating documentation,
etc. Plugins are defined with their group ID, artifact ID, and version.
<build>
</build>
● Build Lifecycle:
● Project Reporting
● src/main/java:
❖ This folder contains the Java source code files of your project.
8
❖ It is in this folder that you will create your Spring Boot application
class with the @SpringBootApplication annotation.
● src/main/resources:
● 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:
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();
❖ logger.debug();
● This method is used to log a message with the DEBUG log level.The
10
Example: logger.debug("Debug message");
❖ logger.error();
● This method is used to log a message with the ERROR log level.The
❖ logger.warn();
potential issues.
❖ 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
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 “message()” method logs information using the logger and returns a
package com.example.Greetings.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
12
Creating a Test Controller
➢ Request Mapping:
➢ Handling Requests:
➢ Data Processing:
13
retrieving data from a database, updating records, or
executing business logic.
➢ Generating Responses:
❖ 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".
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;
}
}
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:
❖ 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.
❖ Start by creating a new package “controller” inside the root package of the
test/java folder of your application.
GreetingsTestController:
17
● @Test annotation is used to mark a method as a test
method.
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;
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:
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.
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:
❖ 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.
❖ Maven will compile the source code, run tests, and create an
executable JAR file in the target 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:
❖ 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.
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:
❖ 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
❖ Send the request: Click on the "Send" button to send the GET request to
❖ Observe the response: Postman will display the response received from
the server. In this case, you should see the "Welcome to SpringBoot"
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:
● Log messages with the log level set to "INFO" will be displayed in
● Log messages with the log level set to "TRACE" will also be
24
● It may also include the name of the logger or the class generating
message.
● The log message itself, such as "I'm up!", "Status: 200 ok", or
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.
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