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 aDispatcherServlet
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.
Annotation | Description |
---|---|
@Component | A generic stereotype for any Spring-managed component. |
@Service | Indicates that a class holds business logic. |
@Repository | Marks a class as a Data Access Object (DAO). |
@Controller | Marks a class as a Spring MVC controller. |
@RestController | A convenience annotation that combines @Controller and @ResponseBody . |
Web and REST Annotations
Annotation | Description |
---|---|
@RequestMapping | Maps web requests to handler methods. Can be used at the class and method level. |
@GetMapping | Shortcut for @RequestMapping(method = RequestMethod.GET) . |
@PostMapping | Shortcut for @RequestMapping(method = RequestMethod.POST) . |
@PutMapping | Shortcut for @RequestMapping(method = RequestMethod.PUT) . |
@DeleteMapping | Shortcut for @RequestMapping(method = RequestMethod.DELETE) . |
@PathVariable | Binds a method parameter to a URI template variable. |
@RequestParam | Binds a method parameter to a web request parameter. |
@RequestBody | Binds the HTTP request body to a method parameter. |
Dependency Injection
Annotation | Description |
---|---|
@Autowired | Injects a bean automatically. Can be used on constructors, fields, or setter methods. |
@Qualifier | Used with @Autowired to resolve ambiguity when multiple beans of the same type exist. |
@Bean | Declares a bean within a @Configuration class. |
Configuration Annotations
Annotation | Description |
---|---|
@Value | Injects values from properties files into fields. |
@ConfigurationProperties | Binds a whole family of properties to a bean. |
@PropertySource | Specifies 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
Property | Description | Example |
---|---|---|
server.port | The port on which the embedded server will run. | server.port=8081 |
spring.application.name | The name of your application. | spring.application.name=my-app |
spring.datasource.url | The JDBC URL of the database. | spring.datasource.url=jdbc:mysql://localhost:3306/mydb |
spring.datasource.username | The username for the database connection. | spring.datasource.username=dbuser |
spring.datasource.password | The password for the database connection. | spring.datasource.password=dbpass |
spring.jpa.hibernate.ddl-auto | Specifies 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
Annotation | Description |
---|---|
@SpringBootTest | Loads the full application context for integration tests. |
@WebMvcTest | For testing the web layer (controllers). It auto-configures MockMvc . |
@DataJpaTest | For testing the JPA layer. It configures an in-memory database and scans for @Entity classes and Spring Data JPA repositories. |
@MockBean | Creates a Mockito mock for a specific bean and adds it to the application context. |
@ActiveProfiles | Sets 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.
Endpoint | Description |
---|---|
/actuator/health | Shows application health information. |
/actuator/info | Displays arbitrary application information. |
/actuator/metrics | Shows various metrics for the application. |
/actuator/env | Displays the current environment properties. |
/actuator/beans | Displays a complete list of all Spring beans in your application. |
/actuator/mappings | Displays a collated list of all @RequestMapping paths. |
/actuator/loggers | Shows 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=*