The Wayback Machine - https://web.archive.org/web/20240907083945/https://www.geeksforgeeks.org/spring-framework-annotations/
Open In App

Spring Framework Annotations

Last Updated : 15 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations are a form of metadata that provides data about a program. 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 what are the main types of annotation that are available in the spring framework with some examples. 

Types of Spring Framework Annotations

Basically, there are 6 types of annotation available in the whole spring framework.

  1. Spring Core Annotations
  2. Spring Web Annotations
  3. Spring Boot Annotations
  4. Spring Scheduling Annotations
  5. Spring Data Annotations
  6. Spring Bean Annotations

Type 1: Spring Core Annotations 

Spring annotations present in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages are commonly known as Spring Core annotations. We can divide them into two categories:

  • DI-Related Annotations
    • @Autowired
    • @Qualifier
    • @Primary
    • @Bean
    • @Lazy
    • @Required
    • @Value
    • @Scope
    • @Lookup, etc.
  • Context Configuration Annotations
    • @Profile
    • @Import
    • @ImportResource
    • @PropertySource, etc.

A DI (Dependency Injection) Related Annotations

1.1: @Autowired

@Autowired annotation is applied to the fields, setter methods, and constructors. It injects object dependency implicitly. We use @Autowired to mark the dependency that will be injected by the Spring container.

1.2: Field injection

Java




class Student {
    @Autowired
    Address address;
}


1.3: Constructor injection

Java




class Student {
    Address address;
  
    @Autowired
    Student(Address address) {
        this.address = address;
    }
}


1.4: Setter injection

Java




class Student {
    Address address;
  
    @Autowired
    void setaddress(Address address) {
        this.address = address;
    }
}


B Context Configuration Annotations 

@Profile: If you want Spring to use a @Component class or a @Bean method only when a specific profile is active then you can mark it with @Profile. 

@Component
@Profile("developer")
public class Employee {}

Type 2: Spring Web Annotations

Spring annotations present in the org.springframework.web.bind.annotation packages are commonly known as Spring Web annotations. Some of the annotations that are available in this category are:

  • @RequestMapping
  • @RequestBody
  • @PathVariable
  • @RequestParam
  • Response Handling Annotations
    • @ResponseBody
    • @ExceptionHandler
    • @ResponseStatus
  • @Controller
  • @RestController
  • @ModelAttribute
  • @CrossOrigin

Example: @Controller

Spring @Controller annotation is also a specialization of @Component annotation. The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It’s used to mark a class as a web request handler. It’s mostly used with Spring MVC applications. This annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations.

Java




package com.example.demo.controller;
  
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
  
@Controller
public class DemoController {
  
    @RequestMapping("/hello")
    @ResponseBody
    public String helloGFG()
    {
        return "Hello GeeksForGeeks";
    }
}


Type 3: Spring Boot Annotations

Spring annotations 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
  • @EnableAutoConfiguration
  • Auto-Configuration Conditions
    • @ConditionalOnClass, and @ConditionalOnMissingClass
    • @ConditionalOnBean, and @ConditionalOnMissingBean
    • @ConditionalOnProperty
    • @ConditionalOnResource
    • @ConditionalOnWebApplication and @ConditionalOnNotWebApplication
    • @ConditionalExpression
    • @Conditional

Example: @SpringBootApplication

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

Java




@SpringBootApplication
  
// Class
public class DemoApplication {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        SpringApplication.run(DemoApplication.class, args);
    }
}


Type 4: Spring Scheduling Annotations

Spring annotations present in the org.springframework.scheduling.annotation packages are commonly known as Spring Scheduling annotations. Some of the annotations that are available in this category are:

  • @EnableAsync
  • @EnableScheduling
  • @Async
  • @Scheduled
  • @Schedules

Example: @EnableAsync

This annotation is used to enable asynchronous functionality in Spring.

@Configuration
@EnableAsync
class Config {}

Type 5: Spring Data Annotations

Spring Data provides an abstraction over data storage technologies. Hence the business logic code can be much more independent of the underlying persistence implementation. Some of the annotations that are available in this category are:

  • Common Spring Data Annotations
    • @Transactional
    • @NoRepositoryBean
    • @Param
    • @Id
    • @Transient
    • @CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
  • Spring Data JPA Annotations
    • @Query
    • @Procedure
    • @Lock
    • @Modifying
    • @EnableJpaRepositories
  • Spring Data Mongo Annotations
    • @Document
    • @Field
    • @Query
    • @EnableMongoRepositories

Example:

A @Transactional 

When there is a need to configure the transactional behavior of a method, we can do it with @Transactional annotation. 

@Transactional
void payment() {}

B @Id: @Id marks a field in a model class as the primary key. Since it’s implementation-independent, it makes a model class easy to use with multiple data store engines.

class Student {

    @Id
    Long id;

    // other fields
      // ........... 
    
}

Type 6: Spring Bean Annotations

There’re several ways to configure beans in a Spring container. You can declare them using XML configuration or you can declare beans using the @Bean annotation in a configuration class or you can mark the class with one of the annotations from the org.springframework.stereotype package and leave the rest to component scanning. Some of the annotations that are available in this category are:

Example: Stereotype Annotations

Spring Framework provides us with some special annotations. These annotations are used to create Spring beans automatically in the application context. @Component annotation is the main Stereotype Annotation. There are some Stereotype meta-annotations which is derived from @Component those are

  1. @Service
  2. @Repository
  3. @Controller

1: @Service: We specify a class with @Service to indicate that they’re holding the business logic. Besides being used in the service layer, there isn’t any other special use for this annotation. The utility classes can be marked as Service classes.

2: @Repository: We specify a class with @Repository to indicate that they’re dealing with CRUD operations, usually, it’s used with DAO (Data Access Object) or Repository implementations that deal with database tables.

3: @Controller: We specify a class with @Controller to indicate that they’re front controllers and responsible to handle user requests and return the appropriate response. It is mostly used with REST Web Services.

So the stereotype annotations in spring are @Component, @Service, @Repository, and @Controller.

Image



Previous Article
Next Article

Similar Reads

Spring Boot - Reactive Programming Using Spring Webflux Framework
In this article, we will explore React programming in Spring Boot, Reactive programming is an asynchronous, non-blocking programming paradigm for developing highly responsive applications that react to external stimuli. What is Reactive ProgrammingIn reactive programming, the flow of data is asynchronous through push-based publishers and subscriber
4 min read
Spring Core Annotations
Spring Annotations are a form of metadata that provides data about a program. 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. In the Spring framework, the annotations are classified into diffe
4 min read
Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
Spring Annotations are a form of metadata that provides data about a program. 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. Here, we are going to discuss the difference between the 4 most im
4 min read
Spring Boot Annotations - @JmsListener, @Retryable, @RSocketMessageMapping, @ConstructorBinding, and @Slf4j
Spring Boot is a popular framework for building modern, scalable, and efficient Java applications. One of the key features of Spring Boot is its extensive use of annotations, which simplify the process of configuring and deploying Spring-based applications. In this article, we will explore some of the latest Spring Boot annotations and how they can
7 min read
Spring Boot - @PathVariable and @RequestParam Annotations
When building RESTful APIs with Spring Boot, it's crucial to extract data from incoming HTTP requests to process and respond accordingly. The Spring framework provides two main annotations for this purpose: @PathVariable and @RequestParam. The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in the reque
8 min read
Spring Bean Validation - JSR-303 Annotations
In this article, we'll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate code and making your code more concise and express
6 min read
Spring - Stereotype Annotations
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations a
10 min read
Spring Conditional Annotations
The Spring Framework provides a powerful way to control bean creation and configuration based on specific conditions through its conditional annotations. These features can be particularly useful in building flexible and environment-specific configurations without cluttering the application with boilerplate code. Conditional annotations let develop
5 min read
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
8 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Introduction to the Spring Data Framework
In the previous article, we have already discussed about spring framework and spring boot. In this article, we will understand about spring data framework. The need for Spring Data Framework Our digital world is holding more than 20 zettabytes of data, and that is around as many bits of information as the stars in our physical universe. These data
5 min read
Spring - ORM Framework
Spring-ORM is a technique or a Design Pattern used to access a relational database from an object-oriented language. ORM (Object Relation Mapping) covers many persistence technologies. They are as follows: JPA(Java Persistence API): It is mainly used to persist data between Java objects and relational databases. It acts as a bridge between object-o
2 min read
Top 10 Most Common Spring Framework Mistakes
"A person who never made a mistake never tried anything new" - Well said the thought of Albert Einstein. Human beings are prone to make mistakes. Be it technological aspect, mistakes are obvious. And when we talk about technology, frameworks play a very important role in building web applications. Frameworks have a defined set of codes that can be
6 min read
10 Reasons to Use Spring Framework in Projects
Spring is the season that is known for fresh leaves, new flowers, and joy which makes our minds more creative. Do you know there is a bonus for us? We have another Spring as well. Our very own Spring framework! It is an open-source application framework that is used for building Java applications and projects. There are many reasons for which Sprin
6 min read
Remoting in Spring Framework
Spring has integration classes for remoting support that use a variety of technologies. The Spring framework simplifies the development of remote-enabled services. It saves a significant amount of code by having its own API. The remote support simplifies the building of remote-enabled services, which are implemented by your standard (Spring) POJOs.
3 min read
Spring Framework Architecture
The Spring framework is a widely-used open-source Java framework that provides a comprehensive programming and configuration model for building enterprise applications. Its architecture is designed around two core principles: Dependency Injection (DI) and Aspect-Oriented Programming (AOP). The Spring framework consists of several modules, which can
7 min read
What is Spring Framework and Hibernate ORM?
Spring Framework is an open-source Java framework that is used to develop enterprise-level applications. It provides a wide range of features and functionalities such as inversion of control (IoC), dependency injection (DI), aspect-oriented programming (AOP), and more. These features help developers to build robust, scalable, and maintainable appli
5 min read
Introduction to Spring Framework
Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to use JavaBeans to create Web applications. Although JavaBeans helped in the development of user interface (UI) components, they were not able to provide services, such as transaction management and security, which were required for developing robust and secure enterprise a
10 min read
Spring - MVC Framework
Spring MVC Framework follows the Model-View-Controller architectural design pattern which works around the Front Controller i.e. the Dispatcher Servlet. The Dispatcher Servlet handles and dispatches all the incoming HTTP requests to the appropriate controller. It uses @Controller and @RequestMapping as default request handlers. The @Controller anno
4 min read
Spring Framework Standalone Collections
Spring Framework allows to inject of collection objects into a bean through constructor dependency injection or setter dependency injection using <list>,<map>,<set>, etc. Given below is an example of the same. Example Projectpom.xml:  [GFGTABS] XML <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="htt
2 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
How to Create Your Own Annotations in Java?
Annotations are a form of metadata that provide information about the program but are not a part of the program itself. An Annotation does not affect the operation of the code they Annotate. Now let us go through different types of java annotations present that are listed as follows: Predefined annotations.: @Deprecated, @Override, @SuppressWarning
5 min read
Inherited Annotations in Java
Annotations in Java help associate metadata to the program elements such as classes, instance variables, methods, etc. Annotations can also be used to attach metadata to other annotations. These types of annotations are called meta-annotation. Java, by default, does not allow the custom annotations to be inherited. @inherited is a type of meta-anno
5 min read
Java @Retention Annotations
In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which p
3 min read
Java @Documented Annotations
By default, Java annotations are not shown in the documentation created using the Javadoc tool. To ensure that our custom annotations are shown in the documentation, we use @Documented annotation to annotate our custom annotations. @Documented is a meta-annotation (an annotation applied to other annotations) provided in java.lang.annotation package
2 min read
Java - @Target Annotations
Annotations in java are used to associate metadata to program elements like classes, methods, instance variables, etc. There are mainly three types of annotations in java: Marker Annotation (without any methods), Single-Valued Annotation (with a single method), and Multi-Valued Annotation (with more than one method). @Target annotation is a meta-an
3 min read
Annotations in Java
Annotations are used to provide supplemental information about a program. Annotations start with ‘@’.Annotations do not change the action of a compiled program.Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.Annotations are not pure comments as they can change
9 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Article Tags :
Practice Tags :