{"id":18153206,"url":"https://github.com/josemarqmt/personal-springboot-notes","last_synced_at":"2026-04-26T23:31:24.718Z","repository":{"id":260289353,"uuid":"880873468","full_name":"josemarqmt/personal-SpringBoot-notes","owner":"josemarqmt","description":"📝 Personal SpringBoot notes  key concepts, best practices, class structure, main annotations, testing and practical examples.","archived":false,"fork":false,"pushed_at":"2024-10-30T14:38:02.000Z","size":17,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-07T00:52:16.999Z","etag":null,"topics":["spring","spring-boot"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/josemarqmt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-30T14:17:04.000Z","updated_at":"2024-10-30T14:40:34.000Z","dependencies_parsed_at":"2024-10-30T15:41:14.669Z","dependency_job_id":null,"html_url":"https://github.com/josemarqmt/personal-SpringBoot-notes","commit_stats":null,"previous_names":["josemarqmt/personal-springboot-notes"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josemarqmt%2Fpersonal-SpringBoot-notes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josemarqmt%2Fpersonal-SpringBoot-notes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josemarqmt%2Fpersonal-SpringBoot-notes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/josemarqmt%2Fpersonal-SpringBoot-notes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/josemarqmt","download_url":"https://codeload.github.com/josemarqmt/personal-SpringBoot-notes/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247574097,"owners_count":20960495,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["spring","spring-boot"],"created_at":"2024-11-02T03:06:01.805Z","updated_at":"2026-04-26T23:31:24.660Z","avatar_url":"https://github.com/josemarqmt.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\n\n# Spring Boot Personal Notes\n\n![image](https://github.com/user-attachments/assets/c93b8dd3-ea49-4e83-8d24-04170118cfea)\n\n\n## Index\n1. [Overview of Spring and Spring Boot](#id1)\n2. [Understanding JDK and JVM in Context](#id2)\n3. [Key Concepts in Spring and Spring Boot](#id3)\n4. [Project Structure and Annotations](#id4)\n5. [Testing and Mocking in Spring Boot](#id5)\n\n\u003ca name=\"id1\"\u003e \u003c/a\u003e\n### 1. Overview of Spring and Spring Boot\nSpring is a powerful framework that simplifies Java development by addressing the complexities of building enterprise applications, particularly those based on J2EE (Java 2 Platform, Enterprise Edition). J2EE applications can be complex and heavyweight, requiring extensive configuration.\n\nSpring Boot, as an extension of Spring, was created to simplify the development of standalone applications. It allows developers to quickly bootstrap projects with minimal and default configurations, reducing the overhead associated with traditional J2EE setups. This makes Spring Boot particularly appealing for microservices architectures.\n\n\u003ca name=\"id2\"\u003e \u003c/a\u003e\n### 2. Understanding JDK and JVM in Context\n- **Java Development Kit (JDK)**: The JDK is essential for developing Java applications, including those built with Spring Boot. It provides the necessary tools, such as the Java compiler, which compiles your Java code into bytecode that can be executed on the JVM.\n  \n  Example commands:\n  ```bash\n  # Compile Java code\n  javac MyApplication.java\n\n  # Run the application\n  java MyApplication\n  ```\n\n- **Java Virtual Machine (JVM)**: The JVM is the runtime environment that executes Java bytecode, making Java applications platform-independent. When you run a Spring Boot application, the JVM interprets the compiled code, allowing it to run seamlessly across different systems.\n\n\u003ca name=\"id3\"\u003e \u003c/a\u003e\n### 3. Key Concepts in Spring and Spring Boot\n- **Aspect-Oriented Programming (AOP)**: AOP in Spring allows developers to separate cross-cutting concerns (such as logging and security) from business logic. This leads to cleaner and more manageable code, especially beneficial in large applications.\n\n- **Inversion of Control (IoC)** and **Dependency Injection (DI)**: \n  - **Inversion of Control (IoC)**: This is a design principle where the creation and management of objects is delegated to a container or framework. Instead of the application code controlling how dependencies are created and managed, the framework handles it, promoting a weaker coupling between classes.\n  \n  - **Dependency Injection (DI)**: This is a specific way of implementing IoC. In DI, a class's dependencies are provided externally (usually by an IoC container), rather than being created within the class itself. This allows classes to be easier to test and maintain since their dependencies can be mocked or replaced.\n\n### Explanation of `@Autowired`\nThe `@Autowired` annotation is used for dependency injection in Spring. It allows the Spring container to automatically inject the appropriate bean into a property, constructor, or method marked with this annotation. This eliminates the need for manually creating instances of dependencies, promoting cleaner and more maintainable code.\n\n**Example of using `@Autowired`**:\n```java\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class UserService {\n    private final UserRepository userRepository;\n\n    // Constructor injection\n    @Autowired\n    public UserService(UserRepository userRepository) {\n        this.userRepository = userRepository;\n    }\n\n    public User findUserById(Long id) {\n        return userRepository.findById(id).orElse(null);\n    }\n}\n```\n\nIn this example:\n- The `UserService` class has a dependency on `UserRepository`.\n- By using `@Autowired` on the constructor, Spring automatically injects an instance of `UserRepository` when it creates a `UserService` bean.\n\n**Setter Injection**:\nYou can also use `@Autowired` on setter methods if you prefer that form of injection.\n\n```java\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class UserService {\n    private UserRepository userRepository;\n\n    // Setter injection\n    @Autowired\n    public void setUserRepository(UserRepository userRepository) {\n        this.userRepository = userRepository;\n    }\n\n    public User findUserById(Long id) {\n        return userRepository.findById(id).orElse(null);\n    }\n}\n```\n\n### Explanation of `@Bean`\nThe `@Bean` annotation is used to declare a bean in the Spring context. A **bean** in Java is an object that is created, managed, and configured by the Spring container. You can think of a bean as any object that you need to be managed by Spring.\n\n**Example of using `@Bean`**:\n```java\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration\npublic class AppConfig {\n    \n    @Bean\n    public UserService userService(UserRepository userRepository) {\n        return new UserService(userRepository);\n    }\n}\n```\n\nIn this example:\n- The `AppConfig` class is marked as `@Configuration`, indicating that it contains bean definitions.\n- The `userService` method is marked with `@Bean`, indicating that it should be managed as a bean. When Spring creates this bean, it injects an instance of `UserRepository` as a constructor argument.\n\n\u003ca name=\"id4\"\u003e \u003c/a\u003e\n### 4. Project Structure and Annotations\n\n#### Class Interaction Diagram\n\nBelow is a simple diagram representing how different classes interact in the user management application workflow:\n\n```\n        +------------------+\n        |  UserController  |\n        +--------+---------+\n                 |\n                 | calls\n                 |\n        +--------v---------+\n        |    UserService   |\n        +--------+---------+\n                 |\n                 | calls\n                 |\n        +--------v---------+\n        |   UserRepository  |\n        +--------+---------+\n                 |\n                 | returns\n                 |\n        +--------v---------+\n        |       User       |\n        +--------+---------+\n                 |\n                 | converts to\n                 |\n        +--------v---------+\n        |     UserDTO      |\n        +------------------+\n```\n\n#### Example Workflow\n\n1. **Controller (UserController)**: This is the entry point for HTTP requests. It handles client requests and calls the corresponding service.\n\n   Example class:\n   ```java\n   import org.springframework.beans.factory.annotation.Autowired;\n   import org.springframework.http.ResponseEntity;\n   import org.springframework.web.bind.annotation.GetMapping;\n   import org.springframework.web.bind.annotation.PathVariable;\n   import org.springframework.web.bind.annotation.RequestMapping;\n   import org.springframework.web.bind.annotation.RestController;\n\n   @RestController\n   @RequestMapping(\"/api/users\")\n   public class UserController {\n       @Autowired\n       private UserService userService;\n\n       @GetMapping(\"/{id}\")\n       public ResponseEntity\u003cUserDTO\u003e getUserById(@PathVariable Long id) {\n           UserDTO userDTO = userService.findById(id);\n           return ResponseEntity.ok(userDTO);\n       }\n   }\n   ```\n\n   **Common Annotations**: \n   - `@RestController`: Combines `@Controller` and `@ResponseBody`, making it easier to create RESTful controllers.\n   - `@RequestMapping`: Defines the base path for requests.\n\n2. **Service (UserService)**: Contains the business logic for managing users. The controller calls this service to perform operations.\n\n   Example class:\n   ```java\n   import org.springframework.beans.factory.annotation.Autowired;\n   import org.springframework.stereotype.Service;\n\n   @Service\n   public class UserService {\n       @Autowired\n       private UserRepository userRepository;\n\n       public UserDTO findById(Long id) {\n           User user = userRepository.findById(id)\n               .orElseThrow(() -\u003e new UserNotFoundException(id));\n           return convertToDTO(user);\n       }\n\n       private UserDTO convertToDTO(User user) {\n           UserDTO dto = new UserDTO();\n           dto.setName(user.getName());\n           dto.setEmail(user.getEmail());\n           return dto;\n       }\n   }\n   ```\n\n   **Common Annotations**:\n   - `@Service`: Indicates that the class contains business logic.\n\n3. **Repository (UserRepository)**: Interacts with the database to perform data access operations. It is responsible for retrieving user information.\n\n   Example interface:\n   ```java\n   import org.springframework.data.jpa.repository.JpaRepository;\n   import org.springframework.stereotype.Repository;\n\n   @Repository\n   public interface UserRepository extends JpaRepository\u003cUser, Long\u003e {\n       // Additional query methods can be defined here\n   }\n   ```\n\n   **Common Annotations**:\n   - `@Repository`: Indicates that the class is a data access component.\n\n4. **Entity (User)**: Represents a data model that maps to a table in the database.\n\n   Example class:\n   ```java\n   import javax.persistence.Entity;\n   import javax.persistence.GeneratedValue;\n   import javax.persistence.GenerationType;\n   import javax.persistence.Id;\n\n   @Entity\n   public class User {\n       @Id\n       @GeneratedValue(strategy = GenerationType.IDENTITY)\n       private Long id;\n       private String name;\n       private String email;\n\n       // Getters and setters\n   }\n   ```\n\n   **Common Annotations**:\n   - `@Entity`: Marks the class as an entity that maps to a database table.\n   - `@Id`: Indicates the field that is the primary key.\n   - `@GeneratedValue`: Specifies that the primary key value will be generated automatically.\n\n5. **DTO (UserDTO)**: Used to transfer data between the controller and the service.\n\n   Example class:\n   ```java\n   public class UserDTO {\n       private String name;\n       private String email;\n\n       // Getters and setters\n   }\n   ```\n\n   **Common Annotations**:\n   - Typically does not require specific annotations but can be included in the conversion between entities and DTOs.\n\n6. **Exception (UserNotFoundException)**: Handles custom\n\n exceptions in case a user is not found.\n\n   Example class:\n   ```java\n   public class UserNotFoundException extends RuntimeException {\n       public UserNotFoundException(Long id) {\n           super(\"User not found: \" + id);\n       }\n   }\n   ```\n\n\u003ca name=\"id5\"\u003e \u003c/a\u003e\n### 5. Testing and Mocking in Spring Boot\n\nTesting is crucial for maintaining application quality. In Spring Boot, there are two primary types of tests: unit tests and integration tests.\n\n#### Unit Testing\nUnit tests are used to test individual components or classes in isolation.\n\n**Example of a Unit Test for UserService**:\n```java\nimport static org.mockito.Mockito.*;\nimport static org.junit.jupiter.api.Assertions.*;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\n\npublic class UserServiceTest {\n    @InjectMocks\n    private UserService userService;\n\n    @Mock\n    private UserRepository userRepository;\n\n    @BeforeEach\n    void setUp() {\n        MockitoAnnotations.openMocks(this);\n    }\n\n    @Test\n    public void testFindUserById_Success() {\n        User user = new User();\n        user.setId(1L);\n        user.setName(\"John Doe\");\n        user.setEmail(\"john.doe@example.com\");\n\n        when(userRepository.findById(1L)).thenReturn(Optional.of(user));\n\n        UserDTO userDTO = userService.findById(1L);\n\n        assertNotNull(userDTO);\n        assertEquals(\"John Doe\", userDTO.getName());\n        assertEquals(\"john.doe@example.com\", userDTO.getEmail());\n    }\n\n    @Test\n    public void testFindUserById_NotFound() {\n        when(userRepository.findById(1L)).thenReturn(Optional.empty());\n\n        assertThrows(UserNotFoundException.class, () -\u003e userService.findById(1L));\n    }\n}\n```\n\nIn this unit test:\n- We use Mockito to create a mock for the `UserRepository`.\n- The `@InjectMocks` annotation creates an instance of `UserService` and injects the mocked `UserRepository`.\n- We test the success case and the not found case for the `findById` method.\n\n#### Integration Testing\nIntegration tests are used to test how various components of the application work together.\n\n**Example of an Integration Test**:\n```java\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;\nimport static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.http.MediaType;\n\n@SpringBootTest\n@AutoConfigureMockMvc\npublic class UserControllerIntegrationTest {\n    @Autowired\n    private MockMvc mockMvc;\n\n    @Test\n    public void testGetUserById() throws Exception {\n        mockMvc.perform(get(\"/api/users/1\")\n                .accept(MediaType.APPLICATION_JSON))\n                .andExpect(status().isOk())\n                .andExpect(jsonPath(\"$.name\").value(\"John Doe\"))\n                .andExpect(jsonPath(\"$.email\").value(\"john.doe@example.com\"));\n    }\n\n    @Test\n    public void testGetUserById_NotFound() throws Exception {\n        mockMvc.perform(get(\"/api/users/999\")\n                .accept(MediaType.APPLICATION_JSON))\n                .andExpect(status().isNotFound());\n    }\n}\n```\n\nIn this integration test:\n- We use Spring's `MockMvc` to perform requests against the controller.\n- The first test checks that the endpoint returns a user with the expected details.\n- The second test checks the behavior when a user is not found.\n\n### Conclusion\nSpring Boot streamlines Java development, offering powerful features like dependency injection and easy setup for testing. Understanding its core concepts, such as IoC and DI, is essential for building robust applications. By leveraging annotations like `@Autowired` and `@Bean`, developers can create clean, maintainable code. Unit and integration tests further ensure the quality and reliability of applications.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjosemarqmt%2Fpersonal-springboot-notes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjosemarqmt%2Fpersonal-springboot-notes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjosemarqmt%2Fpersonal-springboot-notes/lists"}