Comprehensive Guide to Spring Boot Annotations

Core Spring Boot Annotations

@SpringBootApplication

This is a meta-annotation that combines three essential annotations:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

The @ComponentScan directive enables Spring Boot to detect and register beans automatically. The following example demonstrates the typical application entry point:

package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Configuration

Equivalent to traditional XML configuration files. This annotation marks a class as a source of bean definitions, allowing type-safe configuration.

@EnableAutoConfiguration

Enables automatic configuration based on classpath dependencies. For instance, if HSQLDB exists on the classpath without manual database configuration, Spring Boot automatically configures an in-memory database.

@ComponentScan

Scans the specified package for components annotated with @Controller, @Service, @Repository, or @Component, automatically wiring them into the Spring container.

Web Layer Annotations

@RestController

Combines @Controller and @ResponseBody. Methods return values directly written to the HTTP response body, ideal for building RESTful APIs.

package com.example.api;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @RequestMapping("/status")
    public String checkStatus() {
        return "operational";
    }
}

@Controller

Marks a class as a web controller responsible for mapping URL requests to service layer methods.

@Controller
@RequestMapping("/demo")
public class DemoController {
    @Autowired
    private DemoService demoService;

    @RequestMapping("/welcome")
    public String welcomePage(Map<String, Object> model) {
        model.put("message", "Welcome to the application");
        return "welcome";
    }
}

@RequestMapping

Maps HTTP requests to controller methods. Supports multiple attributes:

@RequestMapping(
    value = "/resources/{id}",
    method = RequestMethod.GET,
    params = {"action=view"},
    headers = "X-Custom-Header=present"
)

@RequestParam

Binds request parameters to method arguments.

@RequestMapping("/search")
public String search(@RequestParam String query) {
    return "Searching for: " + query;
}

@PathVariable

Extracts variables from the URI template.

@RequestMapping("/users/{userId}/posts/{postId}")
public String getPost(
    @PathVariable String userId,
    @PathVariable String postId) {
    return "User: " + userId + ", Post: " + postId;
}

Dependency Injection Annotations

@Autowired

Automatically injects required dependencies by type.

@Autowired
private UserRepository userRepository;

@Qualifier

Resolves ambiguity when multiple beans of the same type exist.

@Autowired
@Qualifier("premiumUserService")
private UserService userService;

@Resource

Injects by name, similar to @Autowired with @Qualifier.

@Resource(name = "cacheManager")
private CacheManager cacheManager;

@Inject

Equivalent to @Autowired without the required attribute.

@Value

Injects values from properties files.

@Value("#{appConfig.timeout}")
private int connectionTimeout;

Component Annotations

@Component

Generic stereotype for any Spring-managed component.

@Service

Specialized for service layer components.

@Repository

Specialized for data access layer components, providing exception translation for persistence exceptions.

Bean Configuration Annotations

@Bean

Declares a method as a bean producer, equivalent to <bean> in XML.

@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        return new HikariDataSource();
    }
}

@Import

Imports additional configuration classes.

@ImportResource

Loads XML configuration files into the application context.

JPA Annotations

@Entity and @Table

Mark classes as JPA entities. @Table specifies the database table name.

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
}

@MappedSuperclass

Indicates a base class whose properties are inherited by child entities. Such classes are not mapped to their own database tables.

@Id and @GeneratedValue

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
private Long id;

@SequenceGenerator(name = "user_seq", sequenceName = "seq_users", allocationSize = 1)

@Column

Maps entity fields to database columns with various attributes:

@Column(
    name = "email_address",
    nullable = false,
    length = 255,
    unique = true
)
private String email;

@Transient

Excludes a field from database mapping.

@JsonIgnore

Prevents serialization/deserialization of a field in JSON.

@JoinColumn

Specifies the foreign key column for relationships.

Relationship Annotations

  • @OneToOne
  • @OneToMany
  • @ManyToOne
  • @ManyToMany

Lifecycle Callbacks

Entity Lifecycle Events

Annotation Trigger
@PrePersist Before entity insertion
@PostPersist After entity insertion
@PreUpdate Before entity update
@PostUpdate After entity update
@PreRemove Before entity deletion
@PostRemove After entity deletion
@PostLoad After entity loading
@PrePersist
protected void onCreate() {
    this.createdAt = Instant.now();
}

@PreUpdate
protected void onUpdate() {
    this.updatedAt = Instant.now();
}

Exception Handling

@ControllerAdvice

Global exception handler for all controllers.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse(ex.getMessage()));
    }
}

Lombok Annotations

@Data

Generates getters, setters, equals, hashCode, and toString for all fields.

@Getter and @Setter

Generate accessor methods for individual fields.

@NoArgsConstructor and @AllArgsConstructor

Generate constructors with zero or all parameters respectively.

@Builder

Enables the builder pattern for object construction.

@Slf4j

Creates a logger instance named log.

@NonNull

Adds null-checking to setter methods and constructors.

@Data
@Builder
public class Product {
    @NonNull
    private String name;
    
    private BigDecimal price;
    
    private String description;
}

Configuration Class Example

@Configuration
@ComponentScan(basePackages = "com.example.services")
public class ApplicationConfiguration {
    public ApplicationConfiguration() {
        System.out.println("Container initialized");
    }

    @Bean
    @Scope("prototype")
    public NotificationService notificationService() {
        return new EmailNotificationService();
    }
}

Using the configuration:

public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = 
            new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
        
        NotificationService service = ctx.getBean(NotificationService.class);
        service.send("Hello World");
    }
}

Benefits of Java-Based Configuration

  1. Type safety with compile-time checking
  2. Object-oriented design in configuration
  3. Improved refactoring support
  4. Elimination of verbose XML files
  5. Full access to Spring IoC container features

Tags: spring-boot annotations java spring-framework jpa

Posted on Thu, 07 May 2026 15:11:35 +0000 by gere06