Spring Boot Cheat Sheet: Essential Concepts and Annotations

Spring Boot Cheat Sheet: Essential Concepts

This cheat sheet provides a concise reference of key concepts and annotations in the Spring Boot framework, designed for quick reference during development.


Core Concepts

  • Starters: Convenient dependency descriptors that simplify your Maven or Gradle configuration. By including a starter, you get a curated set of dependencies needed for a specific functionality.
    • spring-boot-starter-web: For building web applications, including RESTful APIs, using Spring MVC and an embedded Tomcat server.
    • spring-boot-starter-data-jpa: For working with databases using the Java Persistence API (JPA) with Hibernate.
    • spring-boot-starter-test: Provides essential libraries for testing, including JUnit, Hamcrest, and Mockito.
    • spring-boot-starter-actuator: Adds production-ready features like monitoring and metrics.
    • spring-boot-starter-security: For enabling security features in your application.
  • Autoconfiguration: Spring Boot’s mechanism to automatically configure your application based on the JAR dependencies you have added. For example, if spring-boot-starter-web is on the classpath, Spring Boot will automatically configure a DispatcherServlet and other web-related components.
  • @SpringBootApplication: A convenience annotation that combines three other annotations:
    • @Configuration: Tags the class as a source of bean definitions for the application context.
    • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
    • @ComponentScan: Tells Spring to look for other components, configurations, and services in the specified package, allowing it to find and register your controllers and other components.

Essential Annotations

Stereotype Annotations

These annotations define the roles of your classes.

AnnotationDescription
@ComponentA generic stereotype for any Spring-managed component.
@ServiceIndicates that a class holds business logic.
@RepositoryMarks a class as a Data Access Object (DAO).
@ControllerMarks a class as a Spring MVC controller.
@RestControllerA convenience annotation that combines @Controller and @ResponseBody.

Web and REST Annotations

AnnotationDescription
@RequestMappingMaps web requests to handler methods. Can be used at the class and method level.
@GetMappingShortcut for @RequestMapping(method = RequestMethod.GET).
@PostMappingShortcut for @RequestMapping(method = RequestMethod.POST).
@PutMappingShortcut for @RequestMapping(method = RequestMethod.PUT).
@DeleteMappingShortcut for @RequestMapping(method = RequestMethod.DELETE).
@PathVariableBinds a method parameter to a URI template variable.
@RequestParamBinds a method parameter to a web request parameter.
@RequestBodyBinds the HTTP request body to a method parameter.

Dependency Injection

AnnotationDescription
@AutowiredInjects a bean automatically. Can be used on constructors, fields, or setter methods.
@QualifierUsed with @Autowired to resolve ambiguity when multiple beans of the same type exist.
@BeanDeclares a bean within a @Configuration class.

Configuration Annotations

AnnotationDescription
@ValueInjects values from properties files into fields.
@ConfigurationPropertiesBinds a whole family of properties to a bean.
@PropertySourceSpecifies the location of a properties file.

Configuration Files: application.properties and YAML

These files, located in src/main/resources, are used for configuring your Spring Boot application. YAML (.yml) is often preferred for its hierarchical and more readable structure.

Common Configuration Properties

PropertyDescriptionExample
server.portThe port on which the embedded server will run.server.port=8081
spring.application.nameThe name of your application.spring.application.name=my-app
spring.datasource.urlThe JDBC URL of the database.spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.usernameThe username for the database connection.spring.datasource.username=dbuser
spring.datasource.passwordThe password for the database connection.spring.datasource.password=dbpass
spring.jpa.hibernate.ddl-autoSpecifies the database schema generation strategy. Common values are none, validate, update, create, and create-drop.spring.jpa.hibernate.ddl-auto=update
logging.level.<logger-name>Sets the logging level for a specific logger.logging.level.org.springframework.web=DEBUG

Testing Spring Boot Applications

Spring Boot provides a robust testing framework. The spring-boot-starter-test includes everything you need for unit and integration testing.

Key Annotations for Testing

AnnotationDescription
@SpringBootTestLoads the full application context for integration tests.
@WebMvcTestFor testing the web layer (controllers). It auto-configures MockMvc.
@DataJpaTestFor testing the JPA layer. It configures an in-memory database and scans for @Entity classes and Spring Data JPA repositories.
@MockBeanCreates a Mockito mock for a specific bean and adds it to the application context.
@ActiveProfilesSets the active Spring profiles for a test class.

Example with MockMvc

Java Code Example:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MyService myService;

    @Test
    public void testGetHello() throws Exception {
        when(myService.getGreeting()).thenReturn("Hello, Mock");

        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello, Mock"));
    }
}

Spring Boot Actuator

Actuator brings production-ready features to your application. To use it, add the spring-boot-starter-actuator dependency.

Common Actuator Endpoints

By default, Actuator endpoints are exposed under the /actuator path.

EndpointDescription
/actuator/healthShows application health information.
/actuator/infoDisplays arbitrary application information.
/actuator/metricsShows various metrics for the application.
/actuator/envDisplays the current environment properties.
/actuator/beansDisplays a complete list of all Spring beans in your application.
/actuator/mappingsDisplays a collated list of all @RequestMapping paths.
/actuator/loggersShows and modifies the configuration of loggers in the application.
Exposing Actuator Endpoints

To expose all endpoints over HTTP (use with caution in production), add the following to your application.properties:

management.endpoints.web.exposure.include=*