logo
eng-flag

Spring Boot Cheatsheet

Table of Contents

  1. Spring Boot Basics
  2. Spring Boot Annotations
  3. Spring Boot Configuration
  4. Spring Boot Data Access
  5. Spring Boot Web
  6. Spring Boot Testing
  7. Spring Boot Actuator
  8. Spring Boot Security
  9. Spring Boot Best Practices

Spring Boot Basics

What is Spring Boot?

Spring Boot is an open-source Java-based framework used to create stand-alone, production-grade Spring-based applications with minimal configuration.

Key Features

  • Opinionated 'starter' dependencies
  • Embedded server
  • Auto-configuration
  • Production-ready features

Creating a Spring Boot Project

You can create a Spring Boot project using:

  1. Spring Initializr (https://start.spring.io/)
  2. Your IDE (IntelliJ IDEA, Eclipse, etc.)
  3. Spring Boot CLI

Example using Spring Boot CLI:

spring init --dependencies=web,data-jpa my-project
cd my-project

Spring Boot Annotations

Core Annotations

  • @SpringBootApplication: Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan
  • @Configuration: Indicates that a class declares one or more @Bean methods
  • @EnableAutoConfiguration: Enables Spring Boot's auto-configuration mechanism
  • @ComponentScan: Tells Spring to look for components in the current package and its sub-packages

Web Annotations

  • @Controller: Marks the class as a web controller
  • @RestController: Combines @Controller and @ResponseBody
  • @RequestMapping: Maps HTTP requests to handler methods
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Shortcut for @RequestMapping with a specific HTTP method

Example:

@RestController
@RequestMapping("/api")
public class UserController {
    @GetMapping("/users")
    public List<User> getAllUsers() {
        // Implementation
    }
}

Data Annotations

  • @Entity: Specifies that the class is an entity and is mapped to a database table
  • @Repository: Indicates that the class is a repository
  • @Service: Indicates that the class is a service
  • @Autowired: Marks a constructor, field, or setter method to be autowired by Spring's dependency injection

Example:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    // getters and setters
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    // methods
}

Spring Boot Configuration

Application Properties

Spring Boot uses application.properties or application.yml for configuration.

Example application.properties:

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password

Profiles

Profiles allow you to define environment-specific configurations.

Example:

# application-dev.properties
server.port=8080

# application-prod.properties
server.port=80

Activate a profile:

java -jar myapp.jar --spring.profiles.active=prod

Custom Configuration

You can create custom configuration classes:

@Configuration
public class MyConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

Spring Boot Data Access

JPA Repositories

Spring Data JPA simplifies data access layer implementation.

Example:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

Using Repositories

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public List<User> getUsersByLastName(String lastName) {
        return userRepository.findByLastName(lastName);
    }
}

Spring Boot Web

RESTful Web Services

Create RESTful APIs easily with Spring Boot.

Example:

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

Exception Handling

Use @ControllerAdvice for global exception handling:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<?> handleUserNotFoundException(UserNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }
}

Spring Boot Testing

Unit Testing

Use @SpringBootTest for integration tests:

@SpringBootTest
class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    void testCreateUser() {
        User user = new User("John Doe");
        User savedUser = userService.createUser(user);
        assertNotNull(savedUser.getId());
        assertEquals("John Doe", savedUser.getName());
    }
}

MockMvc for Controller Testing

Test your controllers using MockMvc:

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void testGetAllUsers() throws Exception {
        List<User> users = Arrays.asList(new User("John"), new User("Jane"));
        when(userService.getAllUsers()).thenReturn(users);

        mockMvc.perform(get("/api/users"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$", hasSize(2)))
               .andExpect(jsonPath("$[0].name", is("John")))
               .andExpect(jsonPath("$[1].name", is("Jane")));
    }
}

Spring Boot Actuator

Spring Boot Actuator provides production-ready features to help you monitor and manage your application.

Enable Actuator

Add the dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Endpoints

Some useful actuator endpoints:

  • /actuator/health: Shows application health information
  • /actuator/info: Displays arbitrary application info
  • /actuator/metrics: Shows metrics information
  • /actuator/env: Exposes properties from Spring's ConfigurableEnvironment

Custom Health Indicator

Create a custom health indicator:

@Component
public class CustomHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    private int check() {
        // Perform some specific health check
        return 0;
    }
}

Spring Boot Security

Basic Security Configuration

Add the security starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Configure basic authentication:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

Spring Boot Best Practices

  1. Use Spring Initializr to bootstrap your projects
  2. Follow a clear package structure (e.g., controller, service, repository, model)
  3. Use constructor injection over field injection
  4. Externalize configuration using properties files
  5. Use profiles for environment-specific configurations
  6. Write unit and integration tests
  7. Use Spring Boot Actuator for monitoring and metrics
  8. Implement proper exception handling
  9. Use DTOs (Data Transfer Objects) to decouple your API from your domain model
  10. Implement proper logging using SLF4J with Logback

Example of constructor injection:

@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    // Service methods
}

2024 © All rights reserved - buraxta.com