A Journey on Spring Boot | Introduction
Hello all,
In this series, I will write about Spring boot. I will go from the very beginning of creating a spring project to many complex parts of spring boot. You will be able to learn very basic concepts to complex concepts.
In this article, let’s see how we can setup a simple Spring boot project and write our first API
First, lets go to Spring Initializer and setup our project.
Select followings:
* Project: Maven
* Language: Java
* Spring Boot: 3.2.1 (3.2.x)
* Under project metadata, provide details about your project
* Packaging: war (Lets create a war file and deploy in tomcat)
* Java: 17
Now lets click on the Generate button and download our project file
I will be using Intellij as my IDE.
Lets now see how we can import this downloaded project as an intellij project
- Extract the downloaded zip file
- Open Intellij
- File -> New -> Project from existing sources …
- Click next until the project is opened in intellij
Now we are ready for coding. Lets write our first API.
For that, we need a controller class. The controller class will be responsible for handling a request and returning a model and a view. The controller class should be very simple and we should not write our business logics within the controller class.
For writing our business logics, we use service class. The service class will be responsible for performing business logic of the application.
In this article, lets create a controller class and a service class.
Controller class
package com.b1zt.springboot.introduction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/api")
public class IntroductoryController {
@Autowired
private IntroductoryService introductoryService;
@GetMapping("/hello")
public String hello() {
return introductoryService.hello();
}
@GetMapping("/helloWithName")
public String helloWithName(@RequestParam String name) {
return introductoryService.helloWithName(name);
}
}
In the above class, I want to highlight following annotations
@RestController: When a class is annotated with @RestController
, it is treated as a controller where every method returns a domain object, and the object is automatically serialized into JSON or XML response by Spring.
@RequestMapping: This can be used in both class level and method level. When used at the class level, @RequestMapping
is often used to define a common base path for all handler methods within that controller. At the method level, it is used to specify the endpoint path and HTTP method(s) that a particular method should handle.
@Autowired: The @Autowired
annotation in Spring is used to automatically inject dependencies into a Spring bean. With @Autowired
annotation, we do not need to explicitly initialize objects. In our code, we use this annotation to create a variable of IntroductoryService but we have not initialized that that variable anywhere. Spring will automatically initialized this object for us.
@GetMapping: The @GetMapping
annotation is a specialized form of the more general @RequestMapping
annotation in the Spring Framework. It is used to map HTTP GET requests to a specific method or handler in a controller class. This annotation is commonly used when building RESTful web services or applications where you want to handle HTTP GET requests for specific endpoints.
In the above code, I have defined two methods
public String hello(): This method is a simple get method. Once we make a get request to the path defined by the @RequestMapping
annotation, we will be able to invoke this method
public String helloWithname(@RequestParam String name): This method expect a query parameter called name. If we make a get request to the path defined by the @RequestMapping
annotation with a query parameter called name
we will be able to invoke this method.
Service Class
package com.b1zt.springboot.introduction;
import org.springframework.stereotype.Service;
@Service
public class IntroductoryService {
public String hello() {
return "Hello World!";
}
public String helloWithName(String name) {
if (name == null || name.isEmpty()) {
return "Hello World!";
}
return "Hello " + name + "!";
}
}
In this service class, I have used only one annotation
@Service:
The @Service
annotation in Spring is used to indicate that a class is a service and its instances are intended to be managed by the Spring IoC (Inversion of Control) container. Services are typically used to encapsulate business logic, and they act as a middle layer between controllers and data access logic.
In this code, I have defined two methods. Those are very simple methods which will return hello world and hello ${name}
If you check the controller class again, you will see, I have called these methods.
Now our coding is mostly done, Now lets build the project. Before building the project, we need to give a name to the final war file. For this, lets modify our pom.xml file and add following line to the pom.xml file
<finalName>Introduction</finalName>
<build>
<finalName>introduction</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
you can try building the project with and without this line and see the difference in the final war file
Now, lets build the project
open a terminal in the root of the project where pom.xml file exists
mvn clean install
Run above command to build the project
Now, if you check the target folder in the root of the project, you will see a war file called introduction.war.
Now we are going to deploy this war file in tomcat,
- First setup your tomcat environment.
- Copy the introduction.war file to the $TOMCAT_HOME/webapps directory
- Go to $TOMCAT_HOME/bin and run
bash catalina.sh run
Depending on your OS, this command might vary.
Now, your war file is deployed in tomcat.
By default tomcat will open in 8080 port. So, lets try to access our web service from a browser.
The URL for our get APIs will be as followed.
http://localhost:8080/introduction + /api + /hello ->
http://localhost:8080/introduction/api/hello
http://localhost:8080/introduction + /api + /helloWithName + ?name=B1zt -> http://localhost:8080/introduction/api/hello?name=B1zt
As you can see, we build our URL as few parts. Lets try to understand how our URL is built
First part, http://localhost:8080 is where our tomcat server is running. introduction is the name of our webapp, so tomcat deploy this webapp with this name. So, we can identify our webapp as following url http://localhost:8080/introduction
The second part is /api
We give a class level request mapping in our controller class. The value we gave was /api
That’s where we get /api
in our URL
The third part is /hello
or /helloWithName
We have defined get mapping for both our methods, the value we passed to that annotation is above values, so we get above values to our URL
Finally, for the helloWithName method, we are passing a query parameter as the input. So, a query param with will be added to that url ?name={name}
Now lets try to access these urls from our browser and see the results
- http://localhost:8080/introduction/api/hello
- http://localhost:8080/introduction/api/helloWithName?name=b1zt
Now you see the magic, you should be able to see the response from the browser. Now, you can try changing paths and business logic and see how things are working
This is the introductory article on spring boot, I will be hoping to cover more complex and interesting parts of spring boot in coming articles. Appriciate your feedback on the article and my writing style. Let me know how I can improve. Stay tuned for the next article on this series. Thank you