Skip to main content

Spring boot annotation

 A Spring Boot application consists of several key annotations that configure components, enable auto-configuration, and manage dependency injection. Below is a comprehensive list of Spring Boot annotations categorized by their purpose.

1. Core Annotations (Bootstrapping & Configuration)

Annotation

Description

@SpringBootApplication

Main entry point for a Spring Boot application. Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.

@Configuration

Marks a class as a Spring configuration class (equivalent to XML config).

@ComponentScan

Enables scanning for components (@Component, @Service, @Repository, etc.) in the package and sub-packages.

@EnableAutoConfiguration

Automatically configures Spring beans based on dependencies. (Part of @SpringBootApplication).

Example

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class MySpringBootApp {

    public static void main(String[] args) {

        SpringApplication.run(MySpringBootApp.class, args);

    }

}

2. Component Scanning & Stereotypes

Annotation

Description

@Component

Generic annotation for Spring-managed beans.

@Service

Specialized @Component for business logic/service layer.

@Repository

Specialized @Component for data persistence (adds exception translation).

@Controller

Specialized @Component for Spring MVC controllers.

@RestController

Combination of @Controller and @ResponseBody, returning JSON/XML responses.

Example

import org.springframework.stereotype.Service;


@Service

public class MyService {

    public String getMessage() {

        return "Hello from MyService!";

    }

}

3. Dependency Injection (DI)

Annotation

Description

@Autowired

Injects dependencies automatically by type.

@Qualifier

Specifies which bean to inject when multiple candidates exist.

@Primary

Marks a bean as the default when multiple beans of the same type exist.

@Bean

Defines a Spring-managed bean inside a @Configuration class.

Example: Dependency Injection

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


@Component

public class MyController {

    private final MyService myService;


    @Autowired  // Injecting MyService bean

    public MyController(MyService myService) {

        this.myService = myService;

    }

}

4. Bean Scope Management

Annotation

Description

@Scope("singleton")

Default scope; only one instance is created.

@Scope("prototype")

A new instance is created for every request.

@Scope("request")

A new bean instance per HTTP request (for web apps).

@Scope("session")

A new bean per HTTP session (for web apps).

Example

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Service;


@Service

@Scope("prototype")  // A new instance each time it is requested

public class PrototypeService { }

5. Spring MVC & REST API Annotations

Annotation

Description

@RequestMapping

Maps HTTP requests to handler methods.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

Specialized versions of @RequestMapping for specific HTTP methods.

@RequestBody

Maps JSON/XML request body to a Java object.

@ResponseBody

Directly returns data (JSON/XML) instead of a view.

@PathVariable

Extracts values from the URL path.

@RequestParam

Extracts query parameters from a request.

Example

import org.springframework.web.bind.annotation.*;


@RestController

@RequestMapping("/api")

public class MyRestController {


    @GetMapping("/hello/{name}")

    public String sayHello(@PathVariable String name) {

        return "Hello, " + name;

    }

}

6. Exception Handling

Annotation

Description

@ExceptionHandler

Handles exceptions at the controller level.

@RestControllerAdvice

Global exception handling for all controllers.

@ResponseStatus

Specifies the HTTP status for an exception.

Example

import org.springframework.web.bind.annotation.*;


@RestControllerAdvice

public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)

    public String handleException(Exception ex) {

        return "Error: " + ex.getMessage();

    }

}

7. Transaction Management

Annotation

Description

@Transactional

Marks a method or class as transactional (commits or rolls back transactions).

Example

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


@Service

public class TransactionalService {


    @Transactional

    public void performTransaction() {

        // Database operations here

    }

}

8. Caching

Annotation

Description

@EnableCaching

Enables Spring’s caching mechanism.

@Cacheable

Caches method results to improve performance.

@CacheEvict

Removes an entry from the cache.

Example

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;


@Service

public class CacheService {


    @Cacheable("items")

    public String getData(String key) {

        return "Data for " + key;

    }

}

9. Spring Security Annotations

Annotation

Description

@EnableWebSecurity

Enables Spring Security.

@Secured

Restricts access based on roles.

@PreAuthorize

More advanced access control before method execution.

Example

import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.stereotype.Service;


@Service

public class SecureService {


    @PreAuthorize("hasRole('ADMIN')")

    public String adminAccess() {

        return "Admin Only";

    }

}

10. Spring Boot Actuator Annotations

Annotation

Description

@EnableAutoConfiguration

Enables Spring Boot’s auto-configuration features.

@ConditionalOnProperty

Enables a bean based on a property in application.properties.

@ConditionalOnClass

Enables a bean if a specific class is present in the classpath.

Example

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import org.springframework.stereotype.Component;


@Component

@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")

public class FeatureBean { }

Conclusion


These are the most commonly used annotations in Spring Boot, covering configuration, dependency injection, REST APIs, transactions, security, caching, and more.

Comments

Popular posts from this blog

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Selection sort Implementation

  Selection sort  : In selection sort we will divide the Array in 2 parts , sorted and unsorted and select the min element from unsorted and will copy to sorted array.      Time Complexity for selection sort also is O(n^2).      space complexity for bubble sort will be O(1). class SelectionSort { public static void sort ( int [] array) { int n = array. length ; for ( int i = 0 ; i < n - 1 ; i++) { int min = i ; for ( int j = i + 1 ; j < n ; j++) { if (array[j] < array[min]) { min = j ; } } swap (array , i , min) ; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ; array[i] = array[j] ; array[j] = temp ; } private static void print ( int [] array) { System. out .print( "[" ) ; for ( int i = 0 ; i < array. lengt...