Springboot Annotations Quick Reference
Springboot Annotations Quick Reference
1. @SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
@Configuration
2. @EnableAutoConfiguration
3. @ComponentScan - for configuring the path where to scan for the beans,
default it scans current and sub-packages(base packages and base classes), we can
specify any path also where to scan for the beans
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 1/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
4. @Configuration
It means we have defined beans in the annotated class so that spring IoC can load
them, third party class objects can be load as beans by adding @Bean annotation
on methods where that class bean is returned. The @Configuration annotation
marks a class as source of bean definitions, the life cycle of the beans defined in
this class are handled by spring IoC container.
5. @Component
This is the base annotation and following annotations like @Service, @Controller,
@Repository are derived from the @Component annotation.
6. @Service
Denotes a service layer class where we can provide some business logic.
7. @RestController Vs @Controller
@Controller is generic type of controller like web controller, REST controller etc.,
It is typically used with annotations like @RequestMapping @ResponseBody
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 2/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
8. @ResponseBody annotation
it specifies that java object is serialized into JSON and put into the body of the
response
9. @RequestBody annotation
11. @GetMapping
@RequestMapping(method = RequestMethod.HEAD)
@RequestMapping(method = RequestMethod.OPTIONS)
@QueryParam is used to retrieve the value from the query string. for example,
the following request
/foo?id=1001
@GetMapping(“/foo”)
14. @PathVariable
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 3/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@GetMapping(“/foo”)
15. @RequestParam
This annotation is used to extract input data that may be passed as a query, form
data, etc.
16. @RequestHeader
Request headers can be captured by using the name of the request header in the
following way
@GetMapping("/foo")
public ResponseEntity<String>
getFoo(@RequestHeader(HttpHeaders.ACCEPT_LANGUAGE) String language) {}
to capture all the request headers, there are two ways, the following code can be
used:
@GetMapping("/foo")
});
OR
@GetMapping("/foo")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 4/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
17. @ControllerAdvice
18. @RestControllerAdvice
19. @ResponseStatus
This annotation is used to set the response status, it can be used in the exception
handler
@ResponseStatus(HttpStatus.NOT_FOUND)
20. @ExceptionHandler
This annotation is used with specific handler classes or methods that handle
exceptions. It takes any of the Exception.class as an argument. Root exception
matching is preferred to the current exception and if there are multiple Controller
Advice Beans, @Order and @Priority annotations should be used to specify the
order and priority, lower value of order takes higher precedence.
For example:
@ExceptionHandler(Exception.class)
@ExceptionHandler(UserNotFoundExecption.class)
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 5/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
21. @Autowired
22. @Qualifier
Spring resolves autowired entries by type. If there are more than one beans of
same type, the container throws NoUniqueBeanDefinitionException, as there is
ambiguity as to which bean to be injected. By including the @Qualifier annotation
we are specifying which specific implementation to be injected. The qualifier
name to be used is the one that is used in @Component
Alternatively, we can use @Primary annotation to mark a bean as primary and the
container injects that bean by default. If we add @Primary annotation to any of
the components, we need not add @Qualifier to all beans when we add second
bean instance.
23. @Lazy
Spring IoC container initializes all beans by default at the start up and this will
unnecessarily create a large number of objects including those that may not be
used immediately, this will occupy a lot of heap, by using the @Lazy annotation,
we are instructing the container to load the bean only on demand,
24. @Value
This annotation is used to inject property values into the bean from property files,
this is used in combination with @PropertyResource annotation
@Value("${dbConnectionString}")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 6/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Value("${server.port:8080}")
@PropertySource("classpath:/com/abc/app.properties")
25. @ConfigurationProperties
This annotation is used to map or bind the entire external configuration values in .
properties or . yml files to Java objects
@Component
@PropertySource("classpath:xyz.properties")
@ConfigurationProperties
private int x;
private String y;
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 7/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Service
@ConditionalOnProperty(
value="logging.enabled",
havingValue = "true",
matchIfMissing = true)
class LoggingService {
28. @ConditionalOnExpression
@Service
@ConditionalOnExpression(
class LoggingService {
29. @Conditional
@Service
@Conditional(MyCondition.class)
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 8/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Override
return JavaVersion.getJavaVersion().equals(JavaVersion.EIGHT);
30. @Profile
31. @Scope
@Scope annotations can only be used on the concrete bean class (for annotated
components) or the factory method (for @Bean methods). When used on the
concrete bean class as a type-level annotation together with @Component,
@Scope indicates the name of a scope to use for instances of the annotated type.
When used on the factory method as a method-level annotation together with
@Bean, @Scope indicates the name of a scope to use for the instance returned
from the method.
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 9/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
32. @Import
scoped bean injection problem - Injecting prototype bean into singleton bean,
both the beans will be initialized only once, the prototype bean will lose its
prototype behavior.
33. @Loopup
Use annotation @Loopup at method level for injection, to solver the scoped bean
injection problem,
@Lookup
34. @Repository
35. @NoRepositoryBean
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 10/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@NoRepositoryBean
36. @Entity
By annotating a class with @Entity, we are specifying that the class is correspond
to a particular DB table and DB operations can be performed on that class.
37. @Table
This annotation allows us to specify the table that a particular entity corresponds
to and that can be used to persist the entity in the database.
@Entity
@Table(name = "EMPLOYEE")
@Id
@GeneratedValue
@Column(name = "id")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 11/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
This annotation is not mandatory, by default, entity class name is treated as the
name of the table, we can specify a different table name using this annotation.
38. @Id
39. @IdClass
--
@Entity
@IdClass(PersonId.class)
40. @EmbeddedId
@EmbeddableClass
Int assessmentYear;
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 12/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
String quarter;
Class Report {
@EmbeddedId
ReportId reportId;
41. @GeneratedValue
ii. GenerationType. IDENTITY - primary keys for the entity using a database
identity column. IDENTITY, SQL server, MYSQL support this and some dbs does not
support.
42. @Column
43. @OneToOne
This annotation is used to denote single entity is mapped to another single entity.
For example, Person and PassportDetails
@Entity
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 13/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
@Column(name="name")
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="passport_number")
@Entity
@Table(name="passport_details")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="passport_number")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 14/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@OneToOne(mappedBy="passportDetails", cascade=
{CascadeType.REFRESH,CascadeType.DETACH,
CascadeType.PERSIST})
Cascade Types:
When we perform some operation like delete on one target entity, the same
action will be applied to associated entities
MERGE
REFRESH
Hibernate Specific:
LOCK - Re-attaches parent entity and its child entities to persistent context.
REPLICATE
SAVE_UPDATE
For example one department have many employees, the mapping can be specified
as follows:
@Entity
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 15/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Id
@Column(name=”department_id”)
@OneToMany(fetch=FetchType.LAZY,mappedBy="department_id", cascade=
{CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
@Entity
@Id
@Column(name=”employee_id”)
CascadeType.DETACH,CascadeType.REFRESH})
@JoinColumn(name="department_id" )
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 16/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Entity
@Id
@Column(name=”product_id”)
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumn(name="product_id")
@Entity
@Table(name="review")
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="comment")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 17/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
45. @ManyToMany
@Entity
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@ManyToMany(fetch=FetchType.LAZY, cascade=
{CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
@JoinTable(name="course_student",
joinColumns=@JoinColumn(name="course_id",
referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="student_id",
referencedColumnName="id")
@Entity
@Table(name="student")
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 18/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
@ManyToMany(fetch=FetchType.LAZY, cascade=
{CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH})
@JoinTable(name="course_student",
joinColumns=@JoinColumn(name="student_id",
referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="course_id",
referencedColumnName="id")
This annotation is used to execute queries for spring repository methods. It can
take JPQL or native SQL queries, by default it takes JPQL query.
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 19/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
Collection<User> findAllPendingOrdersNative();
47. @NamedQuery
This will help define the queries on one place, in the entity class and use them in
the repository class, this is a static query that gets evaluated at the time of
session factory creation
For example,
@Entity
@Table
@NamedQuery(name = "Order.findByStatus",
@Repository
48. @NamedNativeQuery
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 20/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@org.hibernate.annotations.NamedNativeQueries(
@org.hibernate.annotations.NamedNativeQuery(name = "Order.findByOrderId",
query = "select * from Orders emp where order_id=:orderId", resultClass =
Order.class) )
49. @Modifying
This annotation is used along with the @Query annotation to execute commands
(CUD) operations
JPQL
@Modifying
Native SQL
@Modifying
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 21/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
50. @Version
This annotation is used for optimistic locking, to prevent lost updates, when
multiple transactions are reading/writing a particular entity. To implement this,
we need to add a property in the entity class
@Version
Using last modified date for versioning, as per documentation this is less reliable
than version number. DB is the default version, if we use VM, it uses timestamp of
virtual machine
@Version
@Source(value=SourceType.DB)
When a particular entity is read, along with the entity version is also returned, and
when that particular entity is updated, version is incremented. Other transactions
that try to update the entity with older version will throw
OptimisticLockException, they need to read the latest version and try the update
operation.
@Version
51. @OptimisticLock
This annotation can be used with @Version, when we use @Version, the version
gets updated for any property change in the entity, if we want to exclude any
property from version update, we should use this annotation
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 22/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Column(name=”xyz”)
@OptimisticLock(excluded=true)
52. @OptimisticLocking
This annotation is used for versionless optimistic locking, it does not require
version attribute, this is useful with legacy schemas, version checks are performed
either with all the entity attributes or just attributes changed, it has a single
attribute of type OptimisticLockType. There are 4 Optimistic lock types
c. ALL – All entity properties are used to verify the version of the entity
d. DIRTY – Only current dirty properties are used to verify entity version
@Entity(name = "product")
@Table(name = "product")
@OptimisticLocking(type = OptimisticLockType.DIRTY)
@DynamicUpdate
53. @DynamicUpdate
It takes value true or false, if true, dynamic sql will be generated with the changed
columns only as part of the prepared sql statement executed for update.
54. @Lock
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 23/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@Lock(LockModeType.PESSIMISTIC_READ)
55. @ EnableTransactionManagement
@Configuration
@EnableTransactionManagement
56. @Transactional
This annotation can be applied to method or class to indicate that the annotated
method or all methods in the annotated class should be executed within the
transaction.
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 24/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
propagation
REQUIRED, REQUIRES_NEW,MANDATORY,NEVER,SUPPORTS,NOT_SUPPORTED,
NESTED
timeout
readonly
noRollbackFor
noRollbackForClassName
57. @PersistenceContext
@PersistenceContext
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 25/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
@PersistenceContext(type = PersistenceContextType.EXTENDED)
What are some best practices for designing ORM models that are adaptable to future schema
changes?
Data Engineering
How can you use Apache Flink to extract data from cloud-based summarization tools?
Database Design
How do you validate and query json data efficiently and securely?
Database Development
What are the best practices for handling large datasets in ORM code?
Database Development
What is lazy loading in ORM and how does it impact performance in Database Development?
Process Automation
How can you optimize ETL performance with Python and Pandas?
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 26/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
Show more
Show more
Explore topics
Sales
Marketing
Business Administration
HR Management
Content Management
Engineering
Soft Skills
See All
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 27/28
14/04/2024, 19:33 Springboot Annotations Quick Reference
© 2024 About
Language
https://www.linkedin.com/pulse/springboot-annotations-quick-reference-suneel-anthubatla-vqeee 28/28