Spring Annotation Cheat Sheet 1664749230
Spring Annotation Cheat Sheet 1664749230
Spring Annotation Cheat Sheet 1664749230
Spring includes a lot of annotations. Some are annotations created within Spring. Some are
annotations called for by various Java specifications. The annotations fall into categories, as
follows:
Spring Framework
REST
HATEOAS
Session
Boot
Integration
Cloud
Data
Batch
Aspect-oriented Programming
Integration Testing
JMX
Cache Abstraction
Other
Spring Framework
The Spring Framework is the core project within Spring. The Spring Framework includes
annotations in the following categories:
Dependency Injection
Configuration
JMS
AMQP
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Bean Lifecycle
MVC/Web
CORS Support
Dependency Injection
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Allows for loading @Bean definitions from another configuration
@Import
class.
Indicates beans on which the current bean depends.
@DependsOn
Configuration
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that an annotated class is a repository.
@Repository
JMS
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that the return value of a message-handling method should be
sent as a Message to the specified destination(s) prepended
@SendToUser
with /user/{username} where the user name is extracted from the headers
of the input message being handled.
AMQP
Bean Lifecycle
@{BeanName} For example, @foo will find a bean named foo, provided the evaluation
context has been configured with a bean resolver.
Indicates that a method instantiates, configures and initializes a new
@Bean object to be managed by the Spring IoC container.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Adds a description to a bean.
@Description
MVC/Web
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Associates a handler method argument with part of a multi-part
@RequestPart request.
Spring MVC provides the following convenience annotations for request mapping:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@GetMapping Shortcut for @RequestMapping(method = RequestMethod.GET)
CORS Support
Spring MVC/Web includes a single annotation for managing Cross-Origin Resource Support
(CORS):
Security
Spring Security provides the following annotations:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Performs an access-control check after the method
@PostAuthorize has been invoked.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Spring WebSocket
Spring MVC/Web includes the following annotations for working with WebSockets:
REST
Spring Data REST provides the following annotations:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates a component that should handle
@HandleBeforeLinkDelete
the beforeLinkDelete event.
Indicates a component that should handle
@HandleBeforeLinkSave
the beforeLinkSave event.
Indicates a component that should handle
@HandleBeforeSave
the beforeSave event.
Class-level annotation that indicates that the class is an
@RepositoryEvenHandler event handler for a repository.
Indicates an identifier.
@Id
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that a field should be persisted even if there are
@Persistent no getter and setter methods for it.
HATEOAS
Spring HATEOAS provides the following annotations:
@EnableHypermediaSupport
Enables support for a particular hypermedia representation type.
@EnableEntityLinks
Enables dependency injection of EntityLinks objects.
@ExposesResourceFor
Class-level annotation for controllers. Indicates which model type the controller
manages.
@Relation
Indicates the relation to be used when embedding objects in hypermedia.
Session
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Spring Session provides the following annotations:
@EnableRedisHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by Redis. Must be added to an @Configuration class.
@EnableGemFireHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by Pivotal GemFire or Apache Geode. Must be added to an @Configuration
class.
@EnableJdbcHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by a relational database. Must be added to an @Configuration class.
@EnableMongoHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by Mongo. Must be added to an @Configuration class.
@EnableHazelcastHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by Hazelcast. Must be added to an @Configuration class.
@EnableSpringHttpSession
Exposes the SessionRepositoryFilter as a bean named "springSessionRepositoryFilter"
and backed by a user provided implementation of SessionRepository. Must be added to
an @Configuration class.
Boot
Spring Boot provides the following annotations:
@SpringBootApplication
Convenience annotation that includes @Configuration, @EnableAutoConfiguration, and
@ComponentScan
@EnableAutoConfiguration
tells Spring Boot to determine how you will want to configure Spring, based on the jar
dependencies that you have added.
@EntityScan
Configures the base packages used by auto-configuration when scanning for entity
classes.
@ConfigurationProperties
Identifies a class a configuration properties class, which can then be used to control and
validate configuration.
@@EnableConfigurationProperties
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Enables support for @ConfigurationProperties annotated beans.
@ConfigurationPropertiesBinding
Qualifier for beans that are needed to configure the binding of ConfigurationProperties (often
converters).
@JsonComponent
Provides JsonSerializer and/or JsonDeserializer implementations to be registered with
Jackson when JsonComponentModule is in use.
@ServletComponentScan
Enables automatic registration of classes annotated with @WebServlet, @WebFilter, and
@WebListener.
@EnableOAuth2Sso
Enables OAuth2 Single Sign On (SSO).
@SpringBootTest
Creates an ApplicationContext object that supports testing a Spring Boot application.
@AutoConfigureMockMvc
Configures a MockMvc object for use when testing Spring Boot applications.
@SpringBootConfiguration
Indicates that a class provides Spring Boot application @Configuration. Can be used as an
alternative to the Spring’s standard @Configuration annotation so that configuration can be
found automatically (for example in tests). An application should include only one
@SpringBootConfiguration, and most idiomatic Spring Boot applications will inherit it
from @SpringBootApplication.
@TestConfiguration
@Configuration that can be used to define additional beans or customizations for a test.
Unlike regular @Configuration classes the use of @TestConfiguration does not prevent
auto-detection of @SpringBootConfiguration.
@LocalServerPort
Annotation at the field or method/constructor parameter level that injects the HTTP port
that got allocated at runtime. Provides a convenient alternative
for @Value("${local.server.port}").
@MockBean
Adds a mock bean to a Spring ApplicationContext.
@Spybean
Applies Mockito spies to a Spring ApplicationContext.
@ImportAutoConfiguration
Imports and applies the specified auto-configuration classes. Sometimes useful for
testing. Generally, @EnableAutoConfiguration should be preferred.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@JsonTest
Auto-configures Jackson ObjectMapper, any @JsonComponent beans and any
Jackson Modules.
@WebMvcTest
Used with @RunWith(SpringRunner.class) for a typical Spring MVC test. Can be used
when a test focuses only on Spring MVC components. Using this annotation will disable
full auto-configuration and instead apply only configuration relevant to MVC tests.
@DataJpaTest
Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical
JPA test. Can be used when a test focuses only on JPA components.
@AutoConfigureTestEntityManager
Can be applied to a test class to enable auto-configuration of a TestEntityManager.
@AutoConfigureTestDatabase
Can be applied to a test class to configure a test database to use instead of any
application defined or auto-configured DataSource.
@JdbcTest
Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical
JDBC test. By default, it will also configure an in-memory embedded database and
a JdbcTemplate.
@DataMongoTest
Used to test MongoDB applications. By default, it will configure an in-memory embedded
MongoDB (if available), configure a MongoTemplate, scan for @Document classes and
configure Spring Data MongoDB repositories.
@RestClientTest
Used to test REST clients. By default, it will auto-configure Jackson and GSON support,
configure a RestTemplateBuilder and add support for MockRestServiceServer.
@AutoConfigureRestDocs
Used to use Spring REST Docs in your tests. It will automatically configure MockMvc to
use Spring REST Docs and remove the need for Spring REST Docs' JUnit rule.
@WebIntegrationTest
Test class annotation signifying that the tests are "web integration tests" and therefore
require full startup in the same way as a production application (listening on normal
ports). Normally used in conjunction with @SpringApplicationConfiguration.
@SpringApplicationConfiguration
Class-level annotation that is used to determine how to load and configure an
ApplicationContext for integration tests. Similar to the standard ContextConfiguration but
uses Spring Boot’s SpringApplicationContextLoader.
@ConditionalOnClass
Matches only when the specified classes are on the classpath.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@ConditionalOnMissingBean
Matches only when the specified bean classes and/or names are not already contained
in the BeanFactory.
@AutoConfigureBefore
Used when configurations need to be loaded in a particular order.
@AutoConfigureAfter
Used when configurations need to be loaded in a particular order.
@AutoconfigureOrder
Allows for ordering certain auto-configurations that shouldn’t have any direct
knowledge of each other.
@ConditionalOnProperty
Checks whether the specified properties have the specified value.
@ConditionalOnResource
Lets configuration to be included only when a specific resource is present.
@ConditionalOnWebApplication
Matches only when the application context is a web application
@ConditionalOnNotWebApplication
Matches only when the application context is not a web application.
@ConditionalOnExpression
Lets configuration be included based on the result of a SpEL expression.
@ManagementContextConfiguration
Specialized @Configuration class that defines configuration specific for the
management context. Configurations should be registered in /META-INF/spring.factories
under the
org.springframework.boot.actuate.autoconfigure.ManagementContextConfiguration key.
@ExportMetricWriter
Qualifier annotation for a metric repository that is to be used to export metrics from the
ExportMetricReader readers.
@ExportMetricReader
Qualifier annotation for a metric reader that can be exported (to distinguish it from
others that might be installed by the user for other purposes).
@FlywayDataSource
Specifies a DataSource to be injected into Flyway. If used for a second data source, the
other (main) one would normally be marked as {@code @Primary}.
@LiquibaseDataSource
Specifies a DataSource to be injected into Liquibase. If used for a second data source,
the other (main) one would normally be marked as {@code @Primary}.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@DeprecatedConfigurationProperty
Indicates that a getter in a ConfigurationProperties object is deprecated. This annotation has
no bearing on the actual binding processes, but it is used by the spring-boot-configuration-
processor to add deprecation meta-data.
@NestedConfigurationProperty
Indicates that a field in a ConfigurationProperties object should be treated as if it were a
nested type.
Integration
Spring integration includes the following annotations:
@EnableIntegration
Enables Spring Integration infrastructure, registers built-in beans, adds
BeanFactoryPostProcessors, adds BeanPostProcessors, and adds annotation
processors.
@EnableIntegrationManagement
Enables default configuration of management in Spring Integration components in an
existing application.
@EnableMessageHistory
Enables MessageHistory for Integration components.
@EnablePublisher
Provides the registration for the PublisherAnnotationBeanPostProcessor to allow the
use of the Publisher annotation.
@IntegrationComponentScan
Configures component scanning directives for use with Configuration classes.
@Publisher
Indicates that a method (or all public methods if applied at class-level) should publish
Messages.
@GlobalChannelInterceptor
components with this annotation will be applied as global channel
ChannelInterceptor
interceptors using the provided patterns to match channel names.
@Aggregator
Indicates that a method is capable of aggregating messages.
@BridgeFrom
Marks a Bean method for a MessageChannel to produce a BridgeHandler and Consumer Endpoint.
@BridgeTo
Marks a Bean method for a MessageChannel to produce a BridgeHandler and Consumer
Endpoint.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@CorrelationStrategy
Indicates that a given method is capable of determining the correlation key of a
message sent as parameter.
@Filter
Indicates that a method is capable of playing the role of a Message Filter.
@Gateway
Indicates that an interface method is capable of mapping its parameters to a message or
message payload.
@GatewayHeaer
Provides the message header value or expression.
@IdempotentReceiver
A method that has a Messaging annotation (@code, @ServiceActivator, @Router etc.) that also
has this annotation has an IdempotentReceiverInterceptor applied to the
associated MessageHandler.handleMessage(org.springframework.messaging.Message<?>) method.
@InboundChannelAdapter
Indicates that a method is capable of producing a Message payload.
@IntegrationComponentScan
Configures component scanning directives for use with Configuration classes.
@MessageEndpoint
Stereotype annotation indicating that a class is capable of serving as a Message
endpoint.
@MessagingGateway
Provides an Integration Messaging Gateway Proxy (<gateway/>) as an abstraction over
the messaging API.
@Payloads
Marks a method parameter as being a list of message payloads, for POJO handlers that
deal with lists of messages.
@Poller
Provides the PollerMetadata options for the Messaging annotations for polled endpoints.
@Publisher
Indicates that a method (or all public methods if applied at class-level) should publish
Messages.
@ReleaseStrategy
Indicates that a method is capable of asserting if a list of messages or payload objects is
complete.
@Role
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Assigns endpoints to a role. The assigned endpoints can be started and stopped as a
group.
@Router
Indicates that a method is capable of resolving to a channel or channel name based on a
message, message header(s), or both.
@ServiceActivator
Indicates that a method is capable of handling a message or message payload.
@Splitter
Indicates that a method is capable of splitting a single message or message payload to
produce multiple messages or payloads.
@Transformer
Indicates that a method is capable of transforming a message, message header, or
message payload.
@IntegrationConverter
Registers Converter, GenericConverter or ConverterFactory beans for
the integrationConversionService.
@EnableIntegrationMBeanExport
Enables default exporting for Spring Integration components in an existing application
and all @ManagedResource annotated beans.
@EnableMBeanExport
Enables default exporting of all standard MBeans from the Spring context and all
@ManagedResource annotated beans.
@IntegrationManagedResource
Clone of ManagedResource limiting beans thus annotated so that they will only be
exported by the IntegrationMBeanExporter and prevented from being exported by other
MBeanExporters (if present).
@EnableIntegrationGraphController
Enables the IntegrationGraphController if DispatcherServlet is present in the classpath.
Cloud
Spring Cloud includes the following annotations:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Embeds the Spring Cloud Config Server in another Spring
@EnableConfigServer application.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
servers. The backends can be registered manually through
configuration or via a DiscoveryClient.
Enables Atlas metrics publishing.
@EnableAtlas
Data
Spring includes the following annotations:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates an interface for which Spring should not create an
@NoRepositoryBea
instance at runtime.
n
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
registers HateoasPageableHandlerMethodArgumentResolver, HateoasSortHand
lerMethodArgumentResolver, PagedResourcesAssembler,
and SortHandlerMethodArgumentResolver.
@PageableDefault Set defaults when injecting a Pageable into a controller method.
Defines the default Sort options to be used when injecting a Sort
@SortDefault instance into a controller handler method.
Batch
Spring Batch includes the following annotations:
@AfterChunk
Marks a method to be called after a chunk is executed.
@AfterChunkError
Marks a method to be called after a has failed and been marked for rollback.
@AfterJob
Marks a method to be called after a Job has completed.
@AfterProcess
Marks a method to be called after an item is passed to an ItemProcessor.
@AfterRead
Marks a method to be called after an item is read from an ItemReader.
@AfterStep
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Marks a method to be called after a Step has completed.
@AfterWrite
Marks a method to be called after an item is passed to an ItemWriter.
@BeforeChunk
Marks a method to be called before a chunk is executed.
@BeforeJob
Marks a method to be called before a Job is executed, which comes after a JobExecution is
created and persisted, but before the first Step is executed.
@BeforeProcess
Marks a method to be called before an item is passed to an ItemProcessor.
@BeforeRead
Marks a method to be called before an item is read from an ItemReader.
@BeforeStep
Marks a method to be called before a Step is executed, which comes after
a StepExecution is created and persisted, but before the first item is read.
@BeforeWrite
Marks a method to be called before an item is passed to an ItemWriter.
@OnProcessError
Marks a method to be called if an exception is thrown by an ItemProcessor.
@OnReadError
Marks a method to be called if an exception is thrown by an ItemReader.
@OnSkipInProcess
Marks a method to be called when an item is skipped due to an exception thrown in
the ItemProcessor.
@OnSkipInRead
Marks a method to be called when an item is skipped due to an exception thrown in
the ItemReader.
@OnSkipInWrite
Marks a method to be called when an item is skipped due to an exception thrown in
the ItemWriter.
@OnWriteError
Marks a method to be called if an exception is thrown by an ItemWriter.
@EnableBatchProcessing
Enable Spring Batch features and provide a base configuration for setting up batch jobs
in an @Configuration class, roughly equivalent to using the <batch:*> XML namespace.
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
@JobScope
Convenience annotation for job-scoped beans that defaults the proxy mode, so that it
doesn’t have to be specified explicitly on every bean definition.
@StepScope
Convenience annotation for step-scoped beans that defaults the proxy mode, so that it
doesn’t have to be specified explicitly on every bean definition.
@Classifier
Mark a method as capable of classifying its input to an instance of its output.
Aspect-oriented Programming
Spring includes a set of annotations for working with Aspect-oriented Programming (AOP):
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Declares pointcut advice that should run after the methods
matched by the pointcut. The methods must return normally.
@AfterReturning
See @AfterThrowing and @After.
Integration Testing
Spring includes a set of annotations for working with integration testing:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Class-level annotation that configures the locations of
properties files and inlined properties to be added to the set of
@TestPropertySource PropertySources in the Environment for an ApplicationContext
loaded for an integration test.
Unit Testing
Spring includes a set of annotations for unit testing:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that, if the value returned by
@IfProfileValue the name argument matches the value of
the value argument, the annotated test is enabled for
a specific testing environment.
Class-level annotation that specifies what type of
ProfileValueSource to use when retrieving profile
@ProfileValueSourceConfiguration
values configured through
the @IfProfileValue annotation.
Indicates that the annotated test method must finish
@Timed execution in a specified time period (in milliseconds).
JMX
Spring includes a set of annotations for working with Java Managed Extensions (JMX):
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that a method may be called asynchronously.
@Async
Cache Abstraction
Spring includes a set of annotations for working with caching:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Other
Spring includes a few other annotations that don’t fit into the preceding categories:
https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc