Spring Boot Annotations

Spring Boot Annotations

Spring Boot annotations are like labels or tags that give extra information to a Spring application. They help set up and configure the application without needing a lot of manual work. Built on top of the Spring Framework, Spring Boot simplifies the development process by reducing the need for extensive configuration. It has gained immense popularity among developers for its ability to create production-ready applications quickly, enabling a focus on application logic rather than setup complexities.

Spring Boot supports microservice architecture, making it ideal for developing modern, scalable applications. With its pre-configured environment and embedded server options, Spring Boot accelerates deployment and enhances productivity.

Key Features of Spring Boot:

  • Automatically handles configuration, so you don’t need to write XML files.
  • Makes it easy to create and manage REST APIs.
  • Comes with a built-in Tomcat server for quick and simple development.
  • Allows easy deployment of .war and .jar files.
Spring Boot Annotations

Understanding Annotations

Annotations in Spring Boot are used to supply additional details about a program. While they do not alter the behavior of the compiled code, annotations play a crucial role in configuring and organizing the application.

In this guide, we’ll explore some of the key annotations used in Spring Boot. These annotations, found in the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.condition packages, are essential for building efficient and well-structured applications.

Spring Boot annotations simplify the development process, making it easier to design scalable and maintainable applications without manual configuration. Let’s dive into their usage with examples.

Spring Boot Specific Annotations

-> @SpringBootApplication Annotation

The @SpringBootApplication annotation is a shortcut in Spring Boot that combines three important annotations:

  • @Configuration: Marks the class as a configuration file for Spring beans.
  • @EnableAutoConfiguration: Automatically sets up the application based on the dependencies in your project.
  • @ComponentScan: Scans the package for Spring components like @Controller, @Service, and @Repository.
SpringBootApplication Annotation

This annotation is typically used on the main class of a Spring Boot application. It simplifies the setup process, so you don’t have to manually add each of these annotations.


    @SpringBootApplication
    public class MyApplication {
        public static void main(String[] args) {
            // This line starts the Spring Boot application
            SpringApplication.run(MyApplication.class, args);
        }
    }

-> @EnableAutoConfiguration Annotation

The @EnableAutoConfiguration annotation automatically sets up your application based on the libraries and tools you include in your project. For example, if you add a library for a database, it will automatically configure the necessary settings and components to use the database.

You don’t need to use this annotation directly because it is already included in the @SpringBootApplication annotation. This makes setting up a Spring Boot application easier by removing the need for manual configuration.

-> @ConfigurationProperties Annotation

The @ConfigurationProperties annotation is used to connect properties from external configuration files (like application.properties or application.yml) to a Java class. It maps all the related properties with a specific prefix to the fields of a class. let’s understanding about it with an example

Define one message in application.properties file


 app.message = Hello welcome to spring boot lecture with engineer's coding hub
              

Create one class which communicate with this application.properties file using @ConfigurationProperties


@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
	
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

Create controller and define the end point


 @RestController
public class Controller {
	
	@Autowired
	private AppConfig appConfig;
	
	@GetMapping("/message")
	public String getMessage() {
		return appConfig.getMessage();
	}

}

Properties starting with app (like app.message) in the configuration file will automatically be set to the fields of the AppConfig class. Now if we fire the URL http://localhost:8082/getMessage then we got following output

api response

Core Spring Framework Annotations

-> @Component Annotation

In Spring Boot Annotations The @Component annotation is a general-purpose annotation in Spring. It marks a class as a Spring-managed object, making it eligible for detection during the scanning process.

What It Does:

  • Tells Spring that this class is a component and should be managed by the Spring container.

When to Use:

Use it for any class that needs to be automatically discovered and managed by Spring, especially when using annotation-based configuration.


 @Component
 public class MyComponent {
    // Your code here
 }

In this example, the MyComponent class will be automatically detected and managed by Spring during the application’s startup.

-> @Repository Annotation

The @Repository annotation is used to mark a class as part of the persistence layer in a Spring application. It tells Spring that the class is responsible for database operations like saving, retrieving, and searching data.

What It Does:

  • Identifies the class as a repository for managing data storage.
  • Helps Spring handle exceptions related to database operations.

When to Use:

Apply it to classes that interact with the database, such as Data Access Objects (DAOs).


     @Repository
     public class UserRepository {
        // Code for database operations
     } 

Here, the UserRepository class is marked as a repository, so Spring will treat it as a component for managing data-related tasks.

-> @Service Annotation

In Spring Boot annotations The @Service annotation is used to label a class as part of the service layer in a Spring application. It is specifically meant for classes that contain business logic.

What It Does:

  • Marks the class as a service provider.
  • Makes the class eligible for Spring’s component scanning, so it can be automatically managed by the Spring container.

When to Use:

Use it for classes that handle the core business logic or coordinate between the controller and repository layers.


   @Service
   public class UserService {
        // Business logic methods
   }

Here, the UserService class is recognized as a service layer component, responsible for processing and managing the main business rules of the application.

-> @Controller Annotation

The @Controller annotation is used to mark a class as a controller in a Spring MVC application. This means the class will handle HTTP requests and return the appropriate responses.

What It Does:

  • It tells Spring that this class is responsible for processing incoming requests from users (like web pages).

When to Use:

Use it for classes that handle user requests, like getting data from the database and showing it on a webpage.


   @Controller
   public class UserController {
        // Methods to handle HTTP requests
   }

In this example, the UserController class will handle the HTTP requests from users, such as showing user details on a webpage.

-> @Configuration Annotation

In Spring Boot Annotations The @Configuration annotation is used to mark a class as a source of bean definitions for the Spring application context. It tells Spring that this class will provide beans that can be used throughout the application.

What It Does:

  • Marks a class as a configuration class that contains methods for creating beans.
  • The @Bean methods inside this class define the beans for the application.

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

In this example, AppConfig is a configuration class, and the myService method defines a bean of type MyService.

-> @Bean Annotation

The @Bean annotation is used to define individual beans inside a @Configuration class. It marks a method that will create and return an object that will be managed by the Spring container.

What It Does:

  • Tells Spring that this method produces a bean for the application context.
  • The method will be executed to create a bean when the application starts.

     @Configuration
     public class AppConfig {
        @Bean
        public DataSource dataSource() {
            return new DriverManagerDataSource();
        }
     }
                  

Here, the dataSource method creates a DataSource bean that Spring will manage.

-> @Autowired Annotation

The @Autowired annotation is used to automatically inject dependencies into a Spring class. It can be applied to constructors, fields, or setter methods.

What It Does:

  • Tells Spring to automatically inject a matching bean from the application context into the annotated field or method.

    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;
    }
                  

In this example, Spring will automatically inject an instance of UserRepository into UserService.

-> @Qualifier Annotation

The @Qualifier annotation is used alongside @Autowired to specify which bean should be injected when multiple beans of the same type exist.

What It Does:

  • Helps Spring decide which bean to inject if there are multiple options.

     @Autowired
     @Qualifier("specialDataSource")
     private DataSource dataSource;

Here, Spring will inject the specialDataSource bean when there are multiple DataSource beans available.

-> @Value Annotation

The @Value annotation is used to inject values from property files into Spring components, such as values from application.properties or application.yml.

What It Does:

  • Injects simple values (like strings, numbers) into fields of Spring components.

     @Value("${database.username}")
     private String databaseUsername;

Here, the value of database.username from the properties file will be injected into databaseUsername.

-> @PropertySource Annotation

The @PropertySource annotation is used to add external property files to the Spring environment. It helps load configuration properties into your application.

What It Does:

  • Tells Spring to load a property file and make its values available to the application.

    @Configuration
    @PropertySource("classpath:database.properties")
        public class AppConfig {
        // Configuration code here
    }

Youtube Video –

Explore our more articals

What is Annotations in Spring Boot and How its Works ?

Spring Boot annotations are like labels or tags that give extra information to a Spring application. They help set up and configure the application without needing a lot of manual work. Built on top of the Spring Framework, Spring Boot simplifies the development process by reducing the need for extensive configuration. It has gained immense popularity among developers for its ability to create production-ready applications quickly, enabling a focus on application logic rather than setup complexities.

Spring Boot Specific Annotations ?

1.  @SpringBootApplication Annotation – The @SpringBootApplication annotation is a shortcut in Spring Boot that combines of @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations
2. @EnableAutoConfiguration Annotation-The  @EnableAutoConfiguration annotation automatically sets up your application based on the libraries and tools you include in your project. For example, if you add a library for a database, it will automatically configure the necessary settings and components to use the database.
3. @ConfigurationProperties Annotation – The @ConfigurationProperties annotation is used to connect properties from external configuration files (like application.properties or application.yml) to a Java class. It maps all the related properties with a specific prefix to the fields of a class.

Core Spring Framework Annotations ?

-> @Component Annotation
-> @Repository Annotation
-> @Service Annotation
-> @Controller Annotation
-> @Configuration Annotation
-> @Bean Annotation
-> @Autowired Annotation
-> @Qualifier Annotation
-> @Value Annotation
-> @PropertySource Annotation

1 thought on “Spring Boot Annotations”

Leave a Comment