Tutorial World

List of All Spring Boot Annotations, Uses with examples

  • Post author: Tutorial World
  • Post published:
  • Post category: Spring Boot

Table of Contents

Commonly used Spring Boot annotations along with their uses and examples

1). @SpringBootApplication: This annotation is used to bootstrap a Spring Boot application. It combines three annotations: @Configuration , @EnableAutoConfiguration , and @ComponentScan .

2). @RestController: This annotation is used to indicate that a class is a RESTful controller. It combines @Controller and @ResponseBody .

3). @RequestMapping: This annotation is used to map web requests to specific handler methods. It can be applied at the class or method level.

4). @Autowired: This annotation is used to automatically wire dependencies in Spring beans. It can be applied to fields, constructors, or methods.

5). @Component: This annotation is used to indicate that a class is a Spring bean. Example:

6). @Service: This annotation is used to indicate that a class is a specialized type of Spring bean, typically used for business logic.

7). @Repository: This annotation is used to indicate that a class is a specialized type of Spring bean, typically used for database access.

8). @Configuration: This annotation is used to declare a class as a configuration class. It is typically used in combination with @Bean methods.

9). @Value: This annotation is used to inject values from properties files or other sources into Spring beans.

10). @EnableAutoConfiguration: This annotation is used to enable Spring Boot’s auto-configuration mechanism. It automatically configures the application based on the classpath dependencies and properties.

11). @GetMapping, @PostMapping, @PutMapping, @DeleteMapping : These annotations are used to map specific HTTP methods to handler methods. They are shortcuts for <strong>@RequestMapping</strong> with the respective HTTP method.

12). @PathVariable: This annotation is used to bind a method parameter to a path variable in a request URL.

13). @RequestParam: This annotation is used to bind a method parameter to a request parameter.

14). @RequestBody: This annotation is used to bind the request body to a method parameter. It is commonly used in RESTful APIs to receive JSON or XML payloads. Example:

15). @Qualifier: This annotation is used to specify which bean to inject when multiple beans of the same type are available.

16). @ConditionalOnProperty: This annotation is used to conditionally enable or disable a bean or configuration based on the value of a property.

17). @Scheduled: This annotation is used to schedule the execution of a method at fixed intervals.

18). @Cacheable, @CachePut, @CacheEvict: These annotations are used for caching method results. They allow you to cache the return value of a method, update the cache, or evict the cache, respectively.

Here’s an extensive list of Spring Boot annotations

1. core annotations:, a). @springbootapplication.

The @SpringBootApplication annotation is used to mark the main class of a Spring Boot application. This is the Spring Boot Application starting point. It combines three annotations: @Configuration , @EnableAutoConfiguration , and @ComponentScan . This annotation enables auto-configuration, component scanning, and configuration capabilities for the application.

b). @ComponentScan

The @ComponentScan annotation is used to specify the base package(s) to scan for Spring components such as controllers, services, repositories, etc.

c). @Configuration

The @Configuration annotation is used to indicate that a class declares one or more bean definitions. It is typically used in combination with @Bean to define Spring configuration classes. In the example, the DatabaseConfig class is marked as a configuration class, and the dataSource() method is annotated with @Bean to define a bean of type DataSource .

d). @EnableAutoConfiguration

The @EnableAutoConfiguration annotation allows Spring Boot to automatically configure the application based on the dependencies present in the classpath. It helps to reduce manual configuration by inferring configuration based on conventions and default settings.

e). @RestController

The @RestController annotation is used to mark a class as a controller in a Spring MVC or Spring WebFlux application. It combines the @Controller and @ResponseBody annotations. In the example, the UserController class is a REST controller that handles HTTP GET requests for the “/users” endpoint.

f). @Controller

The @Controller annotation is used to mark a class as a controller in a Spring MVC or Spring WebFlux application. It handles HTTP requests and returns the view name or a response body. In the example, the HomeController class is a controller that handles requests for the root (“/”) URL and returns the view name “index”.

g). @Service

The @Service annotation is used to mark a class as a service component in the business logic layer. It is used to encapsulate business logic and perform operations such as data retrieval, manipulation, and validation. In the example, the UserService class is a service component that provides a method to retrieve users.

h). @Repository

The @Repository annotation is used to mark a class as a repository component in the data access layer. It is responsible for data access operations such as querying, saving, updating, and deleting data from a database. In the example, the UserRepository class is a repository component that provides a method to retrieve users from the database.

The @Bean annotation is used to declare a method as a bean producer method within a configuration class. It indicates that the method returns an object that should be managed by the Spring container as a bean. In the example, the userService() method is annotated with @Bean to define a bean of type UserService .

j). @Autowired

The @Autowired annotation is used to inject dependencies automatically by type. It can be applied to constructors, fields, and methods. In the example, the UserRepository dependency is autowired into the UserService class constructor.

k). @Qualifier

The @Qualifier annotation is used to resolve ambiguous dependencies when there are multiple beans of the same type. It can be applied along with @Autowired to specify the exact bean to be injected. In the example, the userRepository bean is qualified using its bean name.

The @Value annotation is used to inject values from external sources, such as properties files, into variables. In the example, the appName the variable is injected with the value of the “app.name” property from an external configuration source.

2. Web Annotations :

@RequestMapping

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

@PatchMapping

@RequestBody

@ResponseBody

@PathVariable

@RequestParam

@RequestHeader

@CookieValue

@ModelAttribute

@ResponseStatus

@ExceptionHandler

3. Data Annotations :

@GeneratedValue

@Repository

@Transactional

@PersistenceContext

@NamedQuery

@JoinColumn

4. Validation Annotations :

5. security annotations :.

@EnableWebSecurity

@Configuration

@EnableGlobalMethodSecurity

@PreAuthorize

@PostAuthorize

@RolesAllowed

@EnableOAuth2Client

@EnableResourceServer

@EnableAuthorizationServer

6. Testing Annotations :

@SpringBootTest

@WebMvcTest

@DataJpaTest

@RestClientTest

@AutoConfigureMockMvc

@BeforeEach

@DisplayName

@ParameterizedTest

@ValueSource

@ExtendWith

7. Caching Annotations :

@EnableCaching

@CacheEvict

8. Scheduling Annotations :

@EnableScheduling

9. Messaging Annotations :

@JmsListener

@MessageMapping

10. Aspect-Oriented Programming (AOP) Annotations :

@AfterReturning

@AfterThrowing

11. Actuator Annotations :

@EnableActuator

@RestControllerEndpoint

@ReadOperation

@WriteOperation

@DeleteOperation

12. Configuration Properties Annotations :

@ConfigurationProperties

@ConstructorBinding

13. Internationalization and Localization :

@EnableMessageSource

@EnableWebMvc

@LocaleResolver

@MessageBundle

@MessageSource

14. Logging and Monitoring :

@ExceptionMetered

15. Data Validation :

@PositiveOrZero

@NegativeOrZero

16. GraphQL Annotations :

@GraphQLApi

@GraphQLQuery

@GraphQLMutation

@GraphQLSubscription

@GraphQLArgument

@GraphQLContext

@GraphQLNonNull

@GraphQLInputType

@GraphQLType

17. Integration Annotations :

@IntegrationComponentScan

@MessagingGateway

@Transformer

@Aggregator

@ServiceActivator

@InboundChannelAdapter

@OutboundChannelAdapter

18. Flyway Database Migrations :

@FlywayTest

@FlywayTestExtension

@FlywayTestExtension.Test

@FlywayTestExtension.BeforeMigration

@FlywayTestExtension.AfterMigration

19. JUnit 5 Annotations :

@TestInstance

@TestTemplate

@DisplayNameGeneration

@DisabledOnOs

@EnabledOnOs

@DisabledIf

20. API Documentation Annotations :

@Api: This annotation is used to provide high-level information about the API.

@ApiOperation: This annotation is used to describe an operation or endpoint in the API.

@ApiParam: This annotation is used to describe a parameter in an API operation.

@ApiModel: This annotation is used to describe a data model used in the API.

@ApiModelProperty: This annotation is used to describe a property of a data model.

21. Exception Handling Annotations :

@ControllerAdvice: This annotation is used to define global exception handling for controllers.

@ExceptionHandler: This annotation is used to define a method to handle specific exceptions.

22. GraphQL Annotations :

@GraphQLSchema: This annotation is used to define the GraphQL schema for a Spring Boot application.

@GraphQLQueryResolver: This annotation is used to define a class as a GraphQL query resolver.

@GraphQLMutationResolver: This annotation is used to define a class as a GraphQL mutation resolver.

@GraphQLSubscriptionResolver: This annotation is used to define a class as a GraphQL subscription resolver.

@GraphQLResolver: This annotation is used to define a class as a generic resolver for GraphQL.

23. Server-Sent Events (SSE) Annotations :

@SseEmitter: This annotation is used to create an SSE endpoint for server-sent events.

@SseEventSink: This annotation is used to inject an SSE event sink into a method parameter.

24. WebFlux Annotations :

@RestController: This annotation is used to create a RESTful controller in a WebFlux application.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping: These annotations are used to map HTTP methods to handler methods in a WebFlux application.

25. Micrometer Metrics Annotations :

@Timed: This annotation is used to measure the execution time of a method.

@Counted: This annotation is used to count the number of times a method is invoked.

@Gauge: This annotation is used to expose a method as a gauge metric.

@ExceptionMetered: This annotation is used to measure the rate of exceptions thrown by a method.

Please note that this is not an exhaustive list, and Spring Boot offers many more annotations across various modules and features. For a comprehensive list of annotations and their usage, I recommend referring to the official Spring Boot documentation and module-specific documentation.

You Might Also Like

Spring security architecture and configuration explanations, dependency injection and inversion of control (ioc) explanations with example, spring beans and bean scopes explanation.

Javatpoint Logo

  • Spring Boot
  • Interview Q

Spring Boot Tutorial

Creating project, project components, spring boot aop, spring boot database, spring boot view, spring boot misc, spring boot - restful, spring tutorial, spring cloud, spring microservices.

Interview Questions

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • 90% Refund @Courses
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Related Articles

  • Solve Coding Problems
  • Spring Boot Tutorial
  • Introduction to Spring Boot
  • Best Way to Master Spring Boot – A Complete Roadmap
  • How to Create a Spring Boot Project?
  • Spring Boot - Annotations
  • Spring Boot - Architecture
  • Spring Boot Actuator
  • Spring Boot - Introduction to RESTful Web Services
  • How to create a basic application in Java Spring Boot
  • How to create a REST API using Java Spring Boot
  • Easiest Way to Create REST API using Spring Boot
  • Java Spring Boot Microservices Sample Project
  • Difference between Spring MVC and Spring Boot
  • Spring Boot - Spring JDBC vs Spring Data JDBC
  • Best Practices For Structuring Spring Boot Application
  • Spring Boot - Start/Stop a Kafka Listener Dynamically
  • How to Dockerize a Spring Boot Application with Maven
  • Dynamic Dropdown From Database using Spring Boot
  • Spring - RestTemplate
  • Spring Boot - Scheduling
  • Spring Boot - Sending Email via SMTP
  • Different Ways to Establish Communication Between Spring Microservices
  • JSON using Jackson in REST API Implementation with Spring Boot
  • How to encrypt passwords in a Spring Boot project using Jasypt
  • Containerizing Spring Boot Application

Spring Boot – Annotations

Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Following are some of the features of Spring Boot:

  • It allows for avoiding heavy configuration of XML which is present in the spring
  • It provides easy maintenance and creation of REST endpoints
  • It includes embedded Tomcat-server
  • Deployment is very easy, war and jar files can be easily deployed in the Tomcat server

Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. So in this article, we are going to discuss some important Spring Boot Annotations that are available in Spring Boot with examples.

Spring Boot Annotations

Spring annotations are present in the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.condition packages are commonly known as Spring Boot annotations. Some of the annotations that are available in this category are:

  • @SpringBootApplication
  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan
  • @ConditionalOnClass, and @ConditionalOnMissingClass
  • @ConditionalOnBean, and @ConditionalOnMissingBean
  • @ConditionalOnProperty
  • @ConditionalOnResource
  • @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
  • @ConditionalExpression
  • @Conditional

1. @SpringBootApplication Annotation

This annotation is used to mark the main class of a Spring Boot application. It encapsulates @SpringBootConfiguration , @EnableAutoConfiguration , and @ComponentScan annotations with their default attributes.

SpringBootApplication_annotation

2. @SpringBootConfiguration Annotation

It is a class-level annotation that is part of the Spring Boot framework. It implies that a class provides Spring Boot application configuration. It can be used as an alternative to Spring’s standard @Configuration annotation so that configuration can be found automatically. Most Spring Boot Applications use @SpringBootConfiguration via @SpringBootApplication. If an application uses @SpringBootApplication, it is already using @SpringBootConfiguration.

3. @EnableAutoConfiguration Annotation

This annotation auto-configures the beans that are present in the classpath. It simplifies the developer’s work by assuming the required beans from the classpath and configure it to run the application. This annotation is part of the spring boot framework. For example, when we illustrate the spring-boot-starter-web dependency in the classpath, Spring boot auto-configures Tomcat , and Spring MVC . The package of the class declaring the @EnableAutoConfiguration annotation is considered as the default. Therefore, we need to apply the @EnableAutoConfiguration annotation in the root package so that every sub-packages and class can be examined.

4. @ComponentScan Annotation

@ComponentScan tells Spring in which packages you have annotated classes that should be managed by Spring. So, for example, if you have a class annotated with @Controller which is in a package that is not scanned by Spring, you will not be able to use it as a Spring controller. So we can say @ComponentScan enables Spring to scan for things like configurations, controllers, services, and other components that are defined. Generally, @ComponentScan annotation is used with @Configuration annotation to specify the package for Spring to scan for components.

5. @ConditionalOnClass Annotation and @ConditionalOnMissingClass Annotation

@ConditionalOnClass Annotation used to mark auto-configuration bean if the class in the annotation’s argument is present/absent.

6. @ConditionalOnBean Annotation and @ConditionalOnMissingBean Annotation 

These annotations are used to let a bean be included based on the presence or absence of specific beans.

7. @ConditionalOnProperty Annotation 

These annotations are used to let configuration be included based on the presence and value of a Spring Environment property.

8. @ConditionalOnResource Annotation 

These annotations are used to let configuration be included only when a specific resource is present in the classpath.

9. @ConditionalOnExpression Annotation 

These annotations are used to let configuration be included based on the result of a SpEL (Spring Expression Language) expression. 

SpEL (Spring Expression Language): It is a powerful expression language that supports querying and manipulating an object graph at runtime. 

10. @ConditionalOnCloudPlatform Annotation 

These annotations are used to let configuration be included when the specified cloud platform is active.

Request Handling and Controller annotations:

Some important annotations comes under this category are:

  • @Controller
  • @RestController
  • @RequestMapping
  • @RequestParam
  • @PathVariable
  • @RequestBody
  • @ResponseBody
  • @ModelAttribute

1. @Controller Annotation

This annotation provides Spring MVC features. It is used to create Controller classes and simultaneously it handles the HTTP requests. Generally we use @Controller annotation with @RequestMapping annotation to map HTTP requests with methods inside a controller class.

2. @RestController Annotation

This annotation is used to handle REST APIs such as GET, PUT, POST, DELETE etc. and also used to create RESTful web services using Spring MVC.

It encapsulates @Controller annotation and @ResponseBody annotation with their default attributes.

@RestController = @Controller + @ResponseBody

3. @RequestMapping Annotation

This annotation is used to map the HTTP requests with the handler methods inside the controller class.

For handling specific HTTP requests we can use

  • @GetMapping
  • @PutMapping
  • @PostMapping
  • @PatchMapping
  • @DeleteMapping
NOTE : We can manually use GET, POST, PUT and DELETE annotations along with the path as well as we can use @RequestMapping annotation along with the method for all the above handler requests

4. @RequestParam Annotation

This annotation is basically used to obtain a parameter from URI. In other words, we can say that @RequestParam annotation is used to read the form data and binds the web request parameter to a specific controller method.

5. @PathVariable Annotation

This annotation is used to extract the data from the URI path. It binds the URL template path variable with method variable.

6. @RequestBody Annotation

This annotation is used to convert HTTP requests from incoming JSON format to domain objects directly from request body. Here method parameter binds with the body of the HTTP request.

7. @ResponseBody Annotation

This annotation is used to convert the domain object into HTTP request in the form of JSON or any other text. Here, the return type of the method binds with the HTTP response body.

8. @ModelAttribute Annotation

This annotation refers to model object in Spring MVC. It can be used on methods or method arguments as well.

Here, we don’t need to add object explicitly to the model, because automatically object will be the part of the attribute.

Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Please Login to comment...

  • Java-Spring-Boot
  • swetadash2000

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Lightrun

  • 25-Jul-2022
  • debugging , Dev Tools , Java

Lightrun Team

The Essential List of Spring Boot Annotations and Their Use Cases

  • debugging Dev Tools Java

The Spring framework is a robust server-side framework for modern Java-based enterprise applications. Since its introduction in 2003, its advantages have made it one of the most dominant server-side frameworks among many organizations. According to a research study by Snyk in 2020 on the usage of the server-side web frameworks , 50% of the respondents have said they use Spring Boot , and 31% of the respondents use Spring MVC. 

Java applications use annotations to provide additional information about the code but do not impact a compiled code. They usually start with ‘@’ and are metadata associated with code components such as variables, methods, classes, etc. Based on the defined annotations, the compiler can change how it treats the program.

What is Java Spring Boot?

Java Spring Boot is an open-source framework that allows the creation of standalone and production-grade enterprise applications that execute on Java Virtual Machine (JVM).

Spring Boot has three core capabilities that enable the development of web applications and microservices faster and easier. 

  • Autoconfiguration
  • An opinionated approach to configuration
  • The ability to create standalone applications

You can configure and set up Spring Boot applications with minimal changes from these core capabilities. Any production application needs to be monitored for its uptime. You can use Spring Boot Actuator as a dependency to simplify monitoring your application’s status. 

Spring Boot Features

Why use Annotations? 

Annotations are not just comments in a program. There are many uses of annotations. Annotations help to provide helpful information such as method dependencies, variable meanings, class references, package declaration, type declaration, and many more. Also, they help developers understand the code easily. The compiler can catch errors and suppress specific warnings using annotations. It allows static type checking at compile time. Developers can use these annotations for further processing, such as creating XML files and codes, and with annotations, developers do not have to do cumbersome configurations.

Spring Boot Annotations and their use cases

Spring Boot Annotations are the metadata that provides the additional formation about a Spring Boot program. Several spring boot annotations provide different automatic configurations.

Below are all the essential spring boot annotations you should know about.

The “@Bean” is a method-level annotation that is analogous to XML <bean> tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory. The following shows how the usage of @Bean in a method statement:

2. @Springbootapplication

The “@SpringBootApplication” annotation triggers auto-configuration and component scanning. It combines three annotations: @Configuration, @ComponentScan, and @EnabeAutoConfiguration. 

3. @Configuration

The “@Configuration” is a class-based annotation that indicates the definition of one or more Bean methods in the class. Once the Sprint container encounters this annotation, it can process these spring beans to generate bean definitions and service requests at runtime.

4. @ComponentScan

You can use the “@ComponentScan” annotation with the “@Configuration” annotation to define the components you need the program to scan. There are a few arguments in this annotation. The framework scans the current package with sub-packages if you do not specify any argument. You can use the ‘basePackages’ argument to define the specific packages to scan.

5. @EnableAutoconfiguration

This annotation allows you to auto-configure the program based on your requirements. The framework decides this auto-configuration based on the jars included in the program and the classpath. For example, suppose you added the “tomcat-embedded.jar” file, then it automatically configures the TomcatServletWebServerFactory if there is no explicit declaration for its related factory bean. Using the “exclude” and “excludeClassName” arguments.

6. @RequestMapping 

The “@RequestMapping” Annotation is used to map HTTP requests to REST and MVC controller methods in Spring Boot applications. You can apply this to either class-level or method-level in a controller. Furthermore, you can declare multiple request mappings using a list of values in the annotation.

7. @GetMapping 

The “@GetMapping” is a shortcut for the  “@RequestMapping(method = RequestMethod.GET)” annotation, which handles the HTTP GET requests corresponding to the specified URL. The following class uses the “@RestController” annotation to indicate it can handle web requests. The “@GetMapping” maps /hello to the hello() method

8. @RequestParam

The “@RequestParam” annotation enables extracting input query parameters, form data, etc. For example, suppose you have an endpoint /API/book which takes a query string parameter called id. Then you can specify that parameter in the following manner using the @RequestParam annotation. 

9. @Service 

The @Service is a class-level annotation used to indicate that the class is a service class that defines the business logic. For instance, the below @Service annotation indicates that BankService is a service class that offers bank services. 

10. @Component 

This component allows the framework to automatically detect the component classes without any need to write any explicit code. Spring framework scans classes with @component, initialize them, and injects the required dependencies.

11. @Repository

The “@Repository” is a specialized version of the “ @Component” annotation. It indicates that the class is a repository that contains data storage and other operations such as updating, deleting, searching, and retrieving data on objects. 

12. @Controller

This class-based annotation is also a specialization of the “@Component” annotation, marking the class as a controller. It usually combines with handler methods annotated with the @RequestMapping annotation and is used with Spring MVC applications. Spring scans these classes with this annotation and catches @RequestMapping annotations. Below is an example of its usage.

13. @Autowired

The “@Autowired” annotation can auto wire bean on a constructor,  setter method, property, or methods with multiple parameters. When you use @Autowired annotation on setter methods, you can eliminate the <property> tag in the XML configuration file. 

14. @SpringBootTest

As the name suggests, @SpringBootTest annotation can be used on a test class that executes Spring Boot-based tests. You can use it easily for integration testing as it loads the full application context. 

15. @MockBean

Using this annotation, you can specify mocks in ApplicationContext and mocks the services or REST API endpoints from your programs. Spring loads the mock version of the application context when you run the application. You can specify this annotation at the class and field levels, and it is possible to specify them in configuration classes. Below is an example of using the “@MockBean” annotation.

Spring Boot has a collection of annotations that enable you to develop web applications faster and more efficiently. While developing with Spring Boot,  speed and productivity are absolute priorities for all developers. Lightrun is a key observability platform that helps developers build applications faster by enabling them to add logs, traces, and metrics to their code on-demand and in real-time while the app runs.

Do you want to build robust and fast-running applications? Then get started with Lightrun or request a demo today!

Observability vs monitoring

Observability vs. Monitoring

Top IntelliJ debug shortcuts

Top 8 IntelliJ Debug Shortcuts

Shift left testing

Shift Left Testing: 6 Essentials for Successful Implementation

It’s really not that complicated..

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Looking for more information about Lightrun and debugging? We’d love to hear from you! Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use .

SpringHow

Spring Boot Annotations | Beginners guide

' src=

Let’s take a look at a list of important spring boot annotations and when to use them with an example.

What are annotations?

Annotations are a form of hints that a developer can give about their program to the compiler and runtime. Based on these hints, the compilers and runtimes can process these programs differently. That is exactly what happens with annotations in spring boot. Spring Boot uses relies on annotations extensively to define and process bean definitions. Some of the features we discuss here are from Spring Framework. But Spring Boot itself is an opinionated version of Spring.

Spring Boot annotation catagories

Based on the use case, Spring annotations fall in to one the following categories.

  • Bean definition annotations (from Core Spring Framework)
  • Configuration annotations

Spring Component annotations

  • Other modules Specific spring-boot annotations

1. Spring Core Annotations

These annotations are not part of spring boot but the spring framework itself. These annotations deal with defining beans. So, Lets look at each of these in details.

You should use the @Bean on a method that returns a bean object. For example, you could define a bean as shown below.

The @Autowired annotation lets you inject a bean wherever you want(most importantly factory methods like the one we seen above). For example, we needed a MyDto for MyService in our previous example. As we had to hardcode in that example, you can simplify it as shown here.

As you see here, @Autowired annotation makes sure spring boot loads an appropriate MyDto bean. Note that, you would get an error if you haven’t defined a MyDto bean. You could work around this by setting @Autowired(required=false) .

This approach provides you a default approach that you can override later.

You could also use the @Autowired annotation for arbitrary number of beans. This is done by setting the annotation at the method level. For instance, take a look at this snippet.

In the above scenario, all three beans must be defined for the myServiceUsingAutowireMultiple factory method to succeed.

Similar to setting required flag in @Autowired , you should use this annotation to mark a certain field or setter method as required. For instance, take a look at this snippet.

2. Spring Boot Configuration annotations

Spring Boot favors java annotations over xml configurations. Even though both of them have pros and cons, the annotations help create complex configurations that work dynamically. So lets go thorough each of these with some examples.

@SpringBootApplication

The @SpringBootApplication annotation is often used in the main class. This annotation is equivalent to using @Configuration , @EnableAutoConfiguration  and  @ComponentScan together. This annotation is responsible for setting up which autoconfiguration to enable and where to look for spring bean components and configurations.

@Configuration

This annotation is used together with the bean definition annotations. When the @ComponentScan finds a class that is annotated with @Configuration , it will try to process all @Bean and other spring related methods inside it.

Configuration properties

This spring boot specific annotation helps bind properties file entries to a java bean. For example, take a look at these configs.

Let’s map these into a java bean.

If setup correctly, Spring boot will create a AppConfig bean object with values mapped from properties. Subsequently, We can autowire them wherever we want.

@Value annotation

This annotation is similar to @Autowired . Except this one is for accessing properties entries instead of beans.

You could also use @Value to access complex SpEL expressions.

there are other few spring boot annotations for configurations that we would not discuss here.

While @Bean lets you create bean using factory methods, you could simply mark a class with one of the following component annotations. These annotations create a singleton bean of that specific class.

In a way these spring boot annotations provide context to what those beans represent in the system. They are,

@Component annotation

This is the basic version among those four. This annotation on a class makes a singleton bean of that said class. For example, the following creates a bean of type BookService with the name “bookService”.

Once the component scan finds this class, it will try to use the constructor to create a BookService object. As you see here, the constructor needs a Dto bean. So spring boot will look for one that satisfies that requirement.

@Service Spring boot annotation

This annotation is similar to Component in everyway. The only reason to use a @Service annotation instead of @Component is for convention(domain driven design).

@Controller annotation

The @Controller marks a class as a spring web MVC controller. This annotation is usually used along with web based spring applications. Apart from the MVC related features it brings, the rest of the behavior stands in line with @Component .

Once the spring MVC sees a controller class, it looks for all @RequestMapping and configures them to handle requests. We will take a look at these in detail later.

There is also a restful variant of @Controller called @RestController . There is also @GetMapping, @PostMapping and other mapping annotations available part of Spring MVC. They are more specialized versions of @RequestMapping annotations.

@RequestMapping

The request mapping annotation lets spring MVC know which controller class method to call. This annotation takes two parameters called path and method . This way we could map them based on path as well as HTTP methods like , GET, POST, PUT and DETELE.

@ResponseBody

The response body is an optional annotation for controller methods. When supplied, this annotation will convert the method return value in to JSON response.

For example, the above code would return a JSON array of strings.

@Repository annotation in Spring Boot

The repository annotation is a bit different among all other stereotypes annotations. Even though this annotation is used extensively in JPA, this annotation came into picture as part of Domain Driven Design.

A common use case would be to annotate JPA repository interfaces. This way Spring-JPA module can provide JPQL support. For example, We could write a BookDto as shown here.

Even though we don’t need to annotate interfaces that extend, it is still a good convention. Also, apart from being a repository, all behaviours from @Component is applicable for @Repository annotation.

Spring boot Module-specific annotations

As spring boot comes with various modules like JPA, MVC, RabbitMQ, Scheduling, caching etc., all of these modules also provide their own annotations for us to use. We have seen some of the annotations from JPA and MVC. So let’s go through the remaining quickly.

Scheduling related annotations

The @Scheduled annotation helps make a method execute on a specific interval.

This annotation takes one of fixedDelay , fixedRate or quartz compatible cron expression.

Caching annotations

Caching annotations play important role in application performance. The cache abstraction in spring boot is powerful and you should take a look. Here are the important annotations from this module.

The @EnableCaching annotation enables support for caching by auto-configuring a cache manager. Usually this annotation goes on the spring boot’s main class.

@Cacheable annotation marks a method’s return values to be cacheable. This way, when the first time the method was called with a specific parameter, the value is saved in the cache. If another request calls the same method with the same parameter, spring boot will return the value from cache instead of executing the method.

As you can see, it takes a cache name and a key to store the result. This way when a new request comes with the same key, we could get the result from cache instead of running the method again.

The @CacheEvict annotation lets you clear a specific value from the cache. It could also be used to clear the entire cache if needed. This annotation exists because your cached results may be outdated and might need a refresh. For example, if you update an entity in DB, then you might want to clear the cached value as well.

AMQP/RabbitMQ annotations

The AMQP module provides certain annotations to deal with message queues of RabbitMQ. The important annotations are listed here.

The @EnableRabbit adds autoconfiguration for AMQP. This annotation is responsible for enabling RabbitAutoConfiguration . Without this annotation, the remaining AMQP annotations won’t work.

@RabbitListener takes a queue name and executes the annotated method. For example, you could read messages from queues as shown here.

There are also few annotations like @Exchange , @queue and @QueueBinding which are used along with @RabbitListener .

We saw a hand-picked list of important annotations used in spring boot. These annotations solve the problem of defining spring beans, utilize them dynamically and configure them. You can find most of these annotations in the samples available in our Github repository .

  • Spring Cache For Better application performance
  • Spring Boot Redis Cache
  • Handling Lists in Thymeleaf view
  • Constructor dependency injection in Spring Framework

Similar Posts

Web server failed to start port 8080 was already in use.

In this post, We will try to understand the Web server failed to start Port 8080 was already in use error and how to fix it. Why Port 8080 was already in use? In the network, an IP address identifies each machine. Similarly, The network port identifies the application or process running on a machine. When an…

@SpringBootApplication annotation – How it works

Every spring boot application has the @SpringBootApplication annotation on its main class. On contrary to popular belief, it is not just there to inform that the application is a spring boot application. Let’s take a deep dive into what this annotation is and how it works with some examples. Introduction The @SpringBootApplication annotation is there…

Introduction to WebSocket with Spring Boot

Let’s look at how to add WebSocket support to a spring boot application. We will try to create a simple chat application. Note that this implementation does not use STOMP. What is WebSocket? The WebSocket protocol helps establish a full-duplex two-way communication between client and server over a single TCP connection. This protocol is different…

Spring Boot and Postgres Using Docker Compose

In this blog post, we will walk through the steps to run a Spring Boot application and PostgreSQL database in Docker using Docker Compose. Prerequisites Before we start, make sure you have the following installed on your machine: Step 1: Create a Spring Boot Application Before we start, we need a spring boot application for…

Spring Boot RabbitMQ – Complete Guide For Beginners

RabbitMQ is a message broker that receives and forwards messages. In this post, You will learn how to use RabbitMQ with spring boot. Also, you will learn how to publish to and subscribe from queues and exchanges. Setting up RabbitMQ in local machine You can download the RabbitMQ installer from the official download page. However,…

Troubleshoot Auto-Configurations in Spring Boot Applications

In this post, we will take a look at how to troubleshoot auto-configurations in Spring Boot applications. What are Auto-Configurations? Spring boot autoconfiguration is where the magic happens. The auto-configuration tries to automatically configure your application based on what’s in the classpath. For example, the h2 database jar in classpath will result in spring boot…

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

ADevGuide

Press ESC to close

All Spring Annotations Explained Cheat Sheet

All Spring Annotations ASAP Cheat Sheet [Core+Boot][2023]

All Spring Annotations Explained Cheat Sheet

  • 1.1) @Configuration
  • 1.2) @ComponentScan
  • 1.3) @Autowired
  • 1.4) @Component
  • 1.6) @Qualifier
  • 1.7) @Primary
  • 1.8) @Required
  • 1.9) @Value
  • 1.10) @DependsOn
  • 1.11) @Lazy
  • 1.12) @Lookup
  • 1.13) @Scope
  • 1.14) @Profile
  • 1.15) @Import
  • 1.16) @ImportResource
  • 1.17) @PropertySource
  • 2.1) @Controller
  • 2.2) @Service
  • 2.3) @Repository
  • 2.4) @RequestMapping
  • 2.5) @RequestBody
  • 2.6) @GetMapping
  • 2.7) @PostMapping
  • 2.8) @PutMapping
  • 2.9) @DeleteMapping
  • 2.10) @PatchMapping
  • 2.11) @ControllerAdvice
  • 2.12) @ResponseBody
  • 2.13) @ExceptionHandler
  • 2.14) @ResponseStatus
  • 2.15) @PathVariable
  • 2.16) @RequestParam
  • 2.17) @RestController
  • 2.18) @ModelAttribute
  • 2.19) @CrossOrigin
  • 2.20) @InitBinder
  • 3.1) @SpringBootApplication
  • 3.2) @EnableAutoConfiguration
  • 3.3) @ConditionalOnClass and @ConditionalOnMissingClass
  • 3.4) @ConditionalOnBean and @ConditionalOnMissingBean
  • 3.5) @ConditionalOnProperty
  • 3.6) @ConditionalOnResource
  • 3.7) @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
  • 3.8) @ConditionalExpression
  • 3.9) @Conditional
  • 4) Cheat Sheet
  • 5) References

All Spring Annotations Explained Cheat Sheet

Nowadays, there are so many spring annotations that it could become overwhelming. Spring Framework started out with XML configuration and over time it has introduced many capabilities to reduce code verbose and get things done quickly. With Spring Boot, we can do almost everything with annotations. Let’s look at all the annotations provided by the Spring Framework.

Spring Core Annotations

@configuration.

@Configuration is used on classes that define beans. @Configuration is an analog for an XML configuration file – it is configured using Java classes. A Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.

@ComponentScan

@ComponentScan is used with the @Configuration annotation to allow Spring to know the packages to scan for annotated components. @ComponentScan is also used to specify base packages using basePackageClasses or basePackage attributes to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

@Autowired is used to mark a dependency which Spring is going to resolve and inject automatically. We can use this annotation with a constructor, setter, or field injection.

@Component is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or component so that the component-scanning mechanism of Spring can add it into the application context.

@Bean is a method-level annotation and a direct analog of the XML element. @Bean marks a factory method which instantiates a Spring bean. Spring calls these methods when a new instance of the return type is required.

@Qualifier helps fine-tune annotation-based autowiring. There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using @Qualifier annotation along with the @Autowired annotation. We use @Qualifier along with @Autowired to provide the bean ID or bean name we want to use in ambiguous situations.

We use @Primary to give higher preference to a bean when there are multiple beans of the same type. When a bean is not marked with @Qualifier, a bean marked with @Primary will be served in case on ambiquity.

The @Required annotation is method-level annotation, and shows that the setter method must be configured to be dependency-injected with a value at configuration time. @Required on setter methods to mark dependencies we want to populate through XML; Otherwise, BeanInitializationException will be thrown.

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. We can use @Value for injecting property values into beans. It’s compatible with the constructor, setter, and field injection.

@DependsOn makes Spring initialize other beans before the annotated one. Usually, this behavior is automatic, based on the explicit dependencies between beans. The @DependsOn annotation may be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.

@Lazy makes beans to initialize lazily. By default, the Spring IoC container creates and initializes all singleton beans at the time of application startup. @Lazy annotation may be used on any class directly or indirectly annotated with @Component or on methods annotated with @Bean.

A method annotated with @Lookup tells Spring to return an instance of the method’s return type when we invoke it.

@Scope is used to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, globalSession or some custom scope.

Beans marked with @Profile will be initialized in the container by Spring only when that profile is active. By Default, all beans has “default” value as Profile. We can configure the name of the profile with the value argument of the annotation.

@Import allows to use specific @Configuration classes without component scanning. We can provide those classes with @Import‘s value argument.

@ImportResource

@ImportResource allows to import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument.

@PropertySource

@PropertySource annotation provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Environment. To be used in conjunction with @Configuration classes.

All About Java Regular Expressions Regex 2019

Spring MVC Annotations

@controller.

The @Controller annotation is used to indicate the class is a Spring controller. This annotation is simply a specialization of the @Component class and allows implementation classes to be auto-detected through the class path scanning.

@Service marks a Java class that performs some service, such as executing business logic, performing calculations, and calling external APIs. This annotation is a specialized form of the @Component annotation intended to be used in the service layer.

@Repository

This annotation is used on Java classes that directly access the database. The @Repository annotation works as a marker for any class that fulfills the role of repository or Data Access Object. This annotation has an automatic translation feature. For example, when an exception occurs in the @Repository, there is a handler for that exception and there is no need to add a try-catch block.

@RequestMapping

@RequestMapping marks request handler methods inside @Controller classes. It accepts below options: path/name/value: which URL the method is mapped to. method: compatible HTTP methods. params: filters requests based on presence, absence, or value of HTTP parameters. headers: filters requests based on presence, absence, or value of HTTP headers. consumes: which media types the method can consume in the HTTP request body. produces: which media types the method can produce in the HTTP response body.

@RequestBody

@RequestBody indicates a method parameter should be bound to the body of the web request. It maps the body of the HTTP request to an object. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. The deserialization is automatic and depends on the content type of the request.

@GetMapping

@GetMapping is used for mapping HTTP GET requests onto specific handler methods. Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@PostMapping

@PostMapping is used for mapping HTTP POST requests onto specific handler methods. Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).

@PutMapping

@PutMapping is used for mapping HTTP PUT requests onto specific handler methods. Specifically, @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).

@DeleteMapping

@DeleteMapping is used for mapping HTTP DELETE requests onto specific handler methods. Specifically, @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).

@PatchMapping

@PatchMapping is used for mapping HTTP PATCH requests onto specific handler methods. Specifically, @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).

@ControllerAdvice

@ControllerAdvice is applied at the class level. For each controller, you can use @ExceptionHandler on a method that will be called when a given exception occurs. But this handles only those exceptions that occur within the controller in which it is defined. To overcome this problem, you can now use the @ControllerAdvice annotation. This annotation is used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods. Thus, if you define the @ExceptionHandler annotation on a method in a @ControllerAdvice class, it will be applied to all the controllers.

@ResponseBody

@ResponseBody on a request handler method tells Spring to converts the return value and writes it to the HTTP response automatically. It tells Spring to treat the result of the method as the response itself. The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. If we annotate a @Controller class with this annotation, all request handler methods will use it.

@ExceptionHandler

@ExceptionHandler is used to declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions. The caught exception can be passed to the method as an argument.

@ResponseStatus

@ResponseStatus is used to specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument.

@PathVariable

@PathVariable is used to indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable.

@RequestParam

@RequestParam indicates that a method parameter should be bound to a web request parameter. We use @RequestParam for accessing HTTP request parameters. With @RequestParam we can specify an injected value when Spring finds no or empty value in the request. To achieve this, we have to set the defaultValue argument.

@RestController

@RestController combines @Controller and @ResponseBody. By annotating the controller class with @RestController annotation, we no longer need to add @ResponseBody to all the request mapping methods.

@ModelAttribute

@ModelAttribute is used to access elements that are already in the model of an MVC @Controller, by providing the model key.

@CrossOrigin

@CrossOrigin enables cross-domain communication for the annotated request handler methods. If we mark a class with it, it applies to all request handler methods in it. We can fine-tune CORS behavior with this annotation’s arguments.

@InitBinder

@InitBinder is a method-level annotation that plays the role of identifying the methods that initialize the WebDataBinder — a DataBinder that binds the request parameter to Java Bean objects. To customize request parameter data binding, you can use @InitBinder annotated methods within our controller. The methods annotated with @InitBinder include all argument types that handler methods support.

The @InitBinder annotated methods will get called for each HTTP request if we don’t specify the value element of this annotation. The value element can be a single or multiple form names or request parameters that the init binder method is applied to.

How is Java Pass by Value and Not by Reference [4 Examples]

Spring Boot Annotations

@springbootapplication.

@SpringBootApplication marks the main class of a Spring Boot application. This is used usually on a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.

@EnableAutoConfiguration

@EnableAutoConfiguration tells Spring Boot to look for auto-configuration beans on its classpath and automatically applies them. It tells Spring Boot to “guess” how you want to configure Spring based on the jar dependencies that you have added. Since spring-boot-starter-web dependency added to classpath leads to configure Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly. This annotation is used with @Configuration.

@ConditionalOnClass and @ConditionalOnMissingClass

The @ConditionalOnClass and @ConditionalOnMissingClass annotations let configuration be included based on the presence or absence of specific classes. With these annotations, Spring will only use the marked auto-configuration bean if the class in the annotation’s argument is present/absent.

@ConditionalOnBean and @ConditionalOnMissingBean

@ConditionalOnBean and @ConditionalOnMissingBean annotations let a bean be included based on the presence or absence of specific beans.

@ConditionalOnProperty

@ConditionalOnProperty annotation lets configuration be included based on a Spring Environment property i.e. make conditions on the values of properties.

@ConditionalOnResource

@ConditionalOnResource annotation lets configuration be included only when a specific resource is present.

@ConditionalOnWebApplication and @ConditionalOnNotWebApplication

@ConditionalOnWebApplication and @ConditionalOnNotWebApplication annotations let configuration be included depending on whether the application is a “web application”. A web application is an application that uses a spring WebApplicationContext, defines a session scope, or has a StandardServletEnvironment.

@ConditionalExpression

@ConditionalExpression is used in more complex situations. Spring will use the marked definition when the SpEL expression is evaluated to true.

@Conditional

@Conditional is used in complex conditions, we can create a class evaluating the custom condition.

Cheat Sheet

All Spring Annotations ASAP Cheat Sheet [Core+Boot][2023] 1

View/Download Cheat Sheet in HD

https://dzone.com https://www.baeldung.com https://jrebel.com/

Share Article:

Pratik bhuite.

In 2019, Pratik Bhuite established ADevGuide, a platform where his passion for technology shines. As a seasoned Full Stack Developer, he's dedicated to absorbing, expanding, and disseminating captivating tech insights. Pratik is presently immersed in the worlds of Java, Oracle, JavaScript, HTML5, and Bootstrap4, contributing to his dynamic expertise.

Most Important Spring Boot Interview Questions [2020]

13 most basic docker commands every developer should know.

Thank you very much for this mate, you saved my life!!!

Welcome, Philip.

Leave a Reply Cancel reply

Spring Boot Annotations Everyone Should Know [2024]

Spring Boot Annotations Everyone Should Know [2024]

In this article, you will learn Spring Boot Annotations like

@Repository

@Configuration

@Controller

  • @RequestMapping
  • @SpringBootApplication
  • @EnableAutoConfiguration

Read the full article to know more in detail.

Spring Boot Annotations are a form of metadata that provides data about a program that is not a part of the program itself. They do not have any direct effect on the operation of the code they annotate. Spring Boot Annotations do not use XML and instead use the convention over configuration principle. 

free courses  to get an edge over the competition.

Ads of upGrad blog

The use of annotations extends beyond mere code organization. Spring Annotations have become integral to the development process, pivotal in simplifying and elevating the overall coding experience.

These annotations are crucial in the software development industry that runs on adaptability and scalability. They provide a mechanism for developers to express intentions and configurations concisely. 

This blog thoroughly explores Spring Boot Annotations , providing detailed insights into their uses. It also offers a helpful Spring Boot Annotations list to understand how these annotations work in practice.

Spring Boot Annotations Explained

Before delving into the different types, it is important to address the fundamental question, “ What are Annotations in Spring Boot ?” 

These annotations are critical in enhancing the development process by simplifying configuration tasks and fostering a more intuitive and readable codebase. Whether categorizing components, defining URL mappings, or specifying dependencies, Spring Boot Annotations in Java contribute to a modular and adaptable architecture.

Advantages of Using Annotations in Spring Boot

Spring Boot Annotations have certain advantages attached to them such as:-

  • Works well the servlet containers

In Java, Spring Boot, the servlet containers are the atmosphere where the Java web applications can survive/ live. Servlet Container or Web Container is the application server where it applies various Java versions like Java Servlet, JSP, etc. 

These containers play a crucial role in executing and managing the lifecycle of web components, handling requests and responses, and ensuring the seamless functioning of Java-based web applications. 

  • Saves memory space due to boostrapping

Bootstrapping in Spring Boot annotations is nothing but a process of initialising an application. The application can be initialised by using the Spring Initializer. Bootstrapping allows the users to utilise the space in their respective devices while they give the scope to applications to load quickly. 

  • No requirement for WAR files

WAR files in software engineering stands for Web Application Resource or Web Application Archive). Although Spring Boot can use WAR files they use JAR files for various reasons, such as the compressed file size which helps the developers to connect the applications with tools. Also, the JAR files are easier to handle, create, update, etc.

JAR or Java Archive files serve as containers for compiling multiple files into a single compressed archive. This format facilitates easy distribution and deployment as well as aids in managing dependencies and resources more efficiently within Spring Boot applications, simplifying development and maintenance processes significantly.

  • POM dependency management

POM is Project – Object-Model, it contains the information about the project in the XML file. The POM dependency management is the centralised process to manage the dependency information. The Springboot dependencies allow the developers to manage dependencies without relying on the parent POM or XML file.

The POM dependency management system ensures consistency and coherence throughout the project. This standardized way ensures everyone working on the project uses the same dependencies. It helps prevent issues and keeps everything working together smoothly.

  • XML configuration is not required

The developers can avoid the XML configuration in Java Spring Boot, which appeals to the developers as it allows them to skip extra steps.

This streamlining enhances efficiency, allowing developers to focus on essential tasks without requiring intricate setup procedures. 

  • Boilerplate code is decreased

The boilerplate code can be used by using the Spring Boot embedded server, as it decreases the boilerplate code. The absence of boilerplate code gives the developers a scope to lessen the time to develop applications and increase their productivity. 

Also, Spring boot starter is another feature, they are dependency descriptors. They can be added under the dependency section in pom. or xml.

Spring Boot Annotations Everyone Should Know

Understanding the use of annotations is crucial for enhancing the efficiency and functionality of applications. A Spring Boot Annotations list with explanations can help you better comprehend the use case of these annotations.

The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be managed by the Spring container. It is an alternative to the XML<bean> tag. 

Public BeanExample beanExample ()

return new BeanExample (),

You can also consider doing our  Java Bootcamp course  from upGrad to upskill your career.

In the spring boot annotation, beans are the objects that are the backbone of the application and are managed by the Spring IoC container. The Spring Bean annotation is declared in the configuration classes method.

This annotation is important for configuring the Spring IoC (Inversion of Control) container. By applying @Bean to a method within a configuration class, developers explicitly declare that the method produces a bean instance managed by the Spring container. 

This compact programmatic approach eliminates the need for extensive XML configurations, providing a more streamlined and maintainable way to define beans.

Explore Our Software Development Free Courses

2. @service.

It is used at the class level. It shows that the annotated class is a service class, such as business basic logic, and call external APIs.

public class TestService

public void service1()

// business code

The @service annotation is used where the classes provide some business functionalities. The spring context autodetects these classes as the annotation is used with those classes where the business functionalities are to be used.

This annotation serves as a marker and allows injecting service components into other Spring-managed beans. It fosters a modular and organized approach to developing applications, where the @Service annotation contributes to the effective structuring and autodetection of business logic components within the Spring context.

Read: Spring Boot Projects & Topics

3. @Repository

It is a Data Access Object (DAO) that accesses the database directly. It indicates that the annotated class is a repository. 

public class TestRepository

public void delete()

// persistence code

The repository annotation indicates the class has the capability of storage, retrieval, updating, deletion, and search.

It is a key component in the data access layer. Using this annotation, developers communicate to the Spring framework that the annotated class serves as a data storage and retrieval repository.  

This annotation is particularly useful for classes that interact directly with databases, handling tasks such as data manipulation, querying, and providing a structured approach to database operations.

Featured Program for you:   Fullstack Development Bootcamp Course

4. @Configuration

It is used as a source of bean definitions. It is a class-level annotation.

public class Bus

@BeanBus engine()

return new Bus();

The configuration annotation represents the class having one or more @Bean methods. The spring container could go ahead and generate the Spring Beans to be used.

@Configuration is regarded as one of the basic annotations in Spring Boot . It is fundamental for defining bean configurations in a concise and programmatic manner. When a class is annotated with @Configuration, it signifies that this class serves as a source of bean definitions, particularly by including one or more @Bean methods within the class.

Explore our Popular Software Engineering Courses

5. @controller.

Among all Spring Boot annotations in Java , @Controller is regarded as one of the most important annotations in Spring Boot. 

The annotation is used to indicate that the class is a web request handler. It is often used to present web pages. It is most commonly used with @RequestMapping annotation. 

The @Controller annotation indicates that the class serves the controller role, playing a pivotal role in handling web requests. By marking a class with @Controller, developers explicitly state that this class is responsible for processing HTTP requests and often involves the presentation of web pages. 

This annotation is frequently paired with the @RequestMapping annotation to define the URL patterns that map to specific methods within the controller.

@RequestMapping(“cars”)

public class CarsController

@RequestMapping(value= “/{name}”, method= RequestMethod.GET)

public Employee getCarsByName()

Return carsTemplate;

The controller annotation indicates the class serves the role of a controller. The controller annotation is a specialisation of the component annotation where it is auto-detected through the classpath scanning.

This means that Spring Boot, during its component scanning process, identifies classes annotated with @Controller and registers them as components, making them accessible for handling web requests in the application.

In-Demand Software Development Skills

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

6. @RequestMapping

RequestMapping is used to map the HTTP request. It is used with the class as well as the method. It has many other optional elements like consumes, name, method, request, path, etc.

public class FlowersController

@RequestMapping (“/red-colour/flowers”)

public String getAllFlowers(Model model)

//application code

return “flowerlist”;

It is one of the most used annotations in Spring Boot and can be applied at both the class and method levels, allowing developers to define URL patterns for handling incoming requests.

In addition to its basic functionality, @RequestMapping offers a range of optional elements that enhance its flexibility and customization. 

Also visit upGrad’s Degree Counselling page for all undergraduate and postgraduate programs.

7. @Autowired

This annotation is used to auto-wire spring bean on setter methods, constructor and instance variable. It injects object dependency implicitly. When we use this annotation, the spring container auto-wires the bean by its matching data type.

public class Employee

private Person person;

public Employee(Person person)

this.person=person

The Autowired annotation is used to inject the dependency in the bean. The Autowired provides more control to the developers over where the Autowire should be used.

It offers developers ample control and flexibility to dictate where and how it should be applied within their application. Additionally, it enhances code readability and maintainability. This makes it easier for them to manage and understand the dependency injection process in a Spring Boot application.

Also Read:  Spring Developer Salary in India

8. @Component

@Component is also regarded as one of the most used annotations in Spring Boot. 

It is a class-level annotation that turns the class into Spring bean at the auto-scan time.

Public class Teachers

The component annotation can automatically detect custom beans. It represents that the framework could autodetect these classes for dependency injection.

This annotation serves as a key component in Spring’s component scanning mechanism. This autodetection capability significantly simplifies the configuration process, enabling developers to focus on the core functionalities of their classes rather than explicitly registering each bean. 

It promotes a convention-over-configuration approach, where the framework autonomously identifies and manages custom beans. This contributes to Spring Boot applications’ overall modularity and maintainability, aligning with the framework’s emphasis on simplicity and ease of development.

9. @SpringBootApplication

It consists of @Configuration, @ComponentScan, and @EnabeAutoConfiguration. The class annotated with @SpringBootApplication is kept in the base package. This annotation does the component scan. However, only the sub-packages are scanned. 

The SpringBoot Application mark a configuration class that declares Bean methods, either one or more than that. The Spring Boot Application contains-

  • Auto-configuration – The @EnableAutoConfiguration annotation is a core component of @SpringBootApplication. It triggers Spring Boot’s auto-configuration mechanism, which automatically configures the application based on the dependencies present in the classpath. Auto-configuration aims to reduce the need for explicit configuration by providing sensible defaults, making it easier for developers to get started with Spring Boot projects.
  • Spring Boot Configuration – The @SpringBootConfiguration annotation is synonymous with @Configuration and indicates that the annotated class contains configuration methods. Configuration methods, marked with @Bean, define and configure beans in the Spring application context. This annotation is essential for organizing and centralizing the configuration of the application.
  • Component Scan – The @ComponentScan annotation automatically discovers and registers Spring components within specified packages, such as controllers, services, and repositories. By default, it scans the class package annotated with @SpringBootApplication, making all components in that package and its sub-packages available for dependency injection. Component scanning enhances modularity and allows for the seamless integration of Spring components without explicit configuration.

10. @EnableAutoConfiguration

It’s one of the most important annotations in Spring Boot that simplifies application context initialization and setup by automating configuration based on classpath settings and added dependencies.

It is placed on the main application class. Based on classpath settings, other beans, and various property settings, this annotation instructs SpringBoot to start adding beans.

The Enable Auto Configuration allows the spring boot to auto-figure the application context. The applications are auto figured basis the added jar dependencies.

This annotation eliminates the need for extensive manual configuration, enabling developers to leverage sensible defaults and conventions. The auto-configuration mechanism is a key feature of Spring Boot, facilitating rapid development and reducing the burden of explicit bean definitions.

11. @ComponetScan

It is used to scan a package of beans. It is used with the annotation @Configuration to allow Spring to know the packages to be scanned for annotated components. This annotation is also used to specify base packages.

@ComponentScan(basePackages = “com.xyz”)

Public class ScanComponent

The component scan annotation specifies the packages the developers want to scan. The component scan annotations specify the packages and sub-packages that are supposed to be scanned.

The @ComponentScan annotation becomes particularly useful when developers want to pinpoint specific packages or sub-packages for scanning. This specificity ensures that only the intended portions of the application are scanned for components, contributing to a more organized and efficient application structure.

In essence, @ComponentScan empowers developers to dictate the packages to be scanned, providing fine-grained control over component discovery and registration within the Spring context. This annotation aligns with Spring Boot’s convention-over-configuration approach, offering a straightforward means of configuring component scanning based on developers’ preferences and application architecture.

12. @Required

This annotation is applied to bean setter methods. It indicates that the required property must be filled at the configuration time in the affected bean, or else it throws an exception: BeanInitializationException.

This annotation, used on bean setter methods, mandates that a required property must be filled during configuration. The BeanInitializationException emphasizes the essential nature of the property for proper bean initialization.

13. @Qualifier

It is used along with @Autowired annotation. It is used when more control is required over the dependency injection process. Individual constructor arguments or method parameters can be specified by using this annotation. Confusion arises when more than one bean of the same type is created, and only one of them is to be wired with a property, @Qualifier is used to get rid of the confusion.

The @Qualifier annotation, used with @Autowired, provides precise control over dependency injection. By applying it to constructor arguments or method parameters, developers can explicitly specify the bean to be injected.

This is crucial when multiple beans of the same type exist, and clarity is needed to identify the specific bean to be wired with a property. @Qualifier resolves this ambiguity, ensuring the correct bean is used for the intended purpose.

14. @CookieValue

It is used at the method parameter level as an argument of the request mapping method. For a given cookie name, the HTTP cookie is bound to a @CookieValue parameter.

The cookie value annotation is used to get the value of any HTTP cookie. Cookies in spring boot are used to show the personalised content to the users and they can be retrieved using the cookie value annotation.

This annotation simplifies the extraction of specific cookie values from incoming HTTP requests. When applied to a method parameter, it allows developers to easily access the value of a particular cookie by specifying its name. This is especially useful when cookies customize user experiences, enabling developers to retrieve and use cookie values for personalized content or functionality in a Spring Boot application.

It is used in the component class. At startup, all auto-wired dependencies are created and configured. But a @Lazy annotation can be created if a bean is to be initialized lazily. This means that only if it is requested for a bean will be created. It can also be used on @Configuartion classes. It’s an indication that all @Bean methods within that @Configuration should be lazily initialized.

When applied at the class level in a configuration class, it signals that all @Bean methods within that configuration should follow a lazy initialization strategy. This flexibility allows developers to fine-tune the initialization behavior in a Spring Boot application based on specific use cases and resource considerations.

Check out: Spring Bean Life Cycle Explained

Learn  Software Engineering Courses online  from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

Spring Boot has made it easy for Java developers to create Spring applications with ease. As a Java enthusiast or a professional, you should be aware of the basic Spring boot annotations . We hope that this blog helped you understand them. You can take the first step towards a successful Java career by enrolling for u pGrad and IIIT-B’s Executive PG Program in Full Stack Development .

These annotations serve as powerful tools for streamlining the development process, providing a concise and expressive way to configure, manage dependencies, and handle various aspects of your application. By mastering these annotations, you enhance your proficiency in Spring Boot and unlock the full potential of the framework, enabling you to build robust and efficient Java applications. 

Profile

Something went wrong

Our Trending Software Engineering Courses

  • Master of Science in Computer Science from LJMU
  • Executive PG Program in Software Development Specialisation in Full Stack Development from IIIT-B
  • Advanced Certificate Programme in Cyber Security from IIITB
  • Full Stack Software Development Bootcamp
  • Software Engineering Bootcamp from upGrad

Our Popular Software Engineering Courses

Full Stack Development

Popular Software Development Skills

  • React Courses
  • Javascript Courses
  • Core Java Courses
  • Data Structures Courses
  • ReactJS Courses
  • NodeJS Courses
  • Blockchain Courses
  • SQL Courses
  • Full Stack Development Courses
  • Big Data Courses
  • Devops Courses
  • NFT Courses
  • Cyber Security Courses
  • Cloud Computing Courses
  • Database Design Courses
  • Crypto Courses
  • Python Courses

Frequently Asked Questions (FAQs)

Java annotations are the metadata, i.e. data about data, of the source code of the program. Annotations are used to supply extra information to the compiler about a Java program. However, these are not a part of the Java program and do not, in any way, influence the program execution. Java annotations start with @. For example, the @Override annotation is used to signal the compiler that the specified method marked with that annotation should override the method contained in the superclass with the same name, parameter list and return type. There are different kinds of formats for annotations used in Java.

Spring Boot is an open-source Java framework that is used to create microservices. On the other hand, Spring Cloud is a technology for configuration server that is used to centralize and manage configuration. Spring Cloud is also implemented to ensure the security of applications running on Spring Boot in many cases. By default, Spring Boot implements Spring features and can quickly execute standalone Spring web-based applications. Spring Cloud offers the platform to develop cloud services; its architecture is based on the Spring Boot model. Spring Boot is adopted for unit testing and reducing the time needed for integration testing.

Spring in Java is an open-source framework that offers the platform to develop Java applications. Programs written using Java are generally very complex and come with various components that make them heavyweight. Spring is a lightweight, low-cost and secure framework that offers the flexibility needed to develop complex programs and enhance the overall efficiency of execution. Spring also optimizes the overall time taken for developing Java applications and eliminates tedious tasks related to the configuration so that programmers can focus their attention on the business logic of applications. The core logic of the Spring framework is dependency injection that allows developers to create decoupled architecture. This framework facilitates the development of high-performing Java applications.

Related Programs View All

spring boot annotation list

Executive PG Certification

GenAI integrated curriculum

View Program

spring boot annotation list

Executive PG Program

IIIT-B Alumni Status

spring boot annotation list

Master's Degree

40000+ Enrolled Learners

spring boot annotation list

Job Assistance

spring boot annotation list

Certification

Top-Notch AWS Trainers

Mix of classroom and practicals

159+ Hours of Live Sessions

spring boot annotation list

126+ Hours of Live Sessions

Fully Online

Practice Assignments & MCQs

spring boot annotation list

2 Unique Specialisations

300+ Hiring Partners

Mock Tests, Assessments and More

24 Hours Live Online Training

32 Hands-On Exercises

Real-World Simulations, Cloud Labs

Microsoft-Approved Curriculum

3 Live Projects to Fortify Learning

spring boot annotation list

40 Hours Instructor-Led Sessions

Exam Support

Logo

DevOps Certified

Explore Free Courses

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in Canada through this course.

Marketing

Advance your career in the field of marketing with Industry relevant free courses

Data Science & Machine Learning

Build your foundation in one of the hottest industry of the 21st century

Management

Master industry-relevant skills that are required to become a leader and drive organizational success

Technology

Build essential technical skills to move forward in your career in these evolving times

Career Planning

Get insights from industry leaders and career counselors and learn how to stay ahead in your career

Law

Kickstart your career in law by building a solid foundation with these relevant free courses.

Chat GPT + Gen AI

Stay ahead of the curve and upskill yourself on Generative AI and ChatGPT

Soft Skills

Build your confidence by learning essential soft skills to help you become an Industry ready professional.

Study Abroad Free Course

Learn more about the education system, top universities, entrance tests, course information, and employment opportunities in USA through this course.

Suggested Blogs

Learn About Static Variable in C [With Coding Example]

by Rohan Vats

12 Feb 2024

Top 21 MEAN Stack Developer Interview Questions &#038; Answers For Beginners &#038; Experienced

by Kechit Goyal

10 Feb 2024

PHP Array Length: How to Find Array Length in PHP [With Examples]

09 Feb 2024

JSP vs Servlet: Difference Between JSP &#038; Servlet [2024]

04 Feb 2024

17 Interesting Java Project Ideas &#038; Topics For Beginners 2023 [Latest]

28 Jan 2024

Top 20 Project Ideas in C++ For Beginners [2023]

JavaTechOnline

Making java easy to learn, spring boot annotations with examples.

  • Spring Boot

Last Updated on December 24th, 2023

Spring Boot Annotations With Examples

Here in this article on ‘Spring Boot Annotations With Examples’, we will discuss about all annotations that we use in a Spring Boot Application. Annotations which are not part of this article, will be included in other respective articles. Link will be provided here only for easy navigation. In addition, you can also check one more article ‘ Annotations in Java ‘ in order to know annotation basics and how to create custom annotations in Java. Let’s start discussing our topic ‘Spring Boot Annotations With Examples’.

Table of Contents

Annotation Basics

Before discussing about ‘Spring Boot Annotations With Examples’, let’s first talk about some basic terminologies used during the explanation of annotations.

What is The IoC container?

In a nutshell, the IoC is a container that injects dependencies while creating the bean. IoC stands for ‘Inversion Of Control’. Instead of creating objects by the developer, the bean itself controls the instantiation or association of its dependencies by using direct construction of classes with the help of the IoC container. Hence, this process is known as ‘Inversion of control’. Sometimes we also call it Spring Container in short.

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container . ApplicationContext is a sub-interface of BeanFactory.

What is an Application Context in Spring Framework?

When you create a project in Spring or Spring Boot, a container or wrapper gets created to manage your beans. This is nothing but Application Context. However Spring supports two containers : Bean Factory and Application Context. In short, the BeanFactory provides the configuration framework and basic functionality. On the other hand, ApplicationContext adds more enterprise-specific functionality including easier integration with Spring’s AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications. The ApplicationContext is a complete superset of the BeanFactory and is used exclusively in this topic in descriptions of Spring’s IoC container . Spring Framework recommends to use Application Context to get the full features of the framework. Moreover, Dependency injection and auto-wiring of beans is done in Application Context.

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and it manages the process of instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata can be represented in three formats: XML, Java annotations, or Java code. Since this is out of our topic ‘Spring Boot Annotations With Examples’, we have discussed about this in detail in a separate article ‘ Spring Core Tutorial ‘.

What is Spring Bean or Components?

During Application startup, Spring instantiates objects and adds them to the Application Context(IoC container). These objects in the Application Context are called ‘Spring Beans’ or ‘Spring Components’. As they are managed by Spring, therefore we also call them Spring-managed Bean or Spring-managed Component.

What is Component Scanning?

The process of discovering classes that can contribute to the Application Context, is called Component Scanning. During Component Scanning, if Spring finds a class annotated with a particular annotation, It will consider this class as a candidate for Spring Bean/Component and adds it to the Application Context. Spring explicitly provides a way to identify Spring bean candidates via the @ComponentScan annotation.

When to use Component Scanning in a Spring Boot Application?

By default, the  @ComponentScan annotation will scan for components in the current package and its all sub-packages. If it is a Spring Boot application, then all the packages under the package containing the Main class (a class annotated with @SpringBootApplication ) will be covered by an implicit component scan. So if your package doesn’t come under the hierarchy of the package containing the Main class, then there is a need for explicit component scanning.

Spring Annotations vs Spring Boot Annotations

As we know that Spring Boot Framework is created using libraries of the Spring Framework and removed the XML configuration approach. However, all the Spring Framework’s annotations are still applicable for Spring Boot. Furthermore, Spring Boot has provided some additional annotations which are specific to Spring Boot only. In some cases, Spring Boot created annotations after adding more than one annotations of the Spring Framework. Here, we will learn most commonly used annotations under our topic of discussion ‘Spring Boot Annotations With Examples’, whether it is a part of Spring Framework or Spring Boot.

Annotations that Supports to create a Spring Bean

Let’s start discussing our topic ‘Spring Boot Annotations with Examples’ with the annotations to create a Bean. Needless to say, we can’t work on Spring Boot/Spring framework without creating a Bean. Now you can imagine how important is that!

Next annotations in our topic ‘Spring Boot Annotations With Examples’ are the stereotype annotations.

@Component 

@Complonent annotation is also an important & most widely used at the class level. This is a generic stereotype annotation which indicates that the class is a Spring-managed bean/component. @Component is a class level annotation. Other stereotypes are a specialization of @Component . During the component scanning, Spring Framework automatically discovers the classes annotated with @Componen t, It registers them into the Application Context as a Spring Bean. Applying @Component annotation on a class means that we are marking the class to work as Spring-managed bean/component. For example, observe the code below:

On writing a class like above, Spring will create a bean instance with name ‘myBean’. Please keep in mind that, By default, the bean instances of this class have the same name as the class name with a lowercase initial. However, we can explicitly specify a different name using the optional argument of this annotation like below.

@Controller 

@Controller tells Spring Framework that the class annotated with @Controller will work as a controller in the Spring MVC project.

@RestControlle r

@RestController tells Spring Framework that the class annotated with @RestController will work as a controller in a Spring REST project.

@Service tells Spring Framework that the class annotated with @Service is a part of service layer and it will include business logics of the application.

@Repository

@Repository tells Spring Framework that the class annotated with @Repos itory is a part of data access layer and it will include logics of accessing data from the database in the application.

Apart from Stereotype annotations, we have two annotations that are generally used together: @Configuration & @Bean.

@Configuration 

We apply this annotation on classes. When we apply this to a class, that class will act as a configuration by itself. Generally the class annotated with @Configuration has bean definitions as an alternative to <bean/> tag of an XML configuration. It also represents a configuration using Java class. Moreover the class will have methods to instantiate and configure the dependencies. For example :

♥ The benefit of creating an object via this method is that you will have only one instance of it. You don’t need to create the object multiple times when required. Now you can call it anywhere in your code.

This is the basic annotation and important for our topic ‘Spring Boot Annotations With Examples’.

We use @Bean at method level. If you remember the xml configuration of a Spring, It is a direct analog of the XML <bean/> element. It creates Spring beans and generally used with @Configuration . As aforementioned, a class with @Configuration (we  can call it as a Configuration class) will have methods to instantiate objects and configure dependencies. Such methods will have @Bean annotation.

By default, the bean name will be the same as the method name. It instantiates and returns the actual bean. The annotated method produces a bean managed by the Spring IoC container. For example:

For the sake of comparison, the configuration above is exactly equivalent to the following Spring XML:

The annotation supports most of the attributes offered by <bean/>, such as:  init-method ,  destroy-method ,  autowiring ,  lazy-init ,  dependency-check ,  depends-on  and  scope .

@Bean vs @Component

@ Component  is a class level annotation whereas @ Bean  is a method level annotation and name of the method serves as the  bean name. @ Bean annotation has to be used within the class and that class should be annotated with @ Configuration . However, @Component needs not to be used with the @Configuration . @Component  auto detects and configures the beans using classpath scanning, whereas @Bean explicitly declares a single bean, rather than letting Spring do it automatically.

Configuration Annotations

Next annotations in our article ‘Spring Boot Annotations with Examples’ are for Configurations. Since Spring Framework is healthy in configurations, we can’t avoid learning annotations on configurations. No doubt, they save us from complex coding effort.

@ComponentScan

Spring container detects Spring managed components with the help of @ComponentScan . Once you use this annotation, you tell the Spring container where to look for Spring components. When a Spring application starts, Spring container needs the information to locate and register all the Spring components with the application context. However It can auto scan all classes annotated with the stereotype annotations such as @Component, @Controller, @Service , and @Repository  from pre-defined project packages.

The @ComponentScan annotation is used with the @Configuration annotation to ask Spring the packages to scan for annotated components. @ComponentScan is also used to specify base packages and base package classes using basePackages or  basePackageClasses attributes of @ComponentScan . For example :

Here the @ComponentScan annotation uses the basePackages attribute to specify three packages including their subpackages that will be scanned by the Spring container. Moreover the annotation also uses the basePackageClasses attribute to declare the Bean1 class, whose package Spring Boot will scan.

Moreover, In a Spring Boot project, we typically apply the @SpringBootApplication annotation on the main application class. Internally, @SpringBootApplication is a combination of the @Configuration, @ComponentScan, and @EnableAutoConfiguration annotations. Further, with this default setting, Spring Boot will auto scan for components in the current package (containing the SpringBoot main class) and its sub packages.

Suppose we have multiple Java configuration classes annotated by @Configuration . @Import imports one or more Java configuration classes. Moreover, it has the capability to group multiple configuration classes. We use this annotation where one @Configuration  class logically  imports  the bean definitions defined by another. For example:

@PropertySource 

If you create a Spring Boot Starter project using an IDE such as STS , application.properties comes under resources folder by default. In contrast, You can provide the name & location of the properties file (containing the key/value pair) as per your convenience by using @PropertySource . Moreover, this annotation provides a convenient and declarative mechanism for adding a PropertySource to Spring’s Environment. For example,

@PropertySources (For Multiple Property Locations)

Of course, If we have multiple property locations in our project, we can also use the @PropertySources annotation and specify an array of @PropertySource .

However, we can also write the same code in another way as below. The @PropertySource annotation is repeatable according to Java 8 conventions. Therefore, if we’re using Java 8 or higher, we can use this annotation to define multiple property locations. For example:

♥ Note : If there is any conflict in names such as the same name of the properties, the last source read will always take precedence.

We can use this annotation to inject values into fields of Spring managed beans. We can apply it at field or constructor or method parameter level. For example, let’s first define a property file, then inject values of properties using @Value.

Now inject the value of server.ip using @Value as below:

@Value for default Value

Suppose we have not defined a property in the properties file. In that case we can provide a default value for that property. Here is the example:

Here, the value Admin will be injected for the property emp.department . However, if we have defined the property in the properties file, the value of property file will override it.

♥ Note : If the same property is defined as a system property and also in the properties file, then the system property would take preference.

@Value for multiple values

Sometimes, we need to inject multiple values of a single property. We can conveniently define them as comma-separated values for the single property in the properties file. Further, we can easily inject them into property that is in the form of an array. For example:

Spring Boot Specific Annotations

Now it’s time to extend our topic ‘Spring Boot Annotations with Examples’ with Spring Boot Specific Annotations. They are discovered by Spring Boot Framework itself. However, most of them internally use annotations provided by Spring Framework and extend them further.

@SpringBootApplication (@Configuration + @ComponentScan + @EnableAutoConfiguration)

Everyone who worked on Spring Boot must have used this annotation either intentionally or unintentionally. When we create a Spring Boot Starter project using an IDE like STS, we receive this annotation as a gift. This annotation applies at the main class which has main () method. The Main class serves two purposes in a Spring Boot application: configuration  and  bootstrapping .

In fact @SpringBootApplication is a combination of three annotations with their default values. They are @Configuration, @ComponentScan, and @EnableAutoConfiguration. Therefore, we can also say that @SpringBootApplication is a 3-in-1 annotation. This is an important annotation in the context of our topic ‘Spring Boot Annotations With Examples’.

@EnableAutoConfiguration : enables the auto-configuration feature of Spring Boot. @ComponentScan : enables @Component scan on the package to discover and register components as beans in Spring’s application Context. @Configuration : allows to register extra beans in the context or imports additional configuration classes.

We can also use above three annotations separately in place of @SpringBootApplication if we want any customized behavior of them.

@EnableAutoConfiguration

@EnableAutoConfiguration enables auto-configuration of beans present in the classpath in Spring Boot applications. In a nutshell, this annotation enables Spring Boot to auto-configure the application context. Therefore, it automatically creates and registers beans that are part of the included jar file in the classpath and also the beans defined by us in the application. For example, while creating a Spring Boot starter project when we select Spring Web and Spring Security dependency in our classpath, Spring Boot auto-configures Tomcat, Spring MVC and Spring Security for us.

Moreover, Spring Boot considers the package of the class declaring the @EnableAutoConfiguration as the default package. Therefore, if we apply this annotation in the root package of the application, every sub-packages & classes will be scanned. As a result, we won’t need to explicitly declare the package names using @ComponentScan .

Furthermore, @EnableAutoConfiguration provides us two attributes to manually exclude classes from auto-configurations. If we don’t want some classes to be auto-configured, we can use exclude attribute to disable them. Another attribute is excludeName to declare a fully qualified list of classes to exclude. For example, below are the codes.

Use of ‘exclude’ in @EnableAutoConfiguration  

Use of ‘excludename’ in @enableautoconfiguration  , @springbootconfiguration.

This annotation is a part of Spring Boot Framework. However, @SpringBootApplication inherits from it. Therefore, If an application uses  @SpringBootApplication , it is already using  @SpringBootConfiguration . Moreover, It acts as an alternative to the @Configuration annotation. The primary difference is that @SpringBootConfiguration allows configuration to be automatically discovered. @SpringBootConfiguration indicates that the class provides configuration and also applied at the class level . Particularly, this is useful in case of unit or integration tests. For example, observe the below code:

@ConfigurationProperties

Spring Framework provides various ways to inject values from the properties file. One of them is by using @Value annotation. Another one is by using @ConfigurationProperties on a configuration bean to inject properties values to a bean. But what is the difference among both ways and what are the benefits of using @ConfigurationProperties , you will understand it at the end. Now Let’s see how to use  @ConfigurationProperties annotation to inject properties values from the application.properties or any other properties file of your own choice.

First, let’s define some properties in our application.properties file as follows. Let’s assume that we are defining some properties of our development working environment. Therefore, representing properties name with prefix ‘dev’.

Now, create a bean class with getter and setter methods and annotate it with @ConfigurationProperties.

Here, Spring will automatically bind any property defined in our property file that has the prefix ‘ dev’ and the same name as one of the fields in the MyDevAppProperties class.

Next, register the @ConfigurationProperties  bean in your  @Configuration class using the @EnableConfigurationProperties  annotation.

Finally create a Test Runner to test the values of properties as below.

We can also use the  @ConfigurationProperties  annotation on  @Bean -annotated methods.

@EnableConfigurationProperties

In order to use a configuration class in our project, we need to register it as a regular Spring bean. In this situation @EnableConfigurationProperties annotation support us. We use this annotation to register our configuration bean (a @ConfigurationProperties annotated class) in a Spring context . This is a convenient way to quickly register @ConfigurationProperties annotated beans. Moreover, It is strictly coupled with @ConfiguratonProperties . For example, you can refer @ConfigurationProperties from the previous section.

@EnableConfigurationPropertiesScan

@EnableConfigurationPropertiesScan  annotation scans the packages based on the parameter value passed into it and discovers all classes annotated with @ConfiguratonProperties under the package . For example, observe the below code:

From the above example, @EnableConfigurationPropertiesScan will scan all the @ConfiguratonProperties annotated classes under the package “com.dev.spring.test.annotation” and register them accordingly.

@EntityScan and @EnableJpaRepositories

Spring Boot annotations like @ComponentScan , @ConfigurationPropertiesScan  and even @SpringBootApplication use packages to define scanning locations. Similarly @EnityScan and @EnableJpaRepositories also use packages to define scanning locations. Here, we use @EntityScan for discovering entity classes, whereas @EnableJpaRepositories for JPA repository classes by convention . These annotations are generally used when your discoverable classes are not under the root package or its sub-packages of your main application.

Remember that, @EnableAutoConfiguration( as part of @SpringBootApplication) scans all the classes under the root package or its sub-packages of your main application. Therefore, If the repository classes or other entity classes are not placed under the main application package or its sub package, then the relevant package(s) should be declared in the main application configuration class with @EntityScan and @EnableJpaRepositories annotation accordingly. For example, observe the below code:

Links to Other Annotations

As stated in the introduction section of our article ‘Spring Boot Annotations With Examples’, we will discuss all annotations that we generally use in a Spring Boot web Application. Below are the links to continue with ‘Spring boot Annotations with Examples’:

1) Spring Boot Bean Annotations With Examples

2) spring boot mvc & rest annotations with examples, 3) spring boot security annotations with examples, 4) spring boot scheduling annotations with examples, 5) spring boot transactions annotations with examples, 6) spring boot errors, exceptions and aop annotations with examples, 6) spring cloud annotations with examples, where can we use annotations.

Apart from learning ‘Spring Boot Annotations With Examples’, its also important to know what are places to apply annotations.

We can apply annotations to the declarations of different elements of a program such as to the declarations of classes, fields, methods, and other program elements. By convention, we apply them just before the declaration of the element. Moreover, as of the Java 8 release, we can apply annotations to the use of types. For example, below code snippets demonstrate the usage of annotations:

1) Class instance creation expression

2) type cast, 3) implements clause, 4) thrown exception declaration.

This form of annotation is called a  type annotation. For more information, see  Type Annotations and Pluggable Type Systems .

However, these annotations are not in tradition at present, but in the future we can see them in the code. Since we are discussing about ‘Spring Boot Annotations With Examples’, we need to at least have the basic idea of them.

spring boot annotation list

5 thoughts on “ Spring Boot Annotations With Examples ”

  • Pingback: Spring Boot Errors and AOP Annotations With Examples | Making Java easy to learn
  • Pingback: Spring Boot Security-Scheduling-Transactions Annotations With Examples | Making Java easy to learn
  • Pingback: Spring Boot MVC & REST Annotations With Examples | Making Java easy to learn
  • Pingback: Spring Boot Bean Annotations With Examples | Making Java easy to learn

Thanks for your best article

Leave a Reply Cancel reply

Insert/edit link.

Enter the destination URL

Or link to existing content

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Spring Boot basic annotations

last modified August 2, 2023

In this article we show how to use basic Spring Boot annotations including @Bean, @Service, @Configuration, @Controller, @RequestMapping, @Repository, @Autowired, and @SpringBootApplication.

Spring is a popular Java application framework for creating enterprise applications. Spring Boot is the next step in evolution of Spring framework. It helps create stand-alone, production-grade Spring based applications with minimal effort. It does not use XML configurations anymore and implements the convention over configuration principle.

Annotation is a form of metadata which provides data about a program that is not part of the program itself. Annotations do not have direct effect on the operation of the code they annotate.

In the example application, we have these Spring Boot annotations:

  • @Bean - indicates that a method produces a bean to be managed by Spring.
  • @Service - indicates that an annotated class is a service class.
  • @Repository - indicates that an annotated class is a repository, which is an abstraction of data access and storage.
  • @Configuration - indicates that a class is a configuration class that may contain bean definitions.
  • @Controller - marks the class as web controller, capable of handling the requests.
  • @RequestMapping - maps HTTP request with a path to a controller method.
  • @Autowired - marks a constructor, field, or setter method to be autowired by Spring dependency injection.
  • @SpringBootApplication - enables Spring Boot autoconfiguration and component scanning.

@Component is a generic stereotype for a Spring managed component. It turns the class into a Spring bean at the auto-scan time. Classes decorated with this annotation are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. @Repository , @Service , and @Controller are specializations of @Component for more specific use cases.

There are also Hibernate @Entity , @Table , @Id , and @GeneratedValue annotations in the example.

Spring Boot basic annotations example

The following application is a Spring Boot application which returns data from an H2 database using Spring Data JPA. The application uses FreeMarker as a template engine.

This is the project structure.

This is the Gradle build file. It contains dependencies for Freemaker, Spring Data JPA, and H2 database. When Spring Boot finds Freemaker and H2 in the build file, it automatically configures them. We can use them right away.

In the application.yml file we write various configuration settings of a Spring Boot application.

This is the City entity. Each entity must have at least two annotations defined: @Entity and @Id . The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping. The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides for the specification of generation strategies for the values of primary keys.

The schema is automatically created by Hibernate; later, the import.sql file is executed to fill the table with data.

The @Repository annotation is used to define a repository.

ICityService provides a contract method to get all cities.

The @Service annotation declares CityService to be a service class: a class that provides business services. The optional @Autowired annotation marks cityRepository field to be injected with CityRepository .

The @Controller annotation marks a class as a web controller. The @RequestMapping maps HTTP request with a path to a controller method. In the second case, it maps the /cities URL to the showCities method.

This is the index.ftlh template file. It contains a link to create a request to show all cities.

This is the showCities.ftlh template file. It uses FreeMarker #list macro to display all city objects.

This is the style.css template file.

The @SpringBootApplication enables auto-configuration and component scanning.

We run the application and locate to the localhost:8080/myapp address.

In this article we have covered a few basic Spring Boot annotations.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Spring Boot tutorials .

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Curated list of frequently used annotations in Spring Boot applications

gindex/spring-boot-annotation-list

Folders and files, repository files navigation, list of frequently used annotations in spring boot apps.

PRs Welcome

This document contains non-comprehensive list of frequently used annotations in Spring Boot applications. It should rather be used as a quick lookup list, for detailed and comprehensive information please read official javadocs and documentation.

Core Spring

Spring boot, spring boot tests, spring test, transactions.

  • Spring JPA & Hibernate

Spring Security

  • @Bean - Annotated method produces a bean managed by the Spring IoC container
  • @Component - Marks annotated class as a bean found by the component-scanning and loaded into the application context
  • @Controller - Marks annotated class as a bean for Spring MVC containing request handler
  • @RestController - Marks annotated class as a @Controller bean and adds @ResponseBody to serialize returned results as messages
  • @Configuration - Marks annotated class as a Java configuration defining beans
  • @Service - Marks annotated class as a bean (as convention usually containing business logic)
  • @Repository - Marks annotated class as a bean (as convention usually providing data access) and adds auto-translation from SQLException to DataAccessExceptions
  • @PostConstruct - Annotated method is executed after dependency injection is done to perform initialization
  • @PreDestroy - Annotated method is executed before the bean is destroyed, e.g. on the shutdown

Configuration

  • @Import - Imports one or more Java configuration classes @Configuration
  • @PropertySource - Indicates the location of applicaiton.properties file to add key-value pairs to Spring Environment
  • @Value - Annotated fields and parameters values will be injected
  • @ComponentScan - Configures component scanning @Compenent , @Service , etc.

Bean properties

  • @Lazy - Annotated bean will be lazily initialized on the first usage
  • @Profile - Indicates that beans will be only initialized if the defined profiles are active
  • @Scope - Defines bean creation scope, e.g. prototype, singleton, etc.
  • @DependsOn - Explicitly defines a dependency to other beans in terms of creation order
  • @Order - Defines sorting order if injecting a list of beans, but it does not resolve the priority if only a single bean is expected
  • @Primary - Annotated bean will be picked if multiple beans can be autowired
  • @ConditionalOnBean
  • @ConditionalOnMissingBean
  • @ConditionalOnClass
  • @ConditionalOnMissingClass
  • @ConditionalOnProperty
  • @ConditionalOnMissingProperty

Bean injection

  • @Autowired - Beans are injected into annotated setters, fields, or constructor params.
  • @Qualifier - Specifies the name of a bean as an additional condition to identify a unique candidate for autowiring
  • @Valid - Mark a property, method parameters or return type for validation
  • @Validated - Variant of @Valid that allows validation of multiple groups, e.g. all fields of an annotated class
  • @NotNull - Must be not null
  • @NotEmpty - Must be not null nor empty
  • @NotBlank - Must be not null and at least one non-whitespace character
  • @Digits - Must be a number within accepted range
  • @Past - Must be an instant, date or time in the past
  • @Future - Must be an instant, date or time in the future
  • @SpringBootConfiguration - Indicates Spring Boot application @Configuration
  • @EnableAutoConfiguration - Enables application context auto-configuration to provide possibly needed beans based on the classpath
  • @ConfigurationProperties - Provides external binding of key value properties
  • @ConstructorBinding - Bind properties by using constructor rather than setters
  • @ConfigurationPropertiesScan - Enables auto-detection of @ConfigurationProperties classes
  • @SpringBootApplication - Combination of @SpringBootConfiguration , @EnableAutoConfiguration , @ConfigurationPropertiesScan and @ComponentScan
  • @EntityScan - Configures base packages to scan for entity classes
  • @EnableJpaRepositories - Enables auto-configuration of jpa repositories
  • @SpringBootTest - Annotated test class will load the entire application context for integration tests
  • @WebMvcTest - Annotated test class will load only the web layer (service and data layer are ignored)
  • @DataJpaTest - Annotated class will load only the JPA components
  • @JsonTest - Annotated class will load only json mapper for serialization and deserialization tests
  • @MockBean - Marks annotated field as a mock and loads it as a bean into the application context
  • @SpyBean - Allows partial mocking of beans
  • @Mock - Defines annotated field as a mock
  • @ContextConfiguration - Defines @Configuration to load application context for integration test
  • @ExtendWith - Defines extensions to execute the tests with, e.g. MockitoExtension
  • @SpringJUnitConfig - Combines @ContextConfiguration and @ExtendWith(SpringExtension.class)
  • @TestPropertySource - Defines the location of property files used in integration tests
  • @DirtiesContext - Indicates that annotated tests dirty the application context and will be cleaned after each test
  • @ActiveProfiles - Defines which active bean definition should be loaded when initializing the test application context
  • @Sql - Allows defining SQL scripts and statements to be executed before and after tests
  • @EnableTransactionManagement - Enables annotation-driven transaction declaration @Transactional
  • @Transactional - Annotated methods will be executed in a transactional manner

Spring JPA and Hibernate

  • @Id - Marks annotated field as a primary key of an entity
  • @GeneratedValue - Provides generation strategy of primary keys
  • @Entity - Marks annotated class as an entity
  • @Column - Provides additional configuration for a field, e.g. column name
  • @Table - Provides additional configuration for an entity, e.g. table name
  • @PersistenceContext - EntityManger is injected into annotated setters and fields
  • @Embedded - Annotated field is instantiated as a value of an Embeddable class
  • @Embeddable - Instances of an annotated class are stored as part of an entity
  • @EmbeddedId - Marks annotated property as a composite key mapped by an embeddable class
  • @AttributeOverride - Overrides the default mapping of a field
  • @Transient - Annotated field is not persistent
  • @CreationTimestamp - Annotated field contains the timestamp when an entity was stored for the first time
  • @UpdateTimestamp - Annotated field contains the timestamp when an entity was updated last time
  • @ManyToOne - Indicates N:1 relationship, the entity containing annotated field has a single relation to an entity of other class, but the other class has multiple relations
  • @JoinColumn - Indicates a column for joining entities in @ManyToOne or @OneToOne relationships at the owning side or unidirectional @OneToMany
  • @OneToOne - Indicates 1:1 relationship
  • @MapsId - References joining columns of owning side of @ManyToOne or @OneToOne relationships to be the primary key of referencing and referenced entities
  • @ManyToMany - Indicates N:M relationship
  • @JoinTable - Specifies an association using a join table
  • @BatchSize - Defines size to lazy load a collection of annotated entities
  • @FetchMode - Defines fetching strategy for an association, e.g. loading all entities in a single subquery
  • @EnableWebSecurity - Enables web security
  • @EnableGlobalMethodSecurity - Enables method security
  • @PreAuthorize - Defines access-control expression using SpEL, which is evaluated before invoking a protected method
  • @PostAuthorize - Defines access-control expression using SpEL, which is evaluated after invoking a protected method
  • @RolesAllowed - Specifies a list of security roles allowed to invoke protected method
  • @Secured - Java 5 annotation for defining method level security
  • @EnableAspectJAutoProxy - Enables support for handling components marked with @Aspect
  • @Aspect - Declares an annotated component as an aspect containing pointcuts and advices
  • @Before - Declares a pointcut executed before the call is propagated to the join point
  • @AfterReturning - Declares a pointcut executed if the join point successfully returns a result
  • @AfterThrowing - Declares a pointcut executed if the join point throws an exception
  • @After - Declares a pointcut executed if the join point successfully returns a result or throws an exception
  • @Around - Declares a pointcut executed before the call giving control over the execution of the join point to the advice
  • @Pointcut - Externalized definition a pointcut expression

Top Streams

  • IT & Software Certification Courses
  • Engineering and Architecture Certification Courses
  • Programming And Development Certification Courses
  • Business and Management Certification Courses
  • Marketing Certification Courses
  • Health and Fitness Certification Courses
  • Design Certification Courses

Specializations

  • Digital Marketing Certification Courses
  • Cyber Security Certification Courses
  • Artificial Intelligence Certification Courses
  • Business Analytics Certification Courses
  • Data Science Certification Courses
  • Cloud Computing Certification Courses
  • Machine Learning Certification Courses
  • View All Certification Courses
  • UG Degree Courses
  • PG Degree Courses
  • Short Term Courses
  • Free Courses
  • Online Degrees and Diplomas
  • Compare Courses

Top Providers

  • Coursera Courses
  • Udemy Courses
  • Edx Courses
  • Swayam Courses
  • upGrad Courses
  • Simplilearn Courses
  • Great Learning Courses
  • JEE Main 2024
  • JEE Advanced 2024
  • BITSAT 2024
  • View All Engineering Exams
  • Colleges Accepting B.Tech Applications
  • Top Engineering Colleges in India
  • Engineering Colleges in India
  • Engineering Colleges in Tamil Nadu
  • Engineering Colleges Accepting JEE Main
  • Top IITs in India
  • Top NITs in India
  • Top IIITs in India
  • JEE Main College Predictor
  • JEE Main Rank Predictor
  • MHT CET College Predictor
  • AP EAMCET College Predictor
  • TS EAMCET College Predictor
  • KCET College Predictor
  • JEE Advanced College Predictor
  • View All College Predictors
  • JEE Main Question Paper
  • JEE Main Mock Test
  • JEE Main Answer Key
  • JEE Main Syllabus
  • Download E-Books and Sample Papers
  • Compare Colleges
  • B.Tech College Applications
  • JEE Main Result
  • MAH MBA CET Exam
  • View All Management Exams

Colleges & Courses

  • MBA College Admissions
  • MBA Colleges in India
  • Top IIMs Colleges in India
  • Top Online MBA Colleges in India
  • MBA Colleges Accepting XAT Score
  • BBA Colleges in India
  • XAT College Predictor 2024
  • SNAP College Predictor 2023
  • NMAT College Predictor
  • MAT College Predictor 2024
  • CMAT College Predictor 2024
  • CAT Percentile Predictor 2023
  • CAT 2023 College Predictor
  • CMAT 2024 Registration
  • XAT Cut Off 2024
  • XAT Score vs Percentile 2024
  • CAT Score Vs Percentile
  • Download Helpful Ebooks
  • List of Popular Branches
  • QnA - Get answers to your doubts
  • IIM Fees Structure
  • AIIMS Nursing
  • Top Medical Colleges in India
  • Top Medical Colleges in India accepting NEET Score
  • Medical Colleges accepting NEET
  • List of Medical Colleges in India
  • List of AIIMS Colleges In India
  • Medical Colleges in Maharashtra
  • Medical Colleges in India Accepting NEET PG
  • NEET College Predictor
  • NEET PG College Predictor
  • NEET MDS College Predictor
  • DNB CET College Predictor
  • DNB PDCET College Predictor
  • NEET Application Form 2024
  • NEET PG Application Form 2024
  • NEET Cut off
  • NEET Online Preparation
  • Download Helpful E-books
  • LSAT India 2024
  • Colleges Accepting Admissions
  • Top Law Colleges in India
  • Law College Accepting CLAT Score
  • List of Law Colleges in India
  • Top Law Colleges in Delhi
  • Top Law Collages in Indore
  • Top Law Colleges in Chandigarh
  • Top Law Collages in Lucknow

Predictors & E-Books

  • CLAT College Predictor
  • MHCET Law ( 5 Year L.L.B) College Predictor
  • AILET College Predictor
  • Sample Papers
  • Compare Law Collages
  • Careers360 Youtube Channel
  • CLAT 2024 Exam Live
  • CLAT Result 2024
  • AIBE 18 Result 2023
  • SEED Result 2024
  • UCEED Answer Key 2024
  • NIFT Admit Card
  • CEED Answer Key 2024

Animation Courses

  • Animation Courses in India
  • Animation Courses in Bangalore
  • Animation Courses in Mumbai
  • Animation Courses in Pune
  • Animation Courses in Chennai
  • Animation Courses in Hyderabad
  • Design Colleges in India
  • Fashion Design Colleges in Bangalore
  • Fashion Design Colleges in Mumbai
  • Fashion Design Colleges in Pune
  • Fashion Design Colleges in Delhi
  • Fashion Design Colleges in Hyderabad
  • Fashion Design Colleges in India
  • Top Design Colleges in India
  • Free Sample Papers
  • Free Design E-books
  • List of Branches
  • Careers360 Youtube channel
  • NIFT College Predictor
  • IPU CET BJMC
  • JMI Mass Communication Entrance Exam
  • IIMC Entrance Exam
  • Media & Journalism colleges in Delhi
  • Media & Journalism colleges in Bangalore
  • Media & Journalism colleges in Mumbai
  • List of Media & Journalism Colleges in India
  • Free Ebooks
  • CA Intermediate
  • CA Foundation
  • CS Executive
  • CS Professional
  • Difference between CA and CS
  • Difference between CA and CMA
  • CA Full form
  • CMA Full form
  • CS Full form
  • CA Salary In India

Top Courses & Careers

  • Bachelor of Commerce (B.Com)
  • Master of Commerce (M.Com)
  • Company Secretary
  • Cost Accountant
  • Charted Accountant
  • Credit Manager
  • Financial Advisor
  • Top Commerce Colleges in India
  • Top Government Commerce Colleges in India
  • Top Private Commerce Colleges in India
  • Top M.Com Colleges in Mumbai
  • Top B.Com Colleges in India
  • IT Colleges in Tamil Nadu
  • IT Colleges in Uttar Pradesh
  • MCA Colleges in India
  • BCA Colleges in India

Quick Links

  • Information Technology Courses
  • Programming Courses
  • Web Development Courses
  • Data Analytics Courses
  • Big Data Analytics Courses
  • RUHS Pharmacy Admission Test
  • Top Pharmacy Colleges in India
  • Pharmacy Colleges in Pune
  • Pharmacy Colleges in Mumbai
  • Colleges Accepting GPAT Score
  • Pharmacy Colleges in Lucknow
  • List of Pharmacy Colleges in Nagpur
  • GPAT Result
  • GPAT 2024 Admit Card
  • GPAT Question Papers
  • NCHMCT JEE 2024
  • Mah BHMCT CET
  • Top Hotel Management Colleges in Delhi
  • Top Hotel Management Colleges in Hyderabad
  • Top Hotel Management Colleges in Mumbai
  • Top Hotel Management Colleges in Tamil Nadu
  • Top Hotel Management Colleges in Maharashtra
  • B.Sc Hotel Management
  • Hotel Management
  • Diploma in Hotel Management and Catering Technology

Diploma Colleges

  • Top Diploma Colleges in Maharashtra
  • UPSC IAS 2024
  • SSC CGL 2024
  • IBPS RRB 2024
  • Previous Year Sample Papers
  • Free Competition E-books
  • Sarkari Result
  • QnA- Get your doubts answered
  • UPSC Previous Year Sample Papers
  • CTET Previous Year Sample Papers
  • SBI Clerk Previous Year Sample Papers
  • NDA Previous Year Sample Papers

Upcoming Events

  • NDA Application Form 2024
  • UPSC IAS Application Form 2024
  • CDS Application Form 2024
  • CTET Admit card 2024
  • HP TET Result 2023
  • SSC GD Constable Admit Card 2024
  • UPTET Notification 2024
  • SBI Clerk Result 2024

Other Exams

  • SSC CHSL 2024
  • UP PCS 2024
  • UGC NET 2024
  • RRB NTPC 2024
  • IBPS PO 2024
  • IBPS Clerk 2024
  • IBPS SO 2024
  • CBSE Class 10th
  • CBSE Class 12th
  • UP Board 10th
  • UP Board 12th
  • Bihar Board 10th
  • Bihar Board 12th
  • Top Schools in India
  • Top Schools in Delhi
  • Top Schools in Mumbai
  • Top Schools in Chennai
  • Top Schools in Hyderabad
  • Top Schools in Kolkata
  • Top Schools in Pune
  • Top Schools in Bangalore

Products & Resources

  • JEE Main Knockout April
  • NCERT Notes
  • NCERT Syllabus
  • NCERT Books
  • RD Sharma Solutions
  • Navodaya Vidyalaya Admission 2024-25
  • NCERT Solutions
  • NCERT Solutions for Class 12
  • NCERT Solutions for Class 11
  • NCERT solutions for Class 10
  • NCERT solutions for Class 9
  • NCERT solutions for Class 8
  • NCERT Solutions for Class 7
  • Top University in USA
  • Top University in Canada
  • Top University in Ireland
  • Top Universities in UK
  • Top Universities in Australia
  • Best MBA Colleges in Abroad
  • Business Management Studies Colleges

Top Countries

  • Study in USA
  • Study in UK
  • Study in Canada
  • Study in Australia
  • Study in Ireland
  • Study in Germany
  • Study in China
  • Study in Europe

Student Visas

  • Student Visa Canada
  • Student Visa UK
  • Student Visa USA
  • Student Visa Australia
  • Student Visa Germany
  • Student Visa New Zealand
  • Student Visa Ireland
  • CUET PG 2024
  • IGNOU B.Ed Admission 2024
  • DU Admission
  • UP B.Ed JEE 2024
  • DDU Entrance Exam
  • IIT JAM 2024
  • ICAR AIEEA Exam
  • Universities in India 2023
  • Top Universities in India 2023
  • Top Colleges in India
  • Top Universities in Uttar Pradesh 2023
  • Top Universities in Bihar 2023
  • Top Universities in Madhya Pradesh 2023
  • Top Universities in Tamil Nadu 2023
  • Central Universities in India
  • CUET PG Admit Card 2024
  • IGNOU Date Sheet
  • CUET Mock Test 2024
  • CUET Application Form 2024
  • CUET PG Syllabus 2024
  • CUET Participating Universities 2024
  • CUET Previous Year Question Paper
  • ICAR AIEEA Previous Year Question Papers
  • E-Books and Sample Papers
  • CUET Exam Pattern 2024
  • CUET Exam Date 2024
  • CUET Syllabus 2024
  • IGNOU Exam Form 2024
  • IGNOU Result 2023
  • CUET PG Courses 2024

Engineering Preparation

  • Knockout JEE Main 2024
  • Test Series JEE Main 2024
  • JEE Main 2024 Rank Booster

Medical Preparation

  • Knockout NEET 2024
  • Test Series NEET 2024
  • Rank Booster NEET 2024

Online Courses

  • JEE Main One Month Course
  • NEET One Month Course
  • IBSAT Free Mock Tests
  • IIT JEE Foundation Course
  • Knockout BITSAT 2024
  • Career Guidance Tool

Popular Searches

Access premium articles, webinars, resources to make the best decisions for career, course, exams, scholarships, study abroad and much more with

Plan, Prepare & Make the Best Career Choices

Spring Boot Annotations List Everyone Should Know About

In Java development, Spring Boot has emerged as a powerful and widely adopted framework for building robust and scalable applications. One of the key reasons for its popularity is its emphasis on convention over configuration, allowing developers to focus more on business logic and less on boilerplate code. Central to this philosophy are Spring Boot annotations, which play a crucial role in simplifying the development process.

Spring Boot Annotations List Everyone Should Know About

In this article, we will explore what Spring Boot is, understand the significance of spring annotations, and highlight some of the essential annotations that every Spring Boot developer should be familiar with. Consider learning these Java certification courses .

Understanding Spring Boot

Spring Boot is an extension of the Spring framework designed to simplify the process of building production-ready applications with minimal effort. It provides a set of conventions and defaults for common tasks, allowing developers to create stand-alone, production-grade Spring-based applications with little configuration.

Spring Boot eliminates much of the manual setup and boilerplate code associated with traditional Spring development, making it an ideal choice for developers seeking rapid application development.

  • Reverse a String in Java
  • Multithreading in Java: A Comprehensive Guide for Beginners
  • Top 30 Design Patterns Programs in Java, Star, Number and Character

Defining Spring Boot Annotations

Springboot annotations are metadata that provide information about the application's components to the Spring container. They help in configuring and customising the behaviour of the application by marking classes, methods, or fields with special markers. These annotations are processed at compile time or runtime, and they guide the Spring framework in managing various aspects of the application.

  • 20+ Online Courses to Learn ReactJS
  • String Buffer in Java: The Power of Dynamic Strings
  • Top 7 Java Developer Interview Questions and Answers

Importance and Significance of Spring Boot Annotations

Annotation in Spring Boot plays a pivotal role in simplifying and enhancing the development of Java-based applications, offering a modular and concise way to configure and customise various aspects of the application. These annotations provide a declarative approach to programming, allowing developers to express their intentions clearly.

The importance and significance of Spring Boot annotations lie in their ability to streamline the development process, improve code readability, and promote best practices. The following points highlights the same:

Reduced Configuration Overhead

Spring Boot annotations significantly reduce the need for extensive XML configuration files. They promote a convention-based approach, simplifying the configuration process and allowing developers to focus on writing business logic.

Rapid Development

By automating common tasks and promoting best practices, Spring Boot annotations enable developers to build applications quickly and efficiently. This results in a shorter development cycle and faster time-to-market for projects.

Enhanced Readability and Maintainability

Annotations in spring boot enhance the readability of the code by providing a concise and standardised way to express configurations. This makes the codebase more maintainable and understandable, especially for developers familiar with Spring Boot conventions.

Integrating Third-Party Libraries

Spring Boot annotations facilitate the integration of third-party libraries and frameworks seamlessly. They provide a consistent way to configure and use external dependencies, promoting interoperability and ease of integration.

  • Free Java Courses & Certifications
  • Free Javascript Courses & Certifications
  • What Is Byte Code in Java and How Does It Work?

Spring Boot Annotations List Everyone Should Know

In the context of Spring Boot annotations are powerful tools that enhance developer productivity by automating common tasks and promoting convention over configuration. This section explores several key Spring Boot application annotation through practical examples, understanding the practicality behind spring boot annotations.

These list with explanations not only enhance code readability but also significantly reduce the amount of boilerplate code developers need to write. Therefore, understanding and utilising the essential metadata is paramount for crafting efficient, scalable, and maintainable applications. Now, let us delve into some essential Spring Boot annotations:

@SpringBootApplication: This annotation is used to mark the main class of a Spring Boot application. It combines three commonly used annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan, streamlining the application setup.

@SpringBootApplication

public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class, args);

@RestController: This annotation is used to define a RESTful controller in a Spring Boot application. It combines @Controller and @ResponseBody, simplifying the creation of RESTful APIs.They provide a clear and concise way to map HTTP requests to controller methods.

@RestController

@RequestMapping("/api")

public class MyController {

@GetMapping("/hello")

public String hello() {

return "Hello, World!";

@Autowired: This annotation is used to automatically inject dependencies into a Spring bean. It eliminates the need for manual wiring and makes the code more modular and easily testable.

public class MyService {

private final MyRepository myRepository;

public MyService(MyRepository myRepository) {

this.myRepository = myRepository;

@RequestMapping: This annotation is used to map HTTP requests to handler methods in a controller. It specifies the URI path and HTTP method for which the method should be invoked.

@Controller

@RequestMapping("/books")

public class BookController {

@GetMapping("/{id}")

public String getBook(@PathVariable Long id) {

// Logic to retrieve and return book details

@Value: This annotation is used to inject values from application properties or configuration files into Spring beans.

public class MyComponent {

@Value("${my.property}")

private String myProperty;

Related: Popular Java Certification Courses by Top Providers

  • Udemy Java Certification Courses
  • Udacity Java Certification Courses
  • Edureka Java Certification Courses
  • Coursera Java Certification Courses
  • Intellipaat Java Certification Courses
  • Coding Ninjas Java Certification Courses
  • Microsoft Corporation Java Certification Courses
  • Amazon Web Services Java Certification Courses

Spring Boot annotations play a pivotal role in simplifying the development of Java applications. They reduce configuration overhead, promote rapid development, enhance code readability, and facilitate the integration of third-party libraries. The examples provided here represent just a glimpse of the extensive set of annotations available in Spring Boot.

As you explore the Spring Boot development, exploring these Spring annotations list will empower Java developers to build scalable, maintainable, and efficient applications.

Frequently Asked Question (FAQs)

Spring Boot annotations serve as metadata that guides the Spring framework in configuring and managing various aspects of an application. They reduce configuration overhead, enhance readability, and promote rapid development by automating common tasks.

The Bean annotation is used to declare a method as a bean. A bean is an object managed by the Spring IoC (Inversion of Control) container. When a method is annotated with @Bean, it indicates that the method produces a bean instance to be managed by the Spring container.

Spring Boot annotations enhance code readability by providing a concise and standardised way to express configurations. They also contribute to maintainability by reducing boilerplate code and promoting best practices, making the codebase more understandable and easier to maintain.

In Spring Boot, the Entity annotation is used to designate a class as a JPA (Java Persistence API) entity. This annotation marks the class as a persistent Java object, indicating that instances of this class will be stored in a relational database.

Spring Boot annotations promote a convention-based approach, eliminating the need for extensive XML configuration files. They encapsulate common configurations, allowing developers to focus more on business logic and less on setup.

  • Latest Articles
  • Popular Articles

Upcoming Exams

Manipal entrance test.

Application Date : 30 September,2023 - 14 March,2024

Alliance University Scholastic Aptitude Test

Application Date : 18 October,2023 - 28 February,2024

Chandigarh University Common Entrance Test

Application Date : 19 October,2023 - 27 February,2024

Kalinga Institute of Industrial Technology Entrance Examination

Application Date : 09 November,2023 - 18 March,2024

NMIMS Programs After Twelfth

Application Date : 05 December,2023 - 19 May,2024

Top Java Providers

Explore career options (by industry).

  • Construction
  • Entertainment
  • Manufacturing
  • Information Technology

Data Administrator

Database professionals use software to store and organise data such as financial information, and customer shipping records. Individuals who opt for a career as data administrators ensure that data is available for users and secured from unauthorised sales. DB administrators may work in various types of industries. It may involve computer systems design, service firms, insurance companies, banks and hospitals.

Bio Medical Engineer

The field of biomedical engineering opens up a universe of expert chances. An Individual in the biomedical engineering career path work in the field of engineering as well as medicine, in order to find out solutions to common problems of the two fields. The biomedical engineering job opportunities are to collaborate with doctors and researchers to develop medical systems, equipment, or devices that can solve clinical problems. Here we will be discussing jobs after biomedical engineering, how to get a job in biomedical engineering, biomedical engineering scope, and salary. 

Database Architect

If you are intrigued by the programming world and are interested in developing communications networks then a career as database architect may be a good option for you. Data architect roles and responsibilities include building design models for data communication networks. Wide Area Networks (WANs), local area networks (LANs), and intranets are included in the database networks. It is expected that database architects will have in-depth knowledge of a company's business to develop a network to fulfil the requirements of the organisation. Stay tuned as we look at the larger picture and give you more information on what is db architecture, why you should pursue database architecture, what to expect from such a degree and what your job opportunities will be after graduation. Here, we will be discussing how to become a data architect. Students can visit NIT Trichy , IIT Kharagpur , JMI New Delhi . 

Ethical Hacker

A career as ethical hacker involves various challenges and provides lucrative opportunities in the digital era where every giant business and startup owns its cyberspace on the world wide web. Individuals in the ethical hacker career path try to find the vulnerabilities in the cyber system to get its authority. If he or she succeeds in it then he or she gets its illegal authority. Individuals in the ethical hacker career path then steal information or delete the file that could affect the business, functioning, or services of the organization.

Data Analyst

The invention of the database has given fresh breath to the people involved in the data analytics career path. Analysis refers to splitting up a whole into its individual components for individual analysis. Data analysis is a method through which raw data are processed and transformed into information that would be beneficial for user strategic thinking.

Data are collected and examined to respond to questions, evaluate hypotheses or contradict theories. It is a tool for analyzing, transforming, modeling, and arranging data with useful knowledge, to assist in decision-making and methods, encompassing various strategies, and is used in different fields of business, research, and social science.

Water Manager

A career as water manager needs to provide clean water, preventing flood damage, and disposing of sewage and other wastes. He or she also repairs and maintains structures that control the flow of water, such as reservoirs, sea defense walls, and pumping stations. In addition to these, the Manager has other responsibilities related to water resource management.

Geothermal Engineer

Individuals who opt for a career as geothermal engineers are the professionals involved in the processing of geothermal energy. The responsibilities of geothermal engineers may vary depending on the workplace location. Those who work in fields design facilities to process and distribute geothermal energy. They oversee the functioning of machinery used in the field.

Geotechnical engineer

The role of geotechnical engineer starts with reviewing the projects needed to define the required material properties. The work responsibilities are followed by a site investigation of rock, soil, fault distribution and bedrock properties on and below an area of interest. The investigation is aimed to improve the ground engineering design and determine their engineering properties that include how they will interact with, on or in a proposed construction. 

The role of geotechnical engineer in mining includes designing and determining the type of foundations, earthworks, and or pavement subgrades required for the intended man-made structures to be made. Geotechnical engineering jobs are involved in earthen and concrete dam construction projects, working under a range of normal and extreme loading conditions. 

Budget Analyst

Budget analysis, in a nutshell, entails thoroughly analyzing the details of a financial budget. The budget analysis aims to better understand and manage revenue. Budget analysts assist in the achievement of financial targets, the preservation of profitability, and the pursuit of long-term growth for a business. Budget analysts generally have a bachelor's degree in accounting, finance, economics, or a closely related field. Knowledge of Financial Management is of prime importance in this career.

Operations Manager

Individuals in the operations manager jobs are responsible for ensuring the efficiency of each department to acquire its optimal goal. They plan the use of resources and distribution of materials. The operations manager's job description includes managing budgets, negotiating contracts, and performing administrative tasks.

Finance Executive

A career as a Finance Executive requires one to be responsible for monitoring an organisation's income, investments and expenses to create and evaluate financial reports. His or her role involves performing audits, invoices, and budget preparations. He or she manages accounting activities, bank reconciliations, and payable and receivable accounts.  

Investment Banker

An Investment Banking career involves the invention and generation of capital for other organizations, governments, and other entities. Individuals who opt for a career as Investment Bankers are the head of a team dedicated to raising capital by issuing bonds. Investment bankers are termed as the experts who have their fingers on the pulse of the current financial and investing climate. Students can pursue various Investment Banker courses, such as Banking and Insurance , and  Economics to opt for an Investment Banking career path.

Product Manager

A Product Manager is a professional responsible for product planning and marketing. He or she manages the product throughout the Product Life Cycle, gathering and prioritising the product. A product manager job description includes defining the product vision and working closely with team members of other departments to deliver winning products.  

Treasury analyst career path is often regarded as certified treasury specialist in some business situations, is a finance expert who specifically manages a company or organisation's long-term and short-term financial targets. Treasurer synonym could be a financial officer, which is one of the reputed positions in the corporate world. In a large company, the corporate treasury jobs hold power over the financial decision-making of the total investment and development strategy of the organisation.

Underwriter

An underwriter is a person who assesses and evaluates the risk of insurance in his or her field like mortgage, loan, health policy, investment, and so on and so forth. The underwriter career path does involve risks as analysing the risks means finding out if there is a way for the insurance underwriter jobs to recover the money from its clients. If the risk turns out to be too much for the company then in the future it is an underwriter who will be held accountable for it. Therefore, one must carry out his or her job with a lot of attention and diligence.

Welding Engineer

Welding Engineer Job Description: A Welding Engineer work involves managing welding projects and supervising welding teams. He or she is responsible for reviewing welding procedures, processes and documentation. A career as Welding Engineer involves conducting failure analyses and causes on welding issues. 

Transportation Planner

A career as Transportation Planner requires technical application of science and technology in engineering, particularly the concepts, equipment and technologies involved in the production of products and services. In fields like land use, infrastructure review, ecological standards and street design, he or she considers issues of health, environment and performance. A Transportation Planner assigns resources for implementing and designing programmes. He or she is responsible for assessing needs, preparing plans and forecasts and compliance with regulations.

Conservation Architect

A Conservation Architect is a professional responsible for conserving and restoring buildings or monuments having a historic value. He or she applies techniques to document and stabilise the object’s state without any further damage. A Conservation Architect restores the monuments and heritage buildings to bring them back to their original state.

Safety Manager

A Safety Manager is a professional responsible for employee’s safety at work. He or she plans, implements and oversees the company’s employee safety. A Safety Manager ensures compliance and adherence to Occupational Health and Safety (OHS) guidelines.

A Team Leader is a professional responsible for guiding, monitoring and leading the entire group. He or she is responsible for motivating team members by providing a pleasant work environment to them and inspiring positive communication. A Team Leader contributes to the achievement of the organisation’s goals. He or she improves the confidence, product knowledge and communication skills of the team members and empowers them.

Structural Engineer

A Structural Engineer designs buildings, bridges, and other related structures. He or she analyzes the structures and makes sure the structures are strong enough to be used by the people. A career as a Structural Engineer requires working in the construction process. It comes under the civil engineering discipline. A Structure Engineer creates structural models with the help of computer-aided design software. 

Individuals in the architecture career are the building designers who plan the whole construction keeping the safety and requirements of the people. Individuals in architect career in India provides professional services for new constructions, alterations, renovations and several other activities. Individuals in architectural careers in India visit site locations to visualize their projects and prepare scaled drawings to submit to a client or employer as a design. Individuals in architecture careers also estimate build costs, materials needed, and the projected time frame to complete a build.

Landscape Architect

Having a landscape architecture career, you are involved in site analysis, site inventory, land planning, planting design, grading, stormwater management, suitable design, and construction specification. Frederick Law Olmsted, the designer of Central Park in New York introduced the title “landscape architect”. The Australian Institute of Landscape Architects (AILA) proclaims that "Landscape Architects research, plan, design and advise on the stewardship, conservation and sustainability of development of the environment and spaces, both within and beyond the built environment". Therefore, individuals who opt for a career as a landscape architect are those who are educated and experienced in landscape architecture. Students need to pursue various landscape architecture degrees, such as  M.Des , M.Plan to become landscape architects. If you have more questions regarding a career as a landscape architect or how to become a landscape architect then you can read the article to get your doubts cleared. 

Orthotist and Prosthetist

Orthotists and Prosthetists are professionals who provide aid to patients with disabilities. They fix them to artificial limbs (prosthetics) and help them to regain stability. There are times when people lose their limbs in an accident. In some other occasions, they are born without a limb or orthopaedic impairment. Orthotists and prosthetists play a crucial role in their lives with fixing them to assistive devices and provide mobility.

Veterinary Doctor

A veterinary doctor is a medical professional with a degree in veterinary science. The veterinary science qualification is the minimum requirement to become a veterinary doctor. There are numerous veterinary science courses offered by various institutes. He or she is employed at zoos to ensure they are provided with good health facilities and medical care to improve their life expectancy.

Pathologist

A career in pathology in India is filled with several responsibilities as it is a medical branch and affects human lives. The demand for pathologists has been increasing over the past few years as people are getting more aware of different diseases. Not only that, but an increase in population and lifestyle changes have also contributed to the increase in a pathologist’s demand. The pathology careers provide an extremely huge number of opportunities and if you want to be a part of the medical field you can consider being a pathologist. If you want to know more about a career in pathology in India then continue reading this article.

Speech Therapist

Gynaecologist.

Gynaecology can be defined as the study of the female body. The job outlook for gynaecology is excellent since there is evergreen demand for one because of their responsibility of dealing with not only women’s health but also fertility and pregnancy issues. Although most women prefer to have a women obstetrician gynaecologist as their doctor, men also explore a career as a gynaecologist and there are ample amounts of male doctors in the field who are gynaecologists and aid women during delivery and childbirth. 

An oncologist is a specialised doctor responsible for providing medical care to patients diagnosed with cancer. He or she uses several therapies to control the cancer and its effect on the human body such as chemotherapy, immunotherapy, radiation therapy and biopsy. An oncologist designs a treatment plan based on a pathology report after diagnosing the type of cancer and where it is spreading inside the body.

Audiologist

The audiologist career involves audiology professionals who are responsible to treat hearing loss and proactively preventing the relevant damage. Individuals who opt for a career as an audiologist use various testing strategies with the aim to determine if someone has a normal sensitivity to sounds or not. After the identification of hearing loss, a hearing doctor is required to determine which sections of the hearing are affected, to what extent they are affected, and where the wound causing the hearing loss is found. As soon as the hearing loss is identified, the patients are provided with recommendations for interventions and rehabilitation such as hearing aids, cochlear implants, and appropriate medical referrals. While audiology is a branch of science that studies and researches hearing, balance, and related disorders.

Healthcare Social Worker

Healthcare social workers help patients to access services and information about health-related issues. He or she assists people with everything from locating medical treatment to assisting with the cost of care to recover from an illness or injury. A career as Healthcare Social Worker requires working with groups of people, individuals, and families in various healthcare settings such as hospitals, mental health clinics, child welfare, schools, human service agencies, nursing homes, private practices, and other healthcare settings.  

For an individual who opts for a career as an actor, the primary responsibility is to completely speak to the character he or she is playing and to persuade the crowd that the character is genuine by connecting with them and bringing them into the story. This applies to significant roles and littler parts, as all roles join to make an effective creation. Here in this article, we will discuss how to become an actor in India, actor exams, actor salary in India, and actor jobs. 

Individuals who opt for a career as acrobats create and direct original routines for themselves, in addition to developing interpretations of existing routines. The work of circus acrobats can be seen in a variety of performance settings, including circus, reality shows, sports events like the Olympics, movies and commercials. Individuals who opt for a career as acrobats must be prepared to face rejections and intermittent periods of work. The creativity of acrobats may extend to other aspects of the performance. For example, acrobats in the circus may work with gym trainers, celebrities or collaborate with other professionals to enhance such performance elements as costume and or maybe at the teaching end of the career.

Video Game Designer

Career as a video game designer is filled with excitement as well as responsibilities. A video game designer is someone who is involved in the process of creating a game from day one. He or she is responsible for fulfilling duties like designing the character of the game, the several levels involved, plot, art and similar other elements. Individuals who opt for a career as a video game designer may also write the codes for the game using different programming languages.

Depending on the video game designer job description and experience they may also have to lead a team and do the early testing of the game in order to suggest changes and find loopholes.

Talent Agent

The career as a Talent Agent is filled with responsibilities. A Talent Agent is someone who is involved in the pre-production process of the film. It is a very busy job for a Talent Agent but as and when an individual gains experience and progresses in the career he or she can have people assisting him or her in work. Depending on one’s responsibilities, number of clients and experience he or she may also have to lead a team and work with juniors under him or her in a talent agency. In order to know more about the job of a talent agent continue reading the article.

If you want to know more about talent agent meaning, how to become a Talent Agent, or Talent Agent job description then continue reading this article.

Radio Jockey

Radio Jockey is an exciting, promising career and a great challenge for music lovers. If you are really interested in a career as radio jockey, then it is very important for an RJ to have an automatic, fun, and friendly personality. If you want to get a job done in this field, a strong command of the language and a good voice are always good things. Apart from this, in order to be a good radio jockey, you will also listen to good radio jockeys so that you can understand their style and later make your own by practicing.

A career as radio jockey has a lot to offer to deserving candidates. If you want to know more about a career as radio jockey, and how to become a radio jockey then continue reading the article.

An individual who is pursuing a career as a producer is responsible for managing the business aspects of production. They are involved in each aspect of production from its inception to deception. Famous movie producers review the script, recommend changes and visualise the story. 

They are responsible for overseeing the finance involved in the project and distributing the film for broadcasting on various platforms. A career as a producer is quite fulfilling as well as exhaustive in terms of playing different roles in order for a production to be successful. Famous movie producers are responsible for hiring creative and technical personnel on contract basis.

Fashion Blogger

Fashion bloggers use multiple social media platforms to recommend or share ideas related to fashion. A fashion blogger is a person who writes about fashion, publishes pictures of outfits, jewellery, accessories. Fashion blogger works as a model, journalist, and a stylist in the fashion industry. In current fashion times, these bloggers have crossed into becoming a star in fashion magazines, commercials, or campaigns. 

Photographer

Photography is considered both a science and an art, an artistic means of expression in which the camera replaces the pen. In a career as a photographer, an individual is hired to capture the moments of public and private events, such as press conferences or weddings, or may also work inside a studio, where people go to get their picture clicked. Photography is divided into many streams each generating numerous career opportunities in photography. With the boom in advertising, media, and the fashion industry, photography has emerged as a lucrative and thrilling career option for many Indian youths.

Copy Writer

In a career as a copywriter, one has to consult with the client and understand the brief well. A career as a copywriter has a lot to offer to deserving candidates. Several new mediums of advertising are opening therefore making it a lucrative career choice. Students can pursue various copywriter courses such as Journalism , Advertising , Marketing Management . Here, we have discussed how to become a freelance copywriter, copywriter career path, how to become a copywriter in India, and copywriting career outlook. 

Individuals in the editor career path is an unsung hero of the news industry who polishes the language of the news stories provided by stringers, reporters, copywriters and content writers and also news agencies. Individuals who opt for a career as an editor make it more persuasive, concise and clear for readers. In this article, we will discuss the details of the editor's career path such as how to become an editor in India, editor salary in India and editor skills and qualities.

Careers in journalism are filled with excitement as well as responsibilities. One cannot afford to miss out on the details. As it is the small details that provide insights into a story. Depending on those insights a journalist goes about writing a news article. A journalism career can be stressful at times but if you are someone who is passionate about it then it is the right choice for you. If you want to know more about the media field and journalist career then continue reading this article.

For publishing books, newspapers, magazines and digital material, editorial and commercial strategies are set by publishers. Individuals in publishing career paths make choices about the markets their businesses will reach and the type of content that their audience will be served. Individuals in book publisher careers collaborate with editorial staff, designers, authors, and freelance contributors who develop and manage the creation of content.

In a career as a vlogger, one generally works for himself or herself. However, once an individual has gained viewership there are several brands and companies that approach them for paid collaboration. It is one of those fields where an individual can earn well while following his or her passion. 

Ever since internet costs got reduced the viewership for these types of content has increased on a large scale. Therefore, a career as a vlogger has a lot to offer. If you want to know more about the Vlogger eligibility, roles and responsibilities then continue reading the article. 

Travel Journalist

The career of a travel journalist is full of passion, excitement and responsibility. Journalism as a career could be challenging at times, but if you're someone who has been genuinely enthusiastic about all this, then it is the best decision for you. Travel journalism jobs are all about insightful, artfully written, informative narratives designed to cover the travel industry. Travel Journalist is someone who explores, gathers and presents information as a news article.

Videographer

Careers in videography are art that can be defined as a creative and interpretive process that culminates in the authorship of an original work of art rather than a simple recording of a simple event. It would be wrong to portrait it as a subcategory of photography, rather photography is one of the crafts used in videographer jobs in addition to technical skills like organization, management, interpretation, and image-manipulation techniques. Students pursue Visual Media , Film, Television, Digital Video Production to opt for a videographer career path. The visual impacts of a film are driven by the creative decisions taken in videography jobs. Individuals who opt for a career as a videographer are involved in the entire lifecycle of a film and production. 

SEO Analyst

An SEO Analyst is a web professional who is proficient in the implementation of SEO strategies to target more keywords to improve the reach of the content on search engines. He or she provides support to acquire the goals and success of the client’s campaigns. 

Production Manager

Quality controller.

A quality controller plays a crucial role in an organisation. He or she is responsible for performing quality checks on manufactured products. He or she identifies the defects in a product and rejects the product. 

A quality controller records detailed information about products with defects and sends it to the supervisor or plant manager to take necessary actions to improve the production process.

Metrologist

You might be googling Metrologist meaning. Well, we have an easily understandable Metrologist definition for you. A metrologist is a professional who stays involved in measurement practices in varying industries including electrical and electronics. A Metrologist is responsible for developing processes and systems for measuring objects and repairing electrical instruments. He or she also involved in writing specifications of experimental electronic units. 

Production Worker

A production worker is a vital part of any manufacturing operation, as he or she plays a leading role in improving the efficiency of the production process. Career as a Production Worker  requires ensuring that the equipment and machinery used in the production of goods are designed to meet the needs of the customers.

Azure Administrator

An Azure Administrator is a professional responsible for implementing, monitoring, and maintaining Azure Solutions. He or she manages cloud infrastructure service instances and various cloud servers as well as sets up public and private cloud systems. 

AWS Solution Architect

An AWS Solution Architect is someone who specializes in developing and implementing cloud computing systems. He or she has a good understanding of the various aspects of cloud computing and can confidently deploy and manage their systems. He or she troubleshoots the issues and evaluates the risk from the third party. 

Computer Programmer

Careers in computer programming primarily refer to the systematic act of writing code and moreover include wider computer science areas. The word 'programmer' or 'coder' has entered into practice with the growing number of newly self-taught tech enthusiasts. Computer programming careers involve the use of designs created by software developers and engineers and transforming them into commands that can be implemented by computers. These commands result in regular usage of social media sites, word-processing applications and browsers.

ITSM Manager

Information security manager.

Individuals in the information security manager career path involves in overseeing and controlling all aspects of computer security. The IT security manager job description includes planning and carrying out security measures to protect the business data and information from corruption, theft, unauthorised access, and deliberate attack 

Big Data Analytics Engineer

Big Data Analytics Engineer Job Description: A Big Data Analytics Engineer is responsible for collecting data from various sources. He or she has to sort the organised and chaotic data to find out patterns. The role of Big Data Engineer involves converting messy information into useful data that is clean, accurate and actionable. 

Everything about Education

Latest updates, Exclusive Content, Webinars and more.

Download Careers360 App's

Regular exam updates, QnA, Predictors, College Applications & E-books now on your Mobile

student

Cetifications

student

We Appeared in

Economic Times

Java Guides

Java Guides

Search this blog.

Check out my 10+ Udemy bestseller courses and discount coupons: Udemy Courses - Ramesh Fadatare

Spring Boot and Spring Framework Annotations Cheat Sheet

Here's a list of commonly used annotations in the Spring Framework and Spring Boot.

Spring Framework Annotations

@Component : Marks a class as a candidate for auto-detection as a Spring-managed bean. 

@Controller : Marks a class as a controller component in the MVC pattern. 

@Service : Marks a class as a service component in the business layer. 

@Repository : Marks a class as a repository component in the persistence layer. 

@Autowired : Injects dependencies automatically by type. 

@Qualifier : Specifies the specific bean to be autowired when multiple beans of the same type are available. 

@Value : Injects values from properties files or environment variables. 

@Configuration : Indicates that a class declares Spring configuration. @Bean: Marks a method as a provider of beans that should be managed by the Spring container. 

@ComponentScan : Configures component scanning for automatic bean detection. 

@RequestMapping : Maps HTTP requests to specific handler methods. 

@PathVariable : Binds a method parameter to a path variable in a request URL. 

@RequestParam : Binds a method parameter to a query parameter or form data in a request. 

@RequestBody : Binds the body of a request to a method parameter. 

@ResponseBody : Indicates that a method return value should be serialized directly to the HTTP response.

@GetMapping : Used to map HTTP GET requests to specific handler methods in a controller class.

@PostMapping : Used to map HTTP POST requests to specific handler methods in a controller class.

@PutMapping : Used to map HTTP PUT requests to specific handler methods in a controller class.

@DeleteMapping : Used to map HTTP DELETE requests to specific handler methods in a controller class.

@PatchMapping : Used to map HTTP PATCH requests to specific handler methods in a controller class.

@ExceptionHandler : Handles exceptions thrown by controller methods. 

@ResponseStatus : Sets the HTTP response status code for a controller method. 

@Aspect : Declares an aspect, combining advice and pointcuts. 

@Transactional : Specifies that a method (or all methods in a class) should be executed within a transactional context. 

@Async : Enables asynchronous execution of a method. 

Spring Boot Annotations

@SpringBootApplication : Combines @Configuration , @EnableAutoConfiguration , and @ComponentScan , marking the main class as the entry point for a Spring Boot application.

 @EnableAutoConfiguration : Enables auto-configuration of the Spring application context, based on the classpath and defined dependencies. 

@ConfigurationProperties : Binds and validates externalized configuration properties to a configuration class. 

@ConditionalOnProperty : Configures beans based on the presence or absence of specified properties. 

@ConditionalOnClass : Configures beans based on the presence or absence of specified classes. 

@ConditionalOnBean : Configures beans based on the presence or absence of specified beans. 

@ConditionalOnMissingBean : Configures beans only if the specified beans are not present. 

@ConditionalOnExpression : Configures beans based on a SpEL expression. 

@Conditional : Specifies custom conditions for bean configuration. 

@EnableConfigurationPropertie s: Enables support for @ConfigurationProperties annotated classes. 

Spring Framework Annotations Cheat Sheet

spring boot annotation list

These are just a few examples of the annotations provided by the Spring Framework and Spring Boot. There are many more annotations available for different purposes, such as security, messaging, caching, testing, and more. The specific annotations you use will depend on the modules and features of the Spring Framework or Spring Boot that you are utilizing in your application.

Related Spring and Spring Boot Tutorials/Guides:

Post a comment.

Leave Comment

Free Course on My YouTube Channel:

Happy New Year 2024! 🎆

Learn spring boot 3, microservices, and full-stack web development using my project-oriented courses.

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot + Apache Kafka - The Quickstart Practical Guide
  • Spring Boot + RabbitMQ (Includes Event-Driven Microservices)
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out my all Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

IMAGES

  1. all the annotations used in spring boot

    spring boot annotation list

  2. Spring Boot Annotations

    spring boot annotation list

  3. The Complete List of Spring Boot Annotations You Must Know

    spring boot annotation list

  4. Spring Boot Auto Configuration

    spring boot annotation list

  5. all the annotations used in spring boot

    spring boot annotation list

  6. Spring Boot Annotations List

    spring boot annotation list

VIDEO

  1. Spring Boot Annotation

  2. Spring Boot 03

  3. 6. What is @SpringbootApplication Annotation

  4. Spring Boot Annotation part-1 Most important asked in Java Interview |TCS|Cognizant|HCL|Latest|

  5. Spring Framework Tutorial: Required Annotation

  6. Spring Boot Rest Client

COMMENTS

  1. Spring Boot Annotations

    We use this annotation to mark the main class of a Spring Boot application: @SpringBootApplication encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their default attributes. 3. @EnableAutoConfiguration. @EnableAutoConfiguration, as its name says, enables auto-configuration.

  2. List of All Spring Boot Annotations, Uses with examples

    Here's an extensive list of Spring Boot annotations 1. Core Annotations: a). @SpringBootApplication . The @SpringBootApplication annotation is used to mark the main class of a Spring Boot application. This is the Spring Boot Application starting point. It combines three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan ...

  3. Spring Boot Annotations

    Spring Boot Annotations @EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication. @SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration ...

  4. Spring Boot Annotations List

    Spring - @Primary Annotation Example. Spring @PostConstruct and @PreDestroy Example. Spring @Repository Annotation. Spring @Service Annotation. The Spring @Controller and @RestController Annotations. Spring Boot @Component, @Controller, @Repository and @Service. Spring @Scope annotation with Prototype Scope Example.

  5. PDF Spring Boot Annotations: Top 30+ most Used Spring Annotations

    The annotations in Spring Boot is not a part of the program itself and do not have any direct effect on the annotated code's operation. Spring Boot Annotations do not use XML configuration, instead, they use the convention over configuration. In this section of the learning Spring Boot Series, we will discuss different types of annotations with ...

  6. Spring Boot

    Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup.

  7. The Essential List of Spring Boot Annotations and Their Use Cases

    Below are all the essential spring boot annotations you should know about. 1. @Bean. The "@Bean" is a method-level annotation that is analogous to XML <bean> tag. When you declare this annotation, Java creates a bean with the method name and registers it with the BeanFactory.

  8. Spring Boot Reference Documentation

    Spring Boot Reference Documentation is the official guide for using Spring Boot , a framework that simplifies the configuration and deployment of Spring applications. It covers topics such as features, dependencies, starters, testing, production, and more. Whether you are new to Spring Boot or an experienced user, you will find valuable information and examples in this documentation.

  9. Spring Annotations

    Spring Annotations. Spring framework implements and promotes the principle of control inversion (IOC) or dependency injection (DI) and is in fact an IOC container. Traditionally, Spring allows a developer to manage bean dependencies by using XML-based configuration. There is an alternative way to define beans and their dependencies.

  10. Spring Boot Annotations

    This spring boot specific annotation helps bind properties file entries to a java bean. For example, take a look at these configs. app.maxOrderPriceLimit= 1000 app.payment.enabled= true app.payment.types=card,cash Code language: Java (java) Let's map these into a java bean.

  11. Spring Annotations Cheat Sheet

    Here are the most important annotations any Java developer working with Spring should know: @Configuration - used to mark a class as a source of the bean definitions. Beans are the components of the system that you want to wire together. A method marked with the @Bean annotation is a bean producer. Spring will handle the life cycle of the beans ...

  12. All Spring Annotations ASAP Cheat Sheet [Core+Boot][2023]

    Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. We can use @Value for injecting property values into beans. It's compatible with the constructor, setter, and field injection.

  13. Spring Boot Annotations Everyone Should Know [2024]

    A Spring Boot Annotations list with explanations can help you better comprehend the use case of these annotations. 1. @Bean. The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be managed by the Spring container. It is an alternative to the XML<bean> tag.

  14. Spring Boot Annotations With Examples

    Next annotations in our topic 'Spring Boot Annotations With Examples' are the stereotype annotations. @Component. @Complonent annotation is also an important & most widely used at the class level. This is a generic stereotype annotation which indicates that the class is a Spring-managed bean/component. @Component is a class level annotation.

  15. introducing basic Spring Boot annotations

    In this article we show how to use basic Spring Boot annotations including @Bean, @Service, @Configuration, @Controller, @RequestMapping, @Repository, @Autowired, and @SpringBootApplication. Spring is a popular Java application framework for creating enterprise applications. Spring Boot is the next step in evolution of Spring framework.

  16. Java, Java EE, Spring and Spring Boot Annotations with Examples

    The @WebMvcTest annotation is used to perform unit tests on Spring MVC controllers. It allows you to test the behavior of controllers, request mappings, and HTTP responses in a controlled and isolated environment. 4. Spring Data JPA Annotations. List of 4.

  17. Validating Lists in a Spring Controller

    In this tutorial, we'll go over ways to validate a List of objects as a parameter to a Spring controller. We'll add validation in the controller layer to ensure that the user-specified data satisfies the specified conditions. 2. Adding Constraints to Fields. For our example, we'll use a simple Spring controller that manages a database of ...

  18. A Comprehensive Guide to Annotations in Spring Boot JPA

    Spring Boot, with its JPA support, makes it even easier to work with databases. In this article, we'll explore a comprehensive list of annotations commonly used in Spring Boot JPA to define and ...

  19. Spring Boot Annotations: Top 30+ most Used Spring Annotations

    The @SpringBootApplication is the combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration. The @SpringBootApplication annotation is used on the application class while setting up a new Spring Boot project. The class that is annotated with this annotation must be placed in the base package.

  20. gindex/spring-boot-annotation-list

    List of frequently used annotations in Spring Boot apps This document contains non-comprehensive list of frequently used annotations in Spring Boot applications. It should rather be used as a quick lookup list, for detailed and comprehensive information please read official javadocs and documentation.

  21. Spring Boot Annotations List Everyone Should Know About

    Spring Boot Annotations List Everyone Should Know. In the context of Spring Boot annotations are powerful tools that enhance developer productivity by automating common tasks and promoting convention over configuration. This section explores several key Spring Boot application annotation through practical examples, understanding the ...

  22. Spring Boot and Spring Framework Annotations Cheat Sheet

    Here's a list of commonly used annotations in the Spring Framework and Spring Boot. Spring Framework Annotations @Component: Marks a class as a candidate for auto-detection as a Spring-managed bean. @Controller: Marks a class as a controller component in the MVC pattern. @Service: Marks a class as a service component in the business layer. @Repository: Marks a class as a repository component ...

  23. Inject Arrays & Lists from Spring Property Files

    1. Overview. In this quick tutorial, we're going to learn how to inject values into an array or List from a Spring properties file. 2. Default Behavior. We'll start with a simple application.properties file: arrayOfStrings=Baeldung,dot,com. Let's see how Spring behaves when we set our variable type to String []: