Backend Development 17 min read

Comprehensive Guide to Spring Boot Annotations

This article provides a detailed overview of the most commonly used Spring Boot annotations, covering core, prototype, Spring Boot, Spring Cloud, caching, testing, database access, JPA, and global exception handling annotations, with clear explanations and practical Java code examples for each.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to Spring Boot Annotations

Spring Boot is a popular Java framework with a rich set of annotations. Before diving into Spring Boot annotations, it is useful to understand Spring's AOP (Aspect‑Oriented Programming) concept, which enables cross‑cutting concerns such as logging and performance monitoring through Aspect classes.

1. Core Annotations

@Configuration

The @Configuration annotation marks a class as a bean configuration class. Within it you can define beans using @Bean and inject other beans with @Autowired or @Value . Example:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

@Autowired

@Autowired automatically injects a bean into the current class. By default it matches by type; if multiple beans of the same type exist, @Qualifier can be used to specify which one.

@Component
public class MyController {
    private final MyService myService;

    @Autowired
    public MyController(MyService myService) {
        this.myService = myService;
    }
}

@Value

@Value injects values from configuration files or environment variables. Placeholders like ${my.property} refer to properties, while $(MY_ENV_VAR) refers to system environment variables.

@Component
public class MyComponent {
    @Value("${my.config.property}")
    private String configProperty;

    @Value("$MY_ENV_VAR")
    private String envVar;
}

@Bean

@Bean defines a bean that will be added to the Spring container, typically inside a class annotated with @Configuration . You can set the bean name, scope, and dependencies.

@Configuration
public class AppConfig {
    @Bean(name = "myService", scope = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MyService myService() {
        return new MyServiceImpl();
    }
}

@ComponentScan

@ComponentScan tells Spring to scan the specified packages for components (beans, controllers, etc.) and register them in the container.

@Configuration
@ComponentScan(basePackages = { "com.example" })
public class AppConfig {
}

@EnableAutoConfiguration

@EnableAutoConfiguration (included in @SpringBootApplication ) enables Spring Boot’s auto‑configuration mechanism, which attempts to configure the application based on classpath contents and property settings.

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

2. Prototype Annotations

@Scope

@Scope defines the bean’s lifecycle scope (e.g., singleton , prototype , request , session ). The default is singleton .

@Configuration
public class AppConfig {
    @Bean(name = "myService")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public MyService myService() {
        return new MyServiceImpl();
    }
}

@Lazy

@Lazy marks a bean for lazy initialization, meaning it will not be created until it is first needed.

@Configuration
public class AppConfig {
    @Bean(name = "myService")
    @Lazy
    public MyService myService() {
        return new MyServiceImpl();
    }
}

@DependsOn

@DependsOn expresses explicit bean dependencies, ensuring that the specified beans are created before the current bean.

@Configuration
public class AppConfig {
    @Bean(name = "myService")
    public MyService myService() {
        return new MyServiceImpl();
    }

    @Bean(name = "myController")
    @DependsOn("myService")
    public MyController myController() {
        return new MyController(myService());
    }
}

3. Spring Boot Annotations

@SpringBootApplication

This meta‑annotation combines @Configuration , @EnableAutoConfiguration , and @ComponentScan , marking the main class of a Spring Boot application.

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

@RestController

@RestController indicates that all methods in the class return JSON (or other response bodies) directly, combining @Controller and @ResponseBody .

@RestController
public class MyController {
    @GetMapping("/greeting")
    public String greeting() {
        return "Hello, world!";
    }
}

@RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

These annotations map HTTP requests to handler methods. @GetMapping is a shortcut for @RequestMapping(method = RequestMethod.GET) , and similarly for the others.

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/greeting")
    public String greeting() {
        return "Hello, world!";
    }

    @PostMapping("/greeting")
    public String createGreeting() {
        return "Created";
    }

    @PutMapping("/greeting")
    public String updateGreeting() {
        return "Updated";
    }

    @DeleteMapping("/greeting")
    public String deleteGreeting() {
        return "Deleted";
    }
}

@RequestParam

@RequestParam binds a request parameter to a method argument, allowing you to specify name, required flag, and default value.

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/greeting")
    public String greeting(@RequestParam("name") String name) {
        return "Hello, " + name + "!";
    }
}

@PathVariable

@PathVariable binds a URI template variable to a method parameter.

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/{name}")
    public String greeting(@PathVariable("name") String name) {
        return "Hello, " + name + "!";
    }
}

@RequestBody

@RequestBody reads the request body and converts it to a Java object, typically used with POST or PUT requests.

@RestController
@RequestMapping("/api")
public class MyController {
    @PostMapping("/greeting")
    public String greeting(@RequestBody GreetingRequest request) {
        return "Hello, " + request.getName() + "!";
    }
}

public class GreetingRequest {
    private String name;
    // getters and setters
}

@ResponseBody

Indicates that the method’s return value should be written directly to the HTTP response body.

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/greeting")
    @ResponseBody
    public String greeting() {
        return "Hello, world!";
    }
}

@ResponseStatus

Sets the HTTP status code for the response.

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/greeting")
    @ResponseStatus(HttpStatus.OK)
    public String greeting() {
        return "Hello, world!";
    }
}

@ExceptionHandler

Handles specific exceptions thrown by controller methods.

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResult handleIllegalArgumentException(IllegalArgumentException ex) {
        return new ErrorResult(ex.getMessage());
    }
}

public class ErrorResult {
    private String message;
    public ErrorResult(String message) { this.message = message; }
    // getters and setters
}

4. Spring Cloud Annotations

@EnableDiscoveryClient

Enables service discovery (e.g., with Eureka) so the application can register itself and discover other services.

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

@LoadBalanced

Marks a RestTemplate bean to enable client‑side load balancing.

@Configuration
public class AppConfig {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

@FeignClient

Defines a declarative HTTP client using Feign.

@FeignClient(name = "my-service")
public interface MyServiceClient {
    @GetMapping("/greeting")
    String greeting();
}

5. Caching Annotations

@Cacheable

Caches the result of a method; subsequent calls with the same arguments return the cached value.

@Service
public class MyService {
    @Cacheable("greetingCache")
    public String greeting(String name) {
        return "Hello, " + name + "!";
    }
}

@CachePut

Executes the method and updates the cache with the new result.

@Service
public class MyService {
    @CachePut("greetingCache")
    public String greeting(String name) {
        return "Hello, " + name + "!";
    }
}

@CacheEvict

Removes entries from the cache after method execution.

@Service
public class MyService {
    @CacheEvict("greetingCache")
    public void clearGreetingCache() {
    }
}

6. Testing Annotations

@SpringBootTest

Bootstraps the full Spring application context for integration tests.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyControllerTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testGreeting() {
        ResponseEntity
response = restTemplate.getForEntity("/api/greeting", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).isEqualTo("Hello, world!");
    }
}

@MockBean

Creates a Mockito mock of a bean and injects it into the Spring context.

@SpringBootTest
public class MyServiceTest {
    @Autowired
    private MyService myService;

    @MockBean
    private MyRepository myRepository;

    @Test
    public void testFindById() {
        Mockito.when(myRepository.findById(1L)).thenReturn(Optional.of(new MyEntity()));
        MyEntity entity = myService.findById(1L);
        assertThat(entity).isNotNull();
        Mockito.verify(myRepository).findById(1L);
    }
}

7. Database Access Annotations

@Transactional

Executes a method within a transaction; by default only unchecked exceptions trigger rollback.

@Service
public class MyService {
    @Autowired
    private MyRepository myRepository;

    @Transactional
    public void save(MyEntity entity) {
        myRepository.save(entity);
    }
}

@Repository

Marks a class as a data‑access component.

@Repository
public interface MyRepository extends JpaRepository
{
}

@Entity, @Table, @Id, @GeneratedValue, @Column

Standard JPA annotations to map a Java class to a database table and its columns.

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

    @Column(name = "name")
    private String name;
    // getters and setters
}

8. JPA Annotations

@EnableJpaRepositories

Enables Spring Data JPA repositories.

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

@Query

Defines a custom JPQL query for a repository method.

@Repository
public interface MyRepository extends JpaRepository
{
    @Query("select e from MyEntity e where e.name = :name")
    List
findByName(@Param("name") String name);
}

9. Global Exception Handling Annotations

@ControllerAdvice

Defines a class that handles exceptions across all controllers.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest request, Exception ex) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.addObject("url", request.getRequestURI());
        mav.setViewName("error");
        return mav;
    }
}

The article concludes that these are the most common Spring Boot annotations, and the author plans to enrich the content over time.

JavaBackend DevelopmentSpring BootAnnotationsSpring Framework
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.