Spring Boot Annotations

Himani Prasad
5 min readMay 17, 2023

--

Photo by Gil Ribeiro on Unsplash

Spring Boot is a framework that makes Java development easier. It uses special codes called annotations to simplify the process of building applications. These annotations help reduce repetitive code and allow developers to focus on writing the important parts of their programs.

1. @Autowired

The famous @Autowired annotation!

It automatically wires beans by type. This means that Spring will look for a bean of the same type as the field, constructor, or method parameter marked with @Autowired, and inject it for you.

You don’t have to write any manual wiring code or worry about creating objects yourself.

One thing to keep in mind is that if there are multiple beans of the same type, Spring will get confused and throw an exception. To avoid this, you can use the @Qualifier annotation to specify which bean you want to use.

2. @Qualifier

To use @Qualifier, you first need to give a name to your beans using the @Component or @Service annotations. Then, in your code, you can annotate with @Autowired and @Qualifier, specifying the name of the bean you want to use.

@Component("myBean")
public class MyBean {
// some code
}
@Service
public class MyService {
@Autowired
@Qualifier("myBean")
private MyBean myBean;

}

3. @Value

@Value is a powerful annotation used to inject values from various sources into your beans. These sources include properties files, environment variables, and command line arguments.

For example, let’s say you have a properties file named “application.properties” with the following content:

myapp.username=John
myapp.password=secret

You can use @Value to inject these values into your beans:

@Service
public class MyService {
@Value("${myapp.username}")
private String username;
@Value("${myapp.password}")
private String password;

}

4. @ResponseBody

In a Spring MVC application, when a controller method is invoked, it typically processes the request, performs necessary operations or logic, and then returns the name of the view that should be rendered. The view resolution process kicks in to locate the appropriate view template based on the returned view name.

By annotating a method with @ResponseBody, you instruct Spring to bypass the view resolution process and write the method's return value directly to the HTTP response body.

Meaning, if you have a method in your controller that returns a value, but instead of rendering it through a view template or HTML page, you want to send it directly as the response body. That’s where the marvelous @ResponseBody

@Controller
public class MyController {
@GetMapping("/data")
@ResponseBody
public String getData() {
return "This is raw data.";
}
}

5. @Component

By becoming a @Component, your class becomes a Spring-managed bean, meaning Spring Boot takes care of creating and managing instances of that class within the application context. You can then inject and use this bean in other parts of your application by using @Autowired or other dependency injection mechanisms.

Here’s a simple example to illustrate the magic of @Component:

@Component
public class ComponentDemo {
public void doSomething() {
// code
}
}
@Service
public class MyService {
@Autowired
private ComponentDemo component;
public void performAction() {
component.doSomething();
}
}

@Component annotation is the base annotation for other specialized annotations in Spring, such as @Service, @Repository, and @Controller. These specialized annotations provide additional semantics and functionality tailored to specific use cases.

6. @Controller

When you annotate a class with @Controller, you're telling Spring Boot that this class will be responsible for handling web requests. It serves as the entry point for the request-response flow. You can then use method-level annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to specify the type of HTTP request that the methods in your controller will handle.

@Controller
@RequestMapping("/users")
public class UserController {

@GetMapping("/{id}")
public UsergetUser(@PathVariable Long id, Model model) {
// Retrieve user from database and add it to the model
User user = userService.getUserById(id);
return user;
}
}

7. @RestController

@RestController = @Controller + @ResponseBody

@RestController handles requests and effortlessly produces the response as-is, without the need for any view templates.

Let’s jump into an example to see @RestController in action:

@RestController
@RequestMapping("/api")
public class SuperheroController {
@GetMapping("/heroes")
public List<Superhero> getAllHeroes() {
// Retrieve all superheroes from the database
List<Superhero> heroes = superheroService.getAllHeroes();
return heroes;
}
}

8. @Service

Services encapsulate the business logic of your application and are responsible for performing specific tasks and coordinating actions between different components.

@Service
public class UserService {

@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id);
}
}

9. @RequestBody

It is used to bind the request body of an HTTP request to a method parameter or an object.

When a client sends an HTTP request, they can include data in the request body, like JSON or XML information. By using @RequestBody, you can automatically extract and use that data.

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
userService.createUser(user);
return ResponseEntity.ok(user);
}
@Data
public class User {
private String name;
private String email;
}

When a client sends an HTTP POST request to the “/users” endpoint with a JSON body like this:

{
"name": "John Doe",
"email": "johndoe@example.com"
}

Spring will automatically deserialize the JSON and bind it to a User object.

10. @PathVariable

The @PathVariable annotation in Spring allows you to extract values from the URL and use them in your code. It's like picking up a specific part of the URL and using it as a variable.

For example, let’s say you have a URL like “/user/123”, where “123” is a dynamic value representing a user ID. With @PathVariable, you can capture that "123" and use it in your method.

@GetMapping("/user/{id}")
public ResponseEntity<User> getUserById(@PathVariable("id") Long userId) {
User user = userService.getUserById(userId);
return ResponseEntity.ok(user);
}

11. @RequestParam

When a client sends an HTTP request, they can include extra information in the URL called query parameters. These parameters appear after a question mark (?) in the URL and are typically in the form of key-value pairs.

Ex: in the URL “/users?id=123”, the query parameter is “id” with a value of “123”.

By using @RequestParam, you can retrieve the value of a specific query parameter and use it in your code.

@GetMapping("/user")
public ResponseEntity<User> getUserById(@RequestParam("id") Long userId) {
User user = userService.getUserById(userId);
return ResponseEntity.ok(user);
}

12. @Bean

@Bean annotation in Spring is used to declare a bean. It is similar to the <bean/> element in XML configuration. By annotating a method with @Bean, you can define a bean and register it in the Spring application context.

It indicates that a method produces a bean to be managed by the Spring container. It is typically used within a class annotated with @Configuration or @Component

@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}

13. @Configuration

The @Configuration annotation in Spring is used to indicate that a class provides configuration for the application context. It is typically used in conjunction with other annotations like @Bean to define beans and configure various aspects of the Spring application.

14. @ControllerAdvice

When you annotate a class with @ControllerAdvice, it becomes a global exception handler. It can contain exception handling methods that will be invoked when exceptions are thrown from controller methods. It allows you to centralize exception handling logic and apply it uniformly across different controllers.

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
// Exception handling logic
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

15. @ExceptionHandler

When an exception occurs within a controller method, the @ExceptionHandler-annotated method is invoked to handle that specific exception.

--

--