Spring Boot 101: An Introduction to Building Web Applications

Kalpa D. Fernando
LinkIT
Published in
11 min readJan 18, 2023

--

Hey there, my name is Kalpa D. Fernando and I’m excited to take you on a journey through the world of Spring Boot! 🚀 Buckle up, because we’re going to dive deep into creating RESTful APIs, connecting to databases, and deploying applications.

Introduction

Spring Boot is a popular framework for building web applications using Java. It is a part of the Spring Framework, which is a collection of tools and libraries for building enterprise-grade applications. Spring Boot makes it easy to create stand-alone, production-grade applications that can be easily deployed and run with minimal configuration.

As a developer with about 3 years of experience working with Spring Boot, I can confidently say that it is one of the most powerful and versatile frameworks for building web applications using the Java programming language.

In my internship, I had the opportunity to work with Spring Boot’s built-in features, such as Spring Security and Spring Data. These features made it easy to implement security and data management in the application.

How Spring Boot makes a developers life easy?

Spring boot auto configuration. Source: Java67.com

In my experience, one of the greatest advantages of Spring Boot is its ability to automatically configure your application based on the dependencies you have added to your project. This feature saves a lot of time and effort for developers, as it eliminates the need for manual configuration. As a result, developers can focus on writing code and implementing features, rather than spending hours configuring the application.

Another advantage of Spring Boot is its support for a wide range of web application technologies. In my projects, I have used Spring Boot with Spring MVC, Spring WebFlux, and Thymeleaf. I have also worked with various data access technologies such as JPA, JDBC, ArangoDB and MongoDB. This flexibility allows developers to select the technology that best suits their needs, and eliminates compatibility issues.

The large and active community of Spring Boot developers is also a significant advantage. During my projects, I have frequently consulted tutorials, documentation, and sample code from the community. And whenever I ran into any issues, I could always find a solution by searching online or asking for help in forums dedicated to Spring Boot.

How to create a Spring Boot project?

There are several ways to create a Spring Boot project, but the most common method is to use the Spring Initializer website (https://start.spring.io/) or the Spring CLI (Command Line Interface) tool.

Method 1: Using Spring Initializer website:

Spring Initializer
  1. Go to the Spring Initializer website (https://start.spring.io/).
  2. Select the options that you want for your project, such as the project type, language, and Spring Boot version.
  3. Select the dependencies that you want to include in your project.
  4. Click on the Generate button to download a ZIP file containing the project files.
  5. Extract the contents of the ZIP file to a directory on your computer.
  6. Import the project into your preferred IDE (Integrated Development Environment) and start developing your application.

Method 2: Using Spring CLI:

  1. Install the Spring CLI tool on your computer. This can be done by following the instructions on the Spring website (https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started-installing-the-cli).
  2. Open a command prompt or terminal window.
  3. Run the command spring init --dependencies=web myproject to create a new Spring Boot project with the web dependency.
  4. The above command will create a new directory called “myproject” with the project files.
  5. Change into the new directory by running the command cd myproject
  6. Run the command ./mvnw spring-boot:run to start the application.

Both methods will create a basic Spring Boot project that you can use as a starting point for your application. Once the project is created, you can start developing your application by adding new controllers, services, and views as needed.

A Simple Spring Boot project

Below is a sample Spring Boot application that demonstrates how to create a simple “Hello, World!” endpoint using Spring MVC.

  1. Create a new Spring Boot project using the Spring Initializer website or the Spring CLI tool.
  2. Add the following dependency to your project’s pom.xml file (if you are using Maven) or build.gradle file (if you are using Gradle):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

3. Create a new package called “com.example.app” and inside that package create a new class called “HelloController” and add the following code:

package com.example.app;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}

4. Create a new class called “Application” and add the following code:

package com.example.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

5. Run the application by running the Application class as a Java application.

6. Open your browser and navigate to “http://localhost:8080/hello". You should see the message “Hello, World!” displayed in the browser.

This is a very basic example of how to create a simple endpoint using Spring Boot. You can add more functionality and complexity to the application as needed.

Creating a RESTful API endpoint

Rest architecture, Source: Java Guides

Creating a RESTful API endpoint with Spring Boot is a relatively straightforward process. The first step is to create a new controller class and annotate it with the @RestController annotation. This annotation tells Spring Boot that the class should be treated as a controller and that it should handle incoming HTTP requests.

Next, you will need to create a new method within the controller class and annotate it with the @RequestMapping annotation. This annotation maps the method to a specific URI, and it can also specify the HTTP method that the method should handle. For example, you can use the @GetMapping annotation to map a method to a specific URI and handle only GET requests.

Here’s an example of a simple RESTful API endpoint that maps to the “/hello” URI and returns a message “Hello, World!” when the endpoint is accessed:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}

In this example, the @RestController annotation tells Spring Boot to treat the class as a controller, and the @GetMapping("/hello") annotation maps the sayHello() method to the "/hello" URI and handles only GET requests. The method returns the string "Hello, World!" when the endpoint is accessed.

You can also pass parameters to the endpoint by using the @PathVariable annotation, for example:

@GetMapping("/hello/{name}")
public String sayHello(@PathVariable String name) {
return "Hello, " + name + "!";
}

In this example, the endpoint /hello/{name} accepts a name parameter in the path and returns "Hello, [name]"

You can also use the @RequestParam annotation to pass query parameters to the endpoint, for example:

@GetMapping("/hello")
public String sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
return "Hello, " + name + "!";
}

In this example, the endpoint /hello accepts a name parameter in the query and return "Hello, [name]".

This is just a basic example of how to create a RESTful API endpoint using Spring Boot, you can add more functionality and complexity to the application as needed.

Using Spring Boot’s built-in features

Source: tutorialandexample.com

Spring Boot provides a variety of built-in features that can be easily integrated into your application to add functionality and simplify development. Some of the most commonly used built-in features include:

  1. Spring Security: Spring Boot provides built-in support for adding authentication and authorization to your application. This can be done by adding the spring-boot-starter-security dependency to your project and configuring the security settings in the application.properties or application.yml file.
  2. Spring Data: Spring Boot provides built-in support for working with databases and other data sources. This can be done by adding the spring-boot-starter-data-jpa or spring-boot-starter-data-mongodb dependency to your project and configuring the data source in the application.properties or application.yml file.
  3. Spring WebFlux: Spring Boot provides built-in support for building reactive web applications. This can be done by adding the spring-boot-starter-webflux dependency to your project and using the reactive programming model provided by Spring WebFlux.
  4. Spring Actuator: Spring Boot provides built-in support for monitoring and managing your application. This can be done by adding the spring-boot-starter-actuator dependency to your project and configuring the actuator settings in the application.properties or application.yml file.

Here is an example of how to use Spring Security in a Spring Boot application:

  1. add the spring-boot-starter-security dependency to your project.
  2. Create a new class called “SecurityConfig” and add the following code:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/hello").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}

In this example, the SecurityConfig class is used to configure the security settings for the application. The configure() method is used to configure the authentication manager and the configure() method is used to configure the HTTP security settings.

The antMatchers("/hello").permitAll() line allows all requests to the "/hello" endpoint to be accessed without authentication, while anyRequest().authenticated() requires authentication for all other requests. And the formLogin() method enables form-based authentication for the application.

Similarly, you can use Spring Data and Spring WebFlux by adding the appropriate dependencies and configuring the settings in the application.properties or application.yml file. And for Spring Actuator, add the spring-boot-starter-actuator dependency and configure the actuator settings in the application.properties or application.yml file.

Connecting your Spring Boot app to a database

Spring database connection illustration

Spring Boot provides built-in support for connecting to a variety of databases, including relational databases (such as MySQL, PostgreSQL, and Oracle) and NoSQL databases (such as MongoDB and Cassandra).

One of the most common ways to connect to a database in Spring Boot is by using the Spring Data JPA (Java Persistence API) module. This module provides a consistent and simple way to interact with databases using the JPA standard.

To use Spring Data JPA in your application, you will need to add the spring-boot-starter-data-jpa dependency to your project and configure the data source in the application.properties or application.yml file.

Here is an example of how to configure a MySQL database connection in Spring Boot:

  1. Add the spring-boot-starter-data-jpa and mysql-connector-java dependencies to your project.
  2. In the application.properties or application.yml file, configure the data source by adding the following properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password

Deploying a Spring Boot application

Deploying a Spring Boot application can be done in a variety of ways, depending on your specific requirements and the environment in which you are deploying. Some of the most common ways to deploy a Spring Boot application include:

  1. Running the application as a standalone jar or war file: This is the simplest way to deploy a Spring Boot application, and it can be done by using the Spring Boot Maven or Gradle plugins to package the application as a standalone jar or war file. Once the application is packaged, it can be run using the java -jar command.
  2. Deploying to a web server: Spring Boot applications can also be deployed to a web server, such as Apache Tomcat or Jetty. This can be done by packaging the application as a war file and deploying it to the web server.
  3. Deploying to a cloud provider: Spring Boot applications can be easily deployed to cloud providers such as AWS, Azure, and Google Cloud. This can be done by using cloud-specific tools and services, such as Elastic Beanstalk, App Engine, and Cloud Foundry.
  4. Using a containerization platform: Spring Boot applications can be deployed using containerization platforms such as Docker, Kubernetes, and OpenShift. This can be done by creating a Docker image of the application and deploying it to the containerization platform.
  5. Deploying to an application server: Spring Boot applications can be deployed to an application server such as WildFly, JBoss EAP, and WebLogic. This can be done by packaging the application as a war file and deploying it to the application server.

It’s important to note that the deployment process may vary depending on the specific environment and the requirements of your application. It’s a good idea to test the application in different environments before deploying it to a production environment.

For more detailed instructions on deploying a Spring Boot application, you can refer to the Spring Boot documentation at https://docs.spring.io/spring-boot/docs/current/reference/html/deployment.html .

Best practices and troubleshooting

When working with Spring Boot, there are several best practices and troubleshooting techniques that can help you build better applications and resolve issues more quickly.

  1. Keep the Spring Boot version up-to-date: Spring Boot is constantly evolving, and new versions are released regularly. Keeping your application’s Spring Boot version up-to-date can help ensure that you have access to the latest features and bug fixes.
  2. Use Spring Boot’s built-in logging: Spring Boot provides built-in support for logging, and it’s recommended to use this feature rather than a third-party logging library. This will provide better integration with the Spring Boot ecosystem and make it easier to troubleshoot issues.
  3. Use the Spring Boot Actuator: The Spring Boot Actuator provides a variety of endpoints that can be used to monitor and manage your application. This can help you quickly identify and resolve issues.
  4. Keep your application’s dependencies up-to-date: Regularly updating the dependencies of your application can help ensure that you have access to the latest features and bug fixes.
  5. Use a Profiler: Spring Boot provides built-in support for profiling your application, which can help you identify performance bottlenecks and memory leaks.
  6. Use Spring Boot’s testing support: Spring Boot provides built-in support for testing, which can help you quickly and easily write and run tests for your application.
  7. Be mindful of the configuration: Spring Boot allows you to configure your application through various methods such as properties file, yml file, and annotations. Be mindful of the configuration you are using, and make sure it’s the correct one.
  8. Check the documentation: Spring Boot has extensive documentation available that can help you understand how to use the framework and solve common issues.

For troubleshooting, Spring Boot also provides a variety of debugging options that can help you quickly identify and resolve issues. For example, you can use the Spring Boot Actuator to view application metrics, or you can enable debugging by adding the — debug flag when starting the application. Additionally, you can use the Spring Boot DevTools to quickly make changes to your application and see the results in real time.

Another useful tool for troubleshooting is the Spring Boot CLI, which allows you to quickly run and test Spring Boot applications from the command line. This can be useful for quickly identifying and resolving issues without having to set up a full development environment.

Overview

The article discussed the process of creating a RESTful API endpoint, using Spring Boot’s built-in features, connecting to a database, deploying a Spring Boot application, and best practices and troubleshooting techniques.

Spring Boot provides built-in support for connecting to databases, adding security to the application, working with the Spring WebFlux module, and monitoring the application through Spring Actuator. Additionally, it can be easily deployed to a variety of environments, including standalone, web servers, cloud providers, containerization platforms, and application servers. By following best practices such as keeping the Spring Boot version up-to-date, using Spring Boot’s built-in logging, and using the Spring Boot Actuator, developers can build better applications and resolve issues more quickly.

In conclusion, Spring Boot is a powerful and flexible framework for building web applications using Spring Framework. It simplifies the development process by providing a variety of built-in features and tools that can be easily integrated into your application.

--

--

Kalpa D. Fernando
LinkIT

Exploring tech, programming & AI. Passionate about sharing my knowledge and improving my skills via Medium articles.