PART TWO: The most common Spring Boot annotations that are used in microservice applications — Now with examples

Kambiz Z
5 min readMay 11, 2023

in my previous article, I talked about the most common Spring Boot annotations a bit and as I promised now we can see them in a code example. This is part two of the same educational content. Now without further due let’s get to it.

This is part two of the same serie; so don’t forget to start from the beginning:
link 1: introducing the common Annotations
link 2: Part One: Common Annotations in code examples

8. an example using the @Autowired annotation:

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

@Service
public class GreetingService {

private final GreetingRepository greetingRepository;

@Autowired
public GreetingService(GreetingRepository greetingRepository) {
this.greetingRepository = greetingRepository;
}

public String getGreeting() {
return greetingRepository.getGreeting();
}
}

In this example, we have a class called GreetingService that is marked with the @Service annotation. This annotation is used to indicate that the class is a Spring-managed service.

The GreetingService has a dependency on the GreetingRepository, which is passed to the constructor using dependency injection. The @Autowired annotation is used to tell Spring to inject an instance of the GreetingRepository into the constructor.

The getGreeting() method is a method in the GreetingService that returns a greeting string from the GreetingRepository.

With this @Autowired annotation, we can inject dependencies into our Spring-managed components like services, controllers, and repositories. Spring will automatically instantiate and inject the dependencies for us.

9. an example using the @GetMapping annotation:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

@GetMapping("/greeting")
public String getGreeting() {
return "Hello, World!";
}
}

In this example, we have a class called GreetingController that is marked with the @RestController annotation. This annotation is used to indicate that the class is a Spring-managed REST controller.

The @GetMapping("/greeting") annotation is used to map the /greeting URL to the getGreeting() method. When a GET request is sent to the /greeting URL, the getGreeting() method will be called, and it will return a greeting string.

With this @GetMapping annotation, we can map HTTP requests to methods in our Spring controllers. Spring will automatically handle the HTTP requests and responses, allowing us to build RESTful APIs quickly and easily.

10. an example using the @ExceptionHandler annotation:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ControllerAdvice
public class ExceptionHandlerControllerAdvice {

@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public String handleUserNotFoundException(UserNotFoundException ex) {
return ex.getMessage();
}
}

In this example, we have a class called ExceptionHandlerControllerAdvice that is marked with the @ControllerAdvice annotation. This annotation is used to indicate that the class contains global exception handling logic for all controllers.

The @ExceptionHandler(UserNotFoundException.class) annotation is used to specify that the handleUserNotFoundException() method will handle exceptions of type UserNotFoundException.

The @ResponseStatus(HttpStatus.NOT_FOUND) annotation is used to set the HTTP response status to 404 (Not Found) for this exception.

The @ResponseBody annotation is used to indicate that the return value of the method should be serialized to the response body.

The handleUserNotFoundException() method takes an instance of UserNotFoundException as its argument and returns the exception message as a string.

With this @ExceptionHandler annotation, we can handle exceptions in a centralized location in our Spring application. This makes it easier to manage and debug errors that occur during request processing.

11. an example using @Component annotation:

import org.springframework.stereotype.Component;

@Component
public class MyComponent {
public void doSomething() {
// do something
}
}

In this example, we have a class called MyComponent that is marked with the @Component annotation. This annotation is used to indicate that the class is a Spring-managed component.

MyComponent is a generic Spring component that does not fit into any other specialised annotations. It can be injected into other Spring-managed components like services, controllers, and repositories.

12. an example using @Configuration annotation:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class MyConfiguration {

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

In this example, we have a class called MyConfiguration that is marked with the @Configuration annotation. This annotation is used to indicate that the class is a configuration class.

MyConfiguration defines a Spring bean using Java-based configuration. The myBean() method is annotated with @Bean, indicating that it should be treated as a Spring bean. When the application context is created, the myBean() method will be called to create an instance of MyBean.

You are almost reaching the end of this article, don’t forget to continue to part one for this content (if you haven’t read it yet) which you can find the link down the page along with my other articles on the topics: Java, Microservices and Spring Boot.

13. an example using @EnableAutoConfiguration annotation:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;

@SpringBootApplication
public class MyApplication {

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

In this example, we have a class called MyApplication that is marked with the @SpringBootApplication annotation. This annotation is a composite annotation that includes @EnableAutoConfiguration.

@EnableAutoConfiguration is used to enable Spring Boot's auto-configuration mechanism. It automatically configures the application based on the classpath dependencies and other settings.

When MyApplication is run, Spring Boot will automatically configure the application based on the dependencies on the classpath and other settings.

14. an example using @Transactional annotation:

@Service
public class MyService {

@Autowired
private MyRepository repository;
@Transactional
public void saveData(MyEntity entity) {
repository.save(entity);
}
}

In this example, we have a MyService class that provides a saveData method to save a MyEntity object to the database. We have marked this method with the @Transactional annotation, which ensures that the method is executed within a database transaction. If an exception is thrown during the transaction, the transaction will be rolled back.

The @Transactional annotation can be applied to a class or to individual methods. When applied to a class, all public methods of the class are considered transactional. When applied to a method, only that method is considered transactional. In this example, we have applied the annotation to the saveData method only.

Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking.

If you’ve enjoyed this article so far, I would highly encourage you to follow me on Medium and don’t forget the clap.

leave some claps for me if you enjoyed the article :) that would be a good support for me.

Also as a follower, you’ll also have the opportunity to engage with me and other like-minded readers in the comments section. I’m always open to feedback and discussion, and I value the input of my followers greatly.

link to my other articles:
1. the most common Spring Boot annotations that are used in microservice applications
2. PART ONE: The most common Spring Boot annotations that are used in microservice applications — Now with examples
3. a simple Spring Boot application that uses MySQL and Rest endpoints
4. best practices to follow when developing REST APIs in a microservice application using Spring Boot

--

--

Kambiz Z

full-stack dev, tech enthusiast, and gadget lover. Passionate about new tools and tech, with experience in complex systems & web dev.