Spring Boot Annotations and Concepts

Spring Boot Annotations and Configuration

@SpringBootApplication

  • Marks the main class of a Spring Boot application.
  • Combines the following:
    • @Configuration: Contains @Bean definitions.
    • @EnableAutoConfiguration: Auto-configures beans based on classpath.
    • @ComponentScan: Scans specific packages for components.

@Autowired

  • Automatically injects dependencies by type.
    • Targets: Field, Constructor, Setter, or Method.
    • Use Case: When you want Spring to resolve and inject beans automatically.
  • Example:
  @Component  
  public class SomeService {
      @Autowired
      private AnotherService anotherService;
  }

@Component

  • Marks a class as a Spring-managed component (bean).
    • Use Case: Generic components to be autodetected by classpath scanning.
  • Example:
  @Component  
  public class UtilityService {
      public void performUtility() {
          // Some utility logic 
      }
  }

@ComponentScan

  • Tells Spring where to scan for components.
    • Use Case: Customize scanning beyond the default package.
  • Example:
  @ComponentScan(basePackages = "com.example.project")
  public class AppConfig {
      // Configuration code
  }

@Bean

  • Declares a bean explicitly within a @Configuration class.
    • Use Case: When a bean isn't autodetected or requires manual instantiation.
  • Example:
  @Configuration
  public class AppConfig {
      @Bean
      public Cache cache() {
          return new Cache();
      }
  }

@Service

  • Specialized @Component for the business logic layer.
    • Use Case: For classes that perform service-level logic.
  • Example:
  @Service
  public class PaymentService {
      public void charge() {
          // Charge logic
      }
  }

@Repository

  • Specialized @Component for persistence logic.
    • Use Case: Interact with the database and provide exception translation.
  • Example:
  @Repository
  public class UserRepository {
      public User findUser() {
          // Database access logic
      }
  }

@Configuration

  • Marks a class for bean definitions via @Bean methods.
    • Use Case: Java-based bean configuration instead of XML.
  • Example:
  @Configuration
  public class Config {
      @Bean
      public Cache cache() {
          return new Cache();
      }
  }

@EnableAutoConfiguration

  • Auto-configures Spring beans based on classpath.
    • Use Case: Reduces boilerplate in Spring Boot.
  • Example:
  @EnableAutoConfiguration
  public class AppStarter {
      public static void main(String[] args) {
          SpringApplication.run(AppStarter.class, args);
      }
  }

@Qualifier

  • Resolves ambiguity when multiple beans of the same type exist.
    • Use Case: Specify which bean to inject when multiple matches are found.
  • Example:
  @Autowired
  @Qualifier("specificBean")
  private Service service;

@Primary

  • Designates a default bean when multiple candidates exist.
    • Use Case: Preferred bean to inject unless overridden by @Qualifier.
  • Example:
  @Bean
  @Primary
  public Service defaultService() {
      return new Service();
  }

@DependsOn

  • Ensures one bean is initialized before another.
    • Use Case: When bean initialization order matters.
  • Example:
  @Bean
  @DependsOn("cacheInitializer")
  public Service service() {
      return new Service();
  }

@Profile

  • Loads a bean/configuration for a specific environment.
    • Use Case: Environment-based configurations (e.g., dev, prod).
  • Example:
  @Configuration
  @Profile("dev")
  public class DevConfig {
      // Development specific beans
  }

@Import

  • Imports other configuration classes.
    • Use Case: Modularizes configuration into separate files.
  • Example:
  @Configuration
  @Import({DbConfig.class, CacheConfig.class})
  public class AppConfig {
      // Configuration code
  }

@ImportResource

  • Imports XML configuration files.
    • Use Case: Integrate legacy Spring XML config.
  • Example:
  @ImportResource("classpath:legacy-config.xml")

@PropertySource

  • Loads properties from a file into Spring Environment.
    • Use Case: Externalizes configuration values.
  • Example:
  @PropertySource("classpath:app.properties")

Retention Policy in Java Annotations

  • Defines annotation lifespan:
    • SOURCE: Discarded during compile.
    • CLASS: Retained in .class file but not in memory.
    • RUNTIME: Retained for reflection during runtime.

ElementType in Java Annotations

  • Defines valid annotation targets: TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR, etc.

@RestController

  • Combines @Controller and @ResponseBody.
    • Use Case: Creates RESTful web services.
  • Example:
  @RestController
  public class MyController {
      @GetMapping
      public String greet() {
          return "Hello!";
      }
  }

@RequestMapping

  • Maps HTTP requests to handler methods.
    • Use Case: Create flexible route mappings for GET, POST, etc.
  • Example:
  @RequestMapping(value = "/users", method = RequestMethod.GET)
  public List<User> getUsers() {
      // Logic to get users
  }

@GetMapping

  • Shorthand for @RequestMapping(method = RequestMethod.GET).
    • Use Case: Read-only REST endpoints.
  • Example:
  @GetMapping("/users")
  public List<User> fetchUsers() {
      // Logic to fetch users
  }

@PostMapping

  • Handles HTTP POST requests.
    • Use Case: Create or submit resources.
  • Example:
  @PostMapping("/users")
  public void addUser(@RequestBody User user) {
      // Logic to add a user
  }

@PutMapping

  • Handles HTTP PUT requests.
    • Use Case: Update existing resources.
  • Example:
  @PutMapping("/users/{id}")
  public void updateUser(@PathVariable Long id, @RequestBody User user) {
      // Logic to update a user
  }

@DeleteMapping

  • Handles HTTP DELETE requests.
    • Use Case: Delete resources.
  • Example:
  @DeleteMapping("/users/{id}")
  public void deleteUser(@PathVariable Long id) {
      // Logic to delete a user
  }

@RequestParam

  • Binds request parameters to method arguments.
    • Use Case: Access query parameters.
  • Example:
  @GetMapping("/search")
  public String search(@RequestParam String keyword) {
      // Search logic
  }

@PathVariable

  • Extracts values from URI path.
    • Use Case: REST endpoints with dynamic values.
  • Example:
  @GetMapping("/users/{id}")
  public User getUser(@PathVariable Long id) {
      // Logic to get a user by ID
  }

@RequestBody

  • Maps request JSON to a Java object.
    • Use Case: Handle input for POST/PUT requests.
  • Example:
  @PostMapping("/register")
  public void register(@RequestBody User user) {
      // Logic to register a user
  }

@ResponseBody

  • Indicates return value is serialized to the response body.
    • Use Case: Used with @Controller to return data directly.
  • Example:
  @ResponseBody
  @GetMapping("/greet")
  public String greet() {
      return "Hello World!";
  }

SpringApplication.run()

  • Bootstraps and launches a Spring application.
    • Use Case: Entry point for running Spring Boot apps.
  • Example:
  public static void main(String[] args) {
      SpringApplication.run(App.class, args);
  }

application.properties

  • Configuration file for Spring Boot apps.
    • Use Case: Set properties like server.port, database config, etc.
  • Example:
  server.port=8081
  spring.datasource.url=jdbc:h2:mem:testdb

application.yml

  • Alternative to application.properties using YAML syntax.
    • Use Case: Hierarchical and cleaner config style.
  • Example:
  server:
    port: 8081

@Value

  • Injects property values from configuration files.
    • Use Case: Externalizes config into properties/yml.
  • Example:
  @Value("${app.name}")
  private String appName;

@ConfigurationProperties

  • Binds properties to a POJO.
    • Use Case: Organize and type-safe config mapping.
  • Example:
  @ConfigurationProperties(prefix="app")
  public class AppConfig {
      private String name;
  }

CommandLineRunner

  • Executes code after the app starts.
    • Use Case: Initial setup logic like seeding data.
  • Example:
  @Bean
  CommandLineRunner run() {
      return args -> System.out.println("App started!");
  }

Actuator

  • Provides production-ready features (metrics, health checks).
    • Use Case: Monitor and manage Spring Boot apps.
  • Example: Add dependency: spring-boot-starter-actuator

Spring DevTools

  • Offers live reload, auto-restart, and dev-friendly settings.
    • Use Case: Accelerate development feedback loop.
  • Example: Add dependency: spring-boot-devtools

Spring Boot Starter

  • A curated set of dependencies for specific functionality.
    • Use Case: Simplifies dependency management.
  • Example: spring-boot-starter-web, spring-boot-starter-data-jpa

Embedded Server in Spring Boot

  • Spring Boot apps run with an embedded server like Tomcat or Jetty.
    • Use Case: No need for external deployment.
    • Example: Built-in with spring-boot-starter-web

@Transactional

  • Declares that a method should run within a transaction.
    • Use Case: Rollback operations on exceptions to maintain data consistency.
  • Example:
  @Transactional
  public void updateAccount() {
      // Update logic
  }

@ControllerAdvice

  • Handles exceptions across the whole application globally.
    • Use Case: Centralized error handling logic.
  • Example:
  @ControllerAdvice
  public class GlobalExceptionHandler {
      @ExceptionHandler(Exception.class)
      public ResponseEntity<String> handleException(Exception ex) {
          return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
  }

Spring Security

  • Framework for authentication and authorization in Spring apps.
    • Use Case: Secure REST APIs, login, roles, permissions.
  • Example: Add dependency: spring-boot-starter-security

Spring Boot Test

  • Testing support for Spring Boot applications.
    • Use Case: Integration tests with embedded containers.
  • Example:
  @RunWith(SpringRunner.class)
  @SpringBootTest
  public class AppTests {
      // Tests
  }

MockMvc

  • Utility for testing Spring MVC controllers without starting a server.
    • Use Case: Unit test controller logic.
  • Example:
  mockMvc.perform(get("/api"))
      .andExpect(status().isOk());

TestRestTemplate

  • Helper class for integration testing RESTful services.
    • Use Case: Test full HTTP lifecycle.
  • Example:
  TestRestTemplate template = new TestRestTemplate();
  ResponseEntity<String> response = template.getForEntity("/api/resource", String.class);

Spring Boot Auto Configuration

  • Automatically configures beans based on classpath, properties, and environment.
    • Use Case: Simplifies configuration for common patterns.
  • How it works: Uses @ConditionalOnX annotations under the hood.

@ConditionalOnProperty

  • Conditionally loads beans based on the presence/value of a property.
    • Use Case: Enable/disable features using config flags.
  • Example:
  @Bean
  @ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
  public Feature feature() {
      return new Feature();
  }

@Conditional

  • Enables bean registration based on custom conditions.
    • Use Case: Register beans programmatically using custom logic.
  • Example: Implement Condition interface and return true/false from matches().

Spring Boot Profiles

  • Environment-specific configuration mechanism.
    • Use Case: Use different configs for dev, test, prod.
    • How: Set spring.profiles.active=dev in properties or VM args.

Spring Boot DevTools

  • Development support tools: auto-restart, livereload, H2 console, etc.
    • Use Case: Enhance developer productivity during iteration.

@RestTemplate

  • Client for performing REST calls.
    • Use Case: Call external services.
  • Example:
  RestTemplate template = new RestTemplate();
  String result = template.getForObject("https://api.example.com", String.class);

WebClient

  • Reactive, non-blocking alternative to RestTemplate.
    • Use Case: Async API calls in reactive applications.
  • Example:
  WebClient client = WebClient.create();
  client.get().uri("/api").retrieve().bodyToMono(String.class);

Health Indicators (Spring Actuator)

  • Custom or built-in checks for service health.
    • Use Case: Expose /actuator/health endpoint.
    • Example: Implement HealthIndicator to add a custom check.

Spring Boot Metrics

  • Track application metrics (e.g., memory, GC, custom counters).
    • Use Case: Performance monitoring with Micrometer + Actuator.
    • Example: /actuator/metrics/jvm.memory.used

Spring Boot Logging

  • Uses SLF4J with Logback by default.
    • Use Case: Customize logging levels, outputs.
    • Example: logging.level.root=DEBUG in application.properties

Spring Boot Caching

  • Enable method-level caching.
    • Use Case: Improve performance by caching expensive operations.
  • Example:
  @EnableCaching
  @Cacheable("users")
  public User getUser(Long id) {
      // Logic to get user
  }

Spring Data JPA

  • Abstraction over JPA for simplified database access.
    • Use Case: Declare interfaces for CRUD operations.
  • Example:
  public interface UserRepository extends JpaRepository<User, Long> {}

Spring Boot JPA Auditing

  • Track entity creation and modification timestamps.
    • Use Case: Auto-populate fields like createdAt, updatedAt.
  • Example:
  @EnableJpaAuditing
  @EntityListeners(AuditingEntityListener.class)

Flyway / Liquibase

  • Version control for database schema.
    • Use Case: Track, apply, and rollback DB migrations safely.
  • Example: Define SQL changesets in db/migration folder.