Monday, December 8, 2025

thumbnail

Spring Boot Annotations You Must Know

 Here’s a comprehensive guide to must-know Spring Boot annotations that every developer should be familiar with. I’ve grouped them by purpose to make it easier to understand and remember.


Spring Boot heavily relies on annotations to simplify configuration, enable auto-configuration, and reduce boilerplate code.


1️⃣ Core Spring Boot Annotations

@SpringBootApplication


The most important annotation in Spring Boot.


Combines three annotations:


@Configuration – marks the class as a source of bean definitions.


@EnableAutoConfiguration – enables Spring Boot’s auto-configuration mechanism.


@ComponentScan – enables scanning of components, services, and controllers.


Placed on the main class to bootstrap the application.


@SpringBootApplication

public class MyApplication {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);

    }

}


@EnableAutoConfiguration


Automatically configures Spring beans based on classpath dependencies and properties.


Usually used implicitly via @SpringBootApplication.


@ComponentScan


Tells Spring where to look for components (@Component, @Service, @Repository, @Controller).


Can specify base packages:


@ComponentScan(basePackages = "com.example.app")


2️⃣ Stereotype Annotations


Used to mark classes as Spring-managed beans.


Annotation Purpose

@Component Generic Spring bean

@Service Business/service layer bean

@Repository Data access layer, integrates with JPA

@Controller Spring MVC controller

@RestController Controller with @ResponseBody for REST

@RestController

public class UserController {

    @GetMapping("/users")

    public String getUsers() {

        return "List of users";

    }

}


3️⃣ Dependency Injection Annotations

Annotation Description

@Autowired Injects a bean automatically

@Qualifier Specifies which bean to inject when multiple exist

@Value Injects property values from application.properties

@Primary Marks a bean as primary when multiple beans of same type exist

@Service

public class UserService {

    @Autowired

    private UserRepository userRepository;


    @Value("${app.defaultRole}")

    private String defaultRole;

}


4️⃣ REST API Annotations

Annotation Usage

@RequestMapping Maps HTTP requests to handler methods

@GetMapping Shortcut for @RequestMapping(method = RequestMethod.GET)

@PostMapping Shortcut for POST requests

@PutMapping Shortcut for PUT requests

@DeleteMapping Shortcut for DELETE requests

@PathVariable Binds URL path variables to method parameters

@RequestParam Binds query parameters

@RequestBody Maps HTTP request body to a Java object

@ResponseBody Sends method return value as HTTP response (JSON/XML)

@RestController

@RequestMapping("/users")

public class UserController {


    @GetMapping("/{id}")

    public User getUser(@PathVariable("id") Long id) {

        return new User(id, "John Doe");

    }


    @PostMapping

    public User createUser(@RequestBody User user) {

        return user;

    }

}


5️⃣ Configuration Annotations

Annotation Usage

@Configuration Marks a class as a source of bean definitions

@Bean Declares a Spring bean

@PropertySource Specifies property files to load

@ConfigurationProperties Binds external properties to a POJO

@EnableConfigurationProperties Enables support for @ConfigurationProperties

@Configuration

@ConfigurationProperties(prefix = "app")

public class AppProperties {

    private String name;

    private String version;

    // getters and setters

}


6️⃣ Spring Boot Testing Annotations

Annotation Usage

@SpringBootTest Boots up the entire Spring context for integration testing

@WebMvcTest Loads only the web layer (controllers) for testing

@DataJpaTest Configures in-memory DB and JPA repositories for testing

@MockBean Replaces a bean with a Mockito mock in the Spring context

@TestConfiguration Provides test-specific bean configurations

@SpringBootTest

public class UserServiceTest {

    @Autowired

    private UserService userService;


    @Test

    public void testGetUser() {

        assertNotNull(userService.getAllUsers());

    }

}


7️⃣ Conditional and Profile Annotations

Annotation Usage

@Profile("dev") Loads bean only for the dev profile

@ConditionalOnProperty Load bean conditionally based on property

@ConditionalOnClass Load bean if a class exists on the classpath

@Service

@Profile("dev")

public class DevEmailService implements EmailService { }


8️⃣ Spring Boot Scheduling and Async Annotations

Annotation Usage

@EnableScheduling Enables scheduled tasks

@Scheduled Runs a method periodically or at fixed intervals

@EnableAsync Enables asynchronous execution

@Async Runs a method asynchronously

@Component

public class TaskScheduler {


    @Scheduled(fixedRate = 5000)

    public void runTask() {

        System.out.println("Task executed every 5 seconds");

    }

}


9️⃣ Spring Boot Miscellaneous Annotations


@Lazy – Initializes bean lazily (on first use)


@Scope – Defines bean scope (singleton, prototype)


@Primary – Marks a bean as the default choice when multiple beans of the same type exist


@Import – Imports additional configuration classes


๐Ÿ”‘ Summary


Here’s a quick cheat sheet of essential Spring Boot annotations:


Core Boot: @SpringBootApplication, @EnableAutoConfiguration, @ComponentScan


Bean & DI: @Component, @Service, @Repository, @Autowired, @Qualifier, @Value, @Primary


REST APIs: @RestController, @RequestMapping, @GetMapping, @PostMapping, @PathVariable, @RequestBody


Configuration: @Configuration, @Bean, @ConfigurationProperties


Testing: @SpringBootTest, @WebMvcTest, @DataJpaTest, @MockBean


Profiles/Conditionals: @Profile, @ConditionalOnProperty


Scheduling/Async: @EnableScheduling, @Scheduled, @EnableAsync, @Async

Learn Full Stack JAVA Course in Hyderabad

Read More

Dependency Injection in Spring Framework

Creating REST APIs using Spring Boot

Spring Boot vs Spring MVC – Key Differences

What is Spring Framework? An Overview

Visit Our Quality Thought Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive