Spring Boot Core Annotations and Their Practical Applications
This class-level annotation enables global exception handling across multiple controllers. When combined with @ExceptionHandler, it centralizes error response logic. The annotations attribute restricts its scope to controllers annotated with specific stereotypes like @RestController or @Controller.
@ResponseBody
@ControllerAdvice(annotations = { RestController.class, Controller.class })
@Slf4j
public class GlobalErrorResponder {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handleIntegrityViolation(SQLIntegrityConstraintViolationException ex) {
log.error("Database constraint violation: {}", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResponse("Data integrity error"));
}
}
@ResponseBody
When applied at the class or method level, this annotation instructs Spring to serialize the return value directly into the HTTP response body, typically as JSON or XML. It is commonly used in RESTful services to avoid view resolution.
@ExceptionHandler
Used on methods within a @ControllerAdvice or controller class, this annotation designates a method as a handler for specific exception types. The value attribute accepts one or more exception classes to intercept.
@Configuration
Designates a class as a Java-based configuration source, equivalent to XML configuration files. Such classes typically declare @Bean components and enable Spring to manage their lifecycle.
@Configuration
@MapperScan("com.example.mapper")
public class DataConfig {
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@Bean
Declares a method that returns an object to be registered as a Spring bean in the application context. The method’s return type defines the bean type, and its name becomes the default bean ID.
@PostConstruct
Indicates that the annotated method should be invoked immediately after dependency injection is completed and before the bean is put in to service. Useful for initialization logic requiring injected dependencies.
@SpringBootApplication
A composite annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It is placed on the main application class to trigger auto-configuration and component scanning.
@Slf4j
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
log.info("Application started successfully");
}
}
@RequestHeader
Binds the value of an HTTP request header to a method parameter. The value attribute specifies the header name, and required determines whether the header must be present.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id,
@RequestHeader(value = "X-Auth-Token", required = false) String token) {
// ...
}
@PathVariable
Extracts values from URI template variables. Used in REST endpoints where dynamic segments (e.g., /users/{userId}) are part of the route.
@GetMapping("/products/{productId}")
public Product getProduct(@PathVariable("productId") Long id) {
return productService.findById(id);
}
@RestController
Combines @Controller and @ResponseBody, signaling that all method in the class return data directly rather than views. Ideal for REST API controllers.
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping
Specialized variants of @RequestMapping for HTTP methods. Each simplifies mapping by eliminating the need to specify the method attribute explicitly.
@RestController
@RequestMapping("/api/books")
public class BookController {
@GetMapping("/{id}")
public Book getBook(@PathVariable Long id) { ... }
@PostMapping
public Book createBook(@RequestBody Book book) { ... }
}
@Value
Injects property values from external configuration files (e.g., application.yml). Supports placeholders like ${property.name} and default values via ${property.name:default}.
@Value("${app.timeout:5000}")
private int connectionTimeout;
@ConfigurationProperties
Binds a group of related properties from the configuration file to a POJO. Requires a prefix that matches the configuration hierarchy. Must be used with @Component or declared as a @Bean.
@Component
@Data
@ConfigurationProperties(prefix = "app.database")
public class DatabaseSettings {
private String url;
private String username;
private int poolSize;
}
@RefreshScope
Enables runtime reloading of bean properties when configuration changes, typically used in Spring Cloud environments with config servers. Only affects beans annotated with this directive.
@RestController
@RefreshScope
public class ConfigController {
@Value("${app.format}")
private String timestampFormat;
@GetMapping("/time")
public String getCurrentTime() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(timestampFormat));
}
}
@TableName
Maps a MyBatis-Plus entity class to a specific database table. Overrides the default naming convention (camelCase to snake_case).
@TableName("user_accounts")
public class User {
private Long id;
private String name;
// getters and setters
}
@TableId
Designates a field as the primary key. The type attribute defines the ID generation strategy: AUTO (database auto-increment), ASSIGN_ID (Snowflake algorithm), or others.
@TableId(type = IdType.ASSIGN_ID, value = "user_id")
private Long userId;
@TableField
Maps a class field to a specific database column. Useful when field names differ from column names or when excluding fields from queries.
@TableField(value = "pwd", select = false)
private String password; // Excluded from SELECT queries
@TableLogic
Enables logical deletion by marking a field as a soft-delete flag. Instead of physical deletion, the field is updated to a designated value (e.g., 1), and queries automatically filter out soft-deleted records.
@TableLogic
private Integer deleted;
@MapperScan
Specifies the package(s) containing MyBatis mapper interfaces, enabling Spring to auto-register them as beans without individual @Mapper annotations.
@Slf4j
Generates a log field using SLF4J, eliminating boilerplate code. Requires Lombok to be configured in the build tool.
@LoadBalanced
Applied to a RestTemplate bean to enable client-side load balancing via Spring Cloud LoadBalancer or Netflix Ribbon.
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@FeignClient
Declares an interface as a declarative HTTP client for remote service invocation using OpenFeign. The value attribute specifies the target service name registered in the service registry.
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/api/users/{id}")
User findById(@PathVariable("id") Long id);
}
@EnableFeignClients
Activates Feign client scanning. Can optionally define base packages or specific client classes to avoid scanning all components.
@SpringBootApplication
@EnableFeignClients(clients = {UserClient.class})
public class OrderServiceApplication { ... }
@Order
Defines the execution order of components like filters, interceptors, or listeners. Lower values execute first. Can also be implemented via the Ordered interface.
@Component
@Order(-1)
public class AuthenticationFilter implements GlobalFilter {
// Executes before other filters
}
@EnableGlobalMethodSecurity
Enables method-level security annotations such as @PreAuthorize, @PostAuthorize, and others. Requires Spring Security on the classpath.
@PreAuthorize
Restricts method access based on SpEL (Spring Expression Language) expressions evaluated before invocation. Commonly used for role or permission checks.
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('MODERATOR')")
@GetMapping("/admin/dashboard")
public String getAdminDashboard() {
return "admin-panel";
}
@SpringBootTest
Configures a test context for integration testing with Spring Boot. Automatically loads the main application configuration unless overridden via the classes attribute.
@SpringBootTest(classes = Application.class)
@ExtendWith(SpringExtension.class)
class UserRepositoryTest {
@Autowired
private UserRepository repository;
@Test
void shouldFindUserById() {
User user = repository.findById(1L).orElse(null);
assertNotNull(user);
}
}