Introduction
Spring Boot is a lightweight application framework based on the Spring Framework. With Spring Boot, you can quickly start and run applications without complex configuration. In this course, we will explore backend development using Spring Boot, covering how to create a real application through an example of blog screen composition and how to test views.
1. Setting Up a Development Environment
To start a Spring Boot project, the following tools are required:
- Java Development Kit (JDK): You should use JDK 8 or higher.
- IDE: An integrated development environment such as IntelliJ IDEA, Eclipse, or VSCode.
- Build Tool: You can use Maven or Gradle.
1.1. Creating a Project with Spring Initializr
To save a lot of time and effort, you can use Spring Initializr to create a project. Here are the basic steps for project creation:
- Visit the website.
- Enter project metadata (Group, Artifact, etc.).
- Select the required dependencies (Starters): Spring Web, Spring Data JPA, Spring Boot DevTools, etc. are recommended.
- Click the “Generate” button to download the ZIP file.
- Extract the downloaded file and import it into your IDE.
2. Understanding Project Structure
Let’s take a look at the basic structure of the generated project:
└── src ├── main │ ├── java │ │ └── com │ │ └── example │ │ └── demo │ │ ├── DemoApplication.java │ │ ├── model │ │ ├── repository │ │ ├── service │ │ └── controller │ └── resources │ ├── application.properties │ └── static │ └── templates └── test
2.1. Role of Each Directory
Each directory has a specific purpose:
model:
Defines the data model of the application.repository:
Contains interfaces for interactions with the database.service:
Handles business logic.controller:
Processes HTTP requests and sends responses.
3. Example of Blog Screen Composition
Now, let’s compose the screen of a simple blog application. Below is an example of a controller and HTML view for displaying a list of blog posts.
3.1. Creating the Blog Post Model
package com.example.demo.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String content; // getters and setters }
3.2. Creating the Blog Repository
package com.example.demo.repository; import com.example.demo.model.Post; import org.springframework.data.jpa.repository.JpaRepository; public interface PostRepository extends JpaRepository{}
3.3. Creating the Blog Service
package com.example.demo.service; import com.example.demo.model.Post; import com.example.demo.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PostService { @Autowired private PostRepository postRepository; public ListfindAll() { return postRepository.findAll(); } public Post save(Post post) { return postRepository.save(post); } }
3.4. Creating the Blog Controller
package com.example.demo.controller; import com.example.demo.model.Post; import com.example.demo.service.PostService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller @RequestMapping("/posts") public class PostController { @Autowired private PostService postService; @GetMapping public String list(Model model) { Listposts = postService.findAll(); model.addAttribute("posts", posts); return "posts/list"; } @PostMapping public String create(Post post) { postService.save(post); return "redirect:/posts"; } }
3.5. Creating the HTML View
Now, let’s create an HTML view. Below is an example of a blog post list view using Thymeleaf:
Blog Post List Blog Post List
Title | Content |
---|---|
4. Testing the View
To ensure the application is working correctly, view tests must be performed. Spring Boot provides various tools to easily conduct integration tests.
4.1. Setting Up the Test Environment
First, the spring-boot-starter-test
dependency must be included. Add the following to your pom.xml
file:
org.springframework.boot spring-boot-starter-test test
4.2. Creating Integration Tests
Next, let’s create a test class for the controller:
package com.example.demo; import com.example.demo.model.Post; import com.example.demo.repository.PostRepository; import com.example.demo.service.PostService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; 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 java.util.Arrays; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; @WebMvcTest(PostController.class) public class PostControllerTest { @Autowired private MockMvc mockMvc; @MockBean private PostService postService; @BeforeEach public void setup() { Listposts = Arrays.asList( new Post(1L, "First Post", "Content 1"), new Post(2L, "Second Post", "Content 2") ); when(postService.findAll()).thenReturn(posts); } @Test public void testList() throws Exception { mockMvc.perform(get("/posts")) .andExpect(status().isOk()) .andExpect(view().name("posts/list")) .andExpect(model().attributeExists("posts")); } @Test public void testCreate() throws Exception { mockMvc.perform(post("/posts") .param("title", "New Post") .param("content", "Content")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/posts")); } }
4.3. Running the Tests
Running the above tests will confirm that the blog post listing and new post creation features are functioning correctly.
Conclusion
In this course, we explored backend development of a blog application using Spring Boot, covering how to set up the model, repository, service, controller, and HTML view necessary for building a real application. We also learned how to test the views we created. Through this course, I hope you will build a solid foundation to create powerful web applications using Spring Boot.