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

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If ...

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; Str...

JAVA 8 FUNTIONAL INTERFACE

JAVA 8 FUNTIONAL INTERFACE  Funtional Interface :     An interface which has only one abstract method can be called a funtional interface. Comparable , Runnable , Callable all these interfaces has only one abstract method and can be consider as funtional interface.    How it works :        Once we will create a interface with one abstract method then java internally predicates the input type and based on the Interface reference it apply the logic mentioned after lambda expression    lets consider we have created an interface as below @FunctionalInterface public interface FuntionalExample { public int cal ( int a , int b) ; } And below class to test our funtional Interface. public class FuntionalInterfaceExample { public static void main (String args[]) { FuntionalExample addition=( int a , int b) -> a+b ; FuntionalExample subtraction=( int a , int b) -> a-b ; FuntionalExample multipl...