Spring Annotation Cheat Sheet 1664749230

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Spring Annotation Cheat Sheet

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

 Task Execution and Scheduling

 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

Spring’s dependency injection capability includes the following annotations:

@Resource Injects the requested resource.

Widely used dependency injection mechanism for constructors,


@Autowired methods, and interfaces.

A dependency injection mechanism that can replace


@Inject @Autowired. @Named may also be used in place of
@Autowired and @Inject.

A dependency injection mechanism that can replace


@Autowired and @Inject. @Named may also be used in place of
@Named @Autowired and @Inject. @Named is also equivalent to
@Component and @ManagedBean.

A dependency injection mechanism that can replace


@Autowired and @Inject. @ManagedBean is also equivalent to
@ManagedBean
@Component and @Named. However, it is not composable.

Injection mechanism for fields and methods that indicates a


@Value default value. Often used to get values from property files.

Marks a method (typically a JavaBean setter method) as being


'required'. That is, the method must be configured to be
@Required
dependency-injected with a value.

Indicates that a particular bean should be given preference


when multiple beans are candidates to be autowired to a
@Primary single-valued dependency. If exactly one 'primary' bean exists
among the candidates, it will be the autowired value.

Generic stereotype for any Spring-managed component.


@Component

Indicates that an annotated class is a service.


@Service

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

@ConstructorPropertie Used to explicitly name your constructor arguments.


s
Indicates 'lookup' methods, to be overridden by the container to
redirect them back to the BeanFactory for a getBean call. This
@Lookup is essentially an annotation-based version of the XML lookup-
method attribute.

Used to declare aliases for annotation attributes.


@AliasFor

Configuration

Spring’s configuration capability includes the following annotations:

Configures component scanning directives for use with


@ComponentScan
@Configuration classes.

Indicates that the primary purpose of the annotated class is


@Configuration to provide a source of bean definitions.

Defines the sort order for an annotated component. Lower


@Order values have higher priority. @Priority can replace @Order.

Defines the sort order for an annotated component. Lower


@Priority values have higher priority. @Order can replace @Priority.

Associates a value with a particular argument. More finely


@Qualifier tuned way than @Order and @Priority to control selection.

Indicates the contexts in which an annotation type is


@Target applicable.

Indicates how long annotations with the annotated type are


@Retention to be retained.

Lets you create custom annotations to use as qualifiers.


@interface

https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that an annotated class is a repository.
@Repository

Indicates that a component is eligible for registration when


@Profile one or more specified profiles are active.

Indicates that a component is only eligible for registration


@Conditional when all specified conditions match.

Allows for loading @Bean definitions from another


configuration class. Also allows for importing XML
@ImportResource
configuration files.

Enables load-time weaving, which is used by Spring to


dynamically transform classes as they are loaded into the
@EnableLoadTimeWeaving
JVM.

Registers an event listener on a public method of a bean.


@EventListener

Specifies that an event listener is asynchronous. See also:


@Async Async under Task Execution and Scheduling.

Adds a PropertySource to Spring’s Environment.


@PropertySource

JMS

Spring’s support for JMS includes the following annotations:

Add to an @configuration class to enable support for @JmsListener


@EnableJms
annotations.

Indicates that a method of a managed bean is a JMS listener endpoint.


@JmsListener

Aggregates several @JmsListener annotations. On Java 8, it can be


@JmsListener
replaced by repeatable @JmsListener annotations.
s

Indicates that a method provides the payload of a message.


@Payload

Indicates the method (or sometimes class) that responds to a message.


@SendTo

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

Spring AMQP provides the following annotations:

@Queue A queue definition used within the bindings attribute of


an @QueueBinding.
Defines a queue, the exchange it is to be bound to, and an optional
@QueueBinding
binding key. Used with @RabbitListener.
Defines an exchange to which to bind a RabbitListener queue.
@Exchange

Represents an argument used when declaring queues etc within a


@Argument QueueBinding.

Enable Rabbit listener annotated endpoints that are created behind


@EnableRabbit the scenes by a RabbitListenerContainerFactory. To be used
on @Configuration classes.
marks a method to be the target of a Rabbit message listener
@RabbitHandler
within a class that is annotated with @RabbitListener.
Marks a method as the target of a Rabbit message listener on the
@RabbitListener
specified queues (or bindings).
Container annotation that aggregates
@RabbitListeners
several @RabbitListener annotations.
Enables proxying of @RabbitListener beans to capture arguments
@RabbitListenerTes
and results (if any). Used on @Configuration classes.
t

Bean Lifecycle

Spring’s bean lifecycle management capability includes the following annotations:

@{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

Generic stereotype for any Spring-managed component.


@Component

Causes lazy resolution of a bean in the IoC container.


@Lazy

Specifies a non-default scope for a component.


@Scope

Identifies a method to be called after an instance of a bean has been


@PostConstruc
constructed. Used to populate caches and similar operations.
t

Identifies a method to be called before an instance of a bean is to be


@PreDestroy destroyed. Used to de-populate caches and similar operations.

MVC/Web

Spring provides the following annotations for web applications: Major


source: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html

@EnableWebMvc Added to a @configuration class to enable Web MVC.

Indicates that a class is an MVC controller.


@Controller

Indicates that a class is a REST controller.


@RESTController

Associates a URI path with a method in a controller.


@RequestMapping

Indicates that a method or argument contributes to a model.


@ModelAttribute

Provides access to pre-existing session attributes that are


@SessionAttribute managed globally.

Declares session attributes used by a specific handler.


@SessionAttributes

Causes the return type to be written to the response body


@ResponseBody (rather than the model).

Binds a request parameter to a method.


@RequestParam

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.

Binds a method argument to the value of a URI template


@PathVariable variable.

Indicates that a method parameter’s value should be retrieved


@Header from the message headers.

Deprecated. Use @header.


@Headers

Binds a method parameter to a request header.


@RequestHeader

Binds a method parameter to the value of the HTTP request body.


@RequestBody

Indicates a business exception.


@ResponseStatus

Allows implementation classes to be auto-detected through


classpath scanning. It is automatically enabled when using the
@ControllerAdvice
MVC namespace or the MVC Java config.

@RestControllerAdvic As @ControllerAdvice (previous) but @ExceptionHandler methods


e assume @ResponseBody semantics by default.
Configures web data binding directly within a controller class.
@InitBinder

Identifies the value part of a name/value pair in a URI path.


@MatrixVariable

Binds a method parameter to the value of an HTTP cookie.


@cookieValue

A specialization of @Scope for a component whose lifecycle is


@RequestScope bound to the current web request.

A specialization of @Scope for a component whose lifecycle is


@SessionScope bound to the current web session.

A specialization of @Scope for a component whose lifecycle is


@ApplicationScope bound to the current web application.

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)

Shortcut for @RequestMapping(method = RequestMethod.POST)


@PostMapping

Shortcut for @RequestMapping(method = RequestMethod.PUT)


@PutMapping

Shortcut for @RequestMapping(method =


@DeleteMapping RequestMethod.DELETE)

Shortcut for @RequestMapping(method = RequestMethod.PATCH)


@PatchMapping

CORS Support

Spring MVC/Web includes a single annotation for managing Cross-Origin Resource Support
(CORS):

@CrossOrigi Enables cross-origin resource sharing (CORS) on a


n path.

Security
Spring Security provides the following annotations:

Adds Spring Security configuration defined in a


WebSecurityConfigurer (often by extending
@EnableWebSecurity
WebSecurityConfigurerAdapter). Must be added to an
@Configuration class.

Class-level annotation that turns on method-level


security. Must be on an @Configuration class. You
@EnableGlobalMethodSecurity must add other annotations to each method to be
secured.

Defines a list of security configuration attributes for


@Secured business methods.

Determines whether a method can actually be invoked


@PreAuthorize or not, usually based on a user role.

https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Performs an access-control check after the method
@PostAuthorize has been invoked.

Enables only the Spring


@SecurityTestExecutionListener
Security TestExecutionListener classes (rather than all
s
Spring TestExecutionListener classes)
Runs a test as a specified mock user.
@WithMockUser

Runs a test as an anonymous user.


@WithAnonymousUser

Runs a test with user details provided by a


@WithUserDetails
custom UserDetailsService.
@WithSecurityContext Runs a test with a custom SecurityContext.
After a method has been called, iterates through a
returned collection and removes any item that doesn’t
@PostFilter
match the filter.

Before a method is called, iterates through a


collection and removes any item that doesn’t match
@PreFilter
the filter. (Used much more rarely than @PostFilter).

Enables Spring Security integration with Spring MVC.


@EnableWebMvcSecurity

Automatically resolves the


@AuthenticationPrincipal current Authentication.getPrincipal() for Spring MVC
arguments.
Convenience annotation for enabling an authorization
Server (that is, an AuthorizationEndpoint and
@EnableAuthorizationServer
a TokenEndpoint) in the current application context,
which must be a DispatcherServlet context.
Convenience annotation for OAuth2 Resource Servers,
enabling a Spring Security filter that authenticates
@EnableResourceServer
requests via an incoming OAuth2 token.

Enables configuration for an OAuth2 client in a web


application that wants to use the Authorization Code
@EhableOAuth2Client
Grant from one or more OAuth2 Authorization servers.

Applies the ChannelSecurityInterceptor(s) using


@SecuredChannel
provided interceptor() bean name(s).

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:

@EnableWebSocket Enables the processing of WebSocket requests. Must


be added to an @Configuration class.
Enables broker-backed messaging over WebSocket
@EnableWebSocketMessageBroke
using a higher-level messaging sub-protocol. Must
r
be added to an @Configuration class.
Maps a Message onto message-handling methods by
@MessageMapping matching to the message destination.

Indicates that a method parameter should be bound


to a template variable in a destination template
@DestinationVariable
string.

Maps subscription messages onto specific handler


@SubscribeMapping methods based on the destination of a subscription.

REST
Spring Data REST provides the following annotations:

Marks a repository for custom export mapping and rel


@RepositoryRestResource
attributes.

Describes the semantics of a resource.


@Description

Indicates a component that should handle


@HandleAfterCreate
the afterCreate event.
Indicates a component that should handle
@HandleAfterDelete
the afterDelete event.
Indicates a component that should handle
@HandleAfterLinkSave
the afterLinkSave event.
Indicates a component that should handle
@HandleAfterSave
the afterSave event.
Indicates a component that should handle
@HandleBeforeCreate
the beforeCreate event.
Indicates a component that should handle
@HandleBeforeDelete
the beforeDelete event.

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 how a repository should be exported and what the


@RestResource value of the rel attribute in links will be.

Ties a particular projection type to a source type. Used to


@Projection find projection interfaces at startup time.

Identifies a property to be used as version field to


@Version implement optimistic locking on entities.

Defines how Spring Data accesses values of persistent


@AccessType properties.

Declares a field as the one representing the principal that


@CreatedBy created the entity containing the field.

Declares a field as the one representing the date the entity


@CreatedDate containing the field was created.

Indicates an identifier.
@Id

Declares a field as the one representing the principal that


@LastModifiedBy recently modified the entity containing the field.

Declares a field as the one representing the date the entity


@LastModifiedDate containing the field was recently modified.

Indicates that a constructor, even one that’s package


protected, as the primary constructor used by the
@PersistenceConstructor
persistence logic.

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.

Meta-Annotation to mark a store-specific annotation as a


query annotation. This allows generic special handing of
@QueryAnnotation
finder methods on Repository interfaces.

Marks a field as read-only for the mapping framework. The


@ReadOnlyProperty field will not be persisted.

Meta-annotation to indicate annotations that mark


@Reference references to other objects.

Marks a field to be transient for the mapping framework.


@Transient

Lets String based type aliases to be used when writing type


@TypeAlias
information for PersistentEntity objects.
Indicates a controller that declares request mappings to be
@BasePathAwareControlle augmented with a base URI in the Spring Data REST
r configuration.

Identifies Spring MVC controllers provided by Spring Data


@RepositoryRestController REST.

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:

{JB: Start here: http://cloud.spring.io/spring-cloud-static/spring-cloud.html}

@RefreshScope Lets beans be refreshed dynamically at runtime.

looks for implementations of the DiscoveryClient interface


@EnableDiscoveryClient
via META-INF/spring.factories.

https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Embeds the Spring Cloud Config Server in another Spring
@EnableConfigServer application.

Enables the Netflix Eureka Service Discovery client.


@EnableEurekaServer

Enables a circuit breaker implementation for an


@EnableCircuitBreaker application.

Enables the Hystrix circuit breaker. Must go on an


application class (such as a class marked with
@EnableHystrix
@SpringBootApplication).

Indicates that a bean should be wrapped in a proxy that is


@HystrixCommand connected to the Hystrix circuit breaker.

Sets a property for the @HystrixCommand annotation. See


@HystrixProperty the @Hystrix wiki.

Enables the Hystrix dashboard. Must go on a Spring Boot


@EnableHystrixDashboard main class.

Enables the Turbine application for a Spring application.


@EnableTurbine Must go on a Spring Boot main class.

Enables the Turbine Stream application for a Spring


@EnableTurbineStream application. Must go on a Spring Boot main class.

Declares that a REST client should be created for the


@FeignClient specified interface.

Scans for interfaces that declare they are feign clients.


@EnableFeignCLients Must go on the application class.

Declares a ribbon client. Must go on an @Configuration


@RibbonClient class.

Convenience annotation that combines


@RibbonClients multiple @RibbonClient annotations on a single class
(including in Java 7).
Sets up a Zuul server endpoint and installs some reverse
@EnableZuulProxy
proxy filters in it, so it can forward requests to backend

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

Enables the binding of targets annotated


@EnableBinding with Input and Output to a broker, according to the list of
interfaces passed as value to the annotation.
Indicates a method that is a listener to the inputs declared
@StreamListener
through @EnableBinding.
Indicates that an input binding target will be created by the
@Input framework.

Indicates that an output binding target will be created by


@Output the framework.

Class annotation that identifies the class as an RxJava


@EnableRxJavaProcessor processor module.

Enables transporting of spans over a Spring Cloud Stream


@EnableZipkinStreamServer (such as RabbitMQ).

Names a span for use with a stream.


@SpanName

Indicates that a RestTemplate bean should be configured to


@LoadBalanced
use a LoadBalancerClient.

Data
Spring includes the following annotations:

@EnableJpaReposi Class-level annotation that enables JPA repositories. By default,


tories scans the package of the annotated @Configuration class for Spring
Data repositories.
@EnableJpaAuditin Class-level annotation that enables auditing in JPA. Must be on
g an @Configuration class.
Indicates the interfaces for which a repository proxy is to be
@RepositoryDefinit
created. Annotating an interface with @RepositoryDefinition will cause
ion
the same behavior as extending Repository.

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

Identifies a domain object to be persisted to MongoDB.


@Document

Indicates that the annotated field is to be stored using a DBRef.


@DBRef

Defines custom metadata for a document field.


@Field

Marks a property as being a language field.


@Language

Marks a property to be considered when doing a full-text search.


@TextScore Important: The property will not be saved when the entity is saved.

Activates MongoDB repositories. If no base package is configured


@EnableMongoRep
through value(), basePackages(), or basePackageClasses(), it will trigger
ositories
scanning of the package of annotated class.
Declares a finder query on a repository method.
@Query

Configures the JPA 2.1 EntityGraphs that should be used on


@EntityGraph repository methods.

@Lock Specifies the LockModeType to be used when executing a query.


Indicates a method should be regarded as a modifying query.
@Modifying

Applies JPA query hints to a query declared in a repository


@QueryHints interface.

Declares an appropriate TemporalType on query method parameters.


@Temporal
Can only be used on parameters of type Date.
Indicates a method that publishes domain events. A method marked
@DomainEvents with @AfterDomainEventsPublication can then be used to manipulated
the published events.
Indicates a method that manipulates published domain events (often
@AfterDomainEven
for selecting only events that meet some particular criterion).
tPublication

Automatically register the following beans for usage with Spring


@EnableSpringDat MVC: DomainClassConverter, PageableHandlerMethodArgumentResolver,
aWebSupport and SortHandlerMethodArgumentResolver. If Spring HATEOAS is on the
classpath, it also

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.

Wrapper annotation to allow declaring multiple SortDefault


@SortDefaults annotations on a method parameter.

Declares a JSON Path expression on a projection interface.


@JsonPath

Enables projection and projection method annotations that contain


@ProjectedPayload JSON or XPath expressions.

Customizes the binding of HTTP request parameters to a Querydsl


QuerydslPredicate
com.mysema.query.types.Predicate in Spring MVC handler methods.

Declares a JPA 2.1 stored procedure mapping directly on a


@Procedure repository method.

Enables Spring’s annotation-driven transaction management


@EnableTransactio
capability.
nManagement

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):

Enables support for handling components marked with


AspectJ’s @Aspect annotation. Must be used on a class that
@EnableAspectJAutoProx
is also marked with the @Configuration annotation (or
y
another annotation that includes the @Configuration
annotation).

Indicates that a class is an aspect.


@Aspect

Defines a join point.


@Pointcut

Limits matching to join points. (Not to be confused with


@target @Target for @Configuration classes.)

Limits matching to join points


@args

Limits matching to join points within types that have the


@within given annotation.

limits matching to join points where the subject of the join


@annotation point has the given annotation

Class annotation that specifies the default transaction


semantics for the execution of any public operation in the
@Transactional
class.

Declares pointcut advice that should run before methods


@Before matched by the pointcut.

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.

Declares pointcut advice that should run after the methods


@AfterThrowing matched by the pointcut have thrown an exception.

Declares pointcut advice to run after the methods matched


by the pointcut have run, whether they returned normally or
@After
threw an exception. Parallel to finally in a try-catch-finally
block.
Declares advice that runs around (potentially both before
and after) the methods matched by the pointcut. Can also
@Around determine if pointcut methods run. Do not use if @Before or
@After suffice.

Declares that matching types have a new parent.


@DeclareParents

Marks a class as eligible for Spring-driven configuration.


@Configurable

Tells the current application context to apply dependency


injection to non-managed classes that are instantiated
@EnableSpringConfigured
outside of the Spring bean factory.

Integration Testing
Spring includes a set of annotations for working with integration testing:

@BootstrapWith Specifies a custom TestContextBootstrapper class.

Defines class-level metadata that determines how to load and


@ContextConfiguration
configure an ApplicationContext for integration tests.
Class-level annotation that is used to declare that
@WebAppConfiguration the ApplicationContext loaded for an integration test should be
a WebApplicationContext.
Class-level annotation that defines a hierarchy of
@ContextHierarchy ApplicationContexts for integration tests.

Class-level annotation that indicates which bean definition


@ActiveProfiles profiles should be active.

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.

Indicates that the underlying Spring ApplicationContext has


been modified or corrupted in some manner during the
execution of a test and should be closed. When an application
@DirtiesContext
context is marked as dirty, it is removed from the testing
framework’s cache and closed.

Defines class-level metadata for configuring the


@TestExecutionListener TestExecutionListener implementations that should be
s registered with the TestContextManager.

Causes a transaction to commit rather than rollback during


testing. Use only when you want a test to modify a database.
@Commit
See @Rollback.

indicates whether the transaction for a transactional test


method should be rolled back after the test method has
@Rollback
completed. See @Commit.

Indicates that the annotated void method should be executed


@BeforeTransaction before a transaction is started for test methods configured to
run within a transaction via Spring’s @Transactional annotation.
Indicates that the annotated void method should be executed
@AfterTransaction after a transaction is ended for test methods configured to run
within a transaction via Spring’s @Transactional annotation.
Annotates a test class or test method to configure SQL scripts
to be executed against a given database during integration
@Sql
tests.

Defines metadata that is used to determine how to parse and


@SqlConfig
execute SQL scripts configured via the @Sql annotation.
Container annotation that aggregates
@SqlGroup
several @Sql annotations.

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).

Indicates that the annotated test method must be


@Repeat executed a number of times.

JMX
Spring includes a set of annotations for working with Java Managed Extensions (JMX):

Marks all instances of a Class as JMX managed


@ManagedResource
resources.

Mark a getter or setter as one half of a JMX attribute.


@ManagedAttribute

Mark a method as a JMX operation.


@ManagedOperation

@ManagedOperationParameter Define descriptions for operation parameters.


s
Define the descriptions for an operation parameter.
@ManagedOperationParameter

Class-level application that indicates whether an


@EnableMBeanExport application is an exporter of managed beans.

Task Execution and Scheduling


Spring includes a set of annotations to support task execution and scheduling:

Indicates that a method should be called on a scheduled


@Scheduled
basis.

https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc
Indicates that a method may be called asynchronously.
@Async

@EnableScheduling Enables support for the @Schedule annotation.


@EnableAsync Enables support for the @Async annotation.

Cache Abstraction
Spring includes a set of annotations for working with caching:

@Cacheable Indicates a method whose result is cacheable.

Indicates that a method performs cache eviction (removes items


@CacheEvict from a cache).

Indicates a method whose result will always be put in a cache.


@CachePut

Allows multiple nested @Cacheable, @CachePut and @CacheEvict to be


@Caching
used on the same method
Class-level annotation that allows sharing of the cache names, the
custom KeyGenerator, the custom CacheManager, and the custom
@CacheConfig CacheResolver. Placing this annotation on the class does not turn on
any caching operation. See @EnableCaching.

@EnableCaching Turns on caching in an application. Must go on an @Configuration class.


Similar to @Cacheable but can cache specific exceptions and force the
@CacheResult
execution of the method regardless of the content of the cache.
Similar to @CacheEvict but can support conditional removal if the
@CacheRemove
method throws an exception.
Similar to @CacheEvict(allEntries=true) but can support conditional
@CacheRemoveAll
removal if the method throws an exception.
@CacheDefaults Similar to @CacheConfig.
Usable with @CachePut to update the cache before or after method
@CacheValue invocation.

Optional method parameter annotation to indicate which argument(s)


should be the key. (The default is to construct the key from all the
@CacheKey
parameters, unless one or more parameters are marked
with @CacheKey.)

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:

Annotation for handling exceptions in specific handler classes


@ExceptionHandler
and/or handler methods.

Declares that a field or method parameter should be formatted as a


@NumberFormat number.

Declares that a field or method parameter should be formatted as a


@DateTimeFormat date or time.

https://github.com/Buzzardo/spring-docs/blob/master/annotation-cheat-sheet.adoc

You might also like