0% found this document useful (0 votes)
6 views24 pages

Essential Spring Annotations Guide

The document outlines important Spring annotations for managing components, dependency injection, and transaction management. It describes the lifecycle of a Spring application, including initialization, usage, and destruction phases, as well as various transaction propagation behaviors and isolation levels. Additionally, it covers Spring MVC components, their roles in web applications, and the use of Spring Boot for simplified configuration and development.

Uploaded by

Tajar Dundar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

Essential Spring Annotations Guide

The document outlines important Spring annotations for managing components, dependency injection, and transaction management. It describes the lifecycle of a Spring application, including initialization, usage, and destruction phases, as well as various transaction propagation behaviors and isolation levels. Additionally, it covers Spring MVC components, their roles in web applications, and the use of Spring Boot for simplified configuration and development.

Uploaded by

Tajar Dundar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Most important annotations

• Stereotype annotations are used to mark classes according to their purpose.


– @Component: template for any Spring-managed
component(bean).

– @Repository: template for a component used to provide data access,


specialization of the @Component annotation for the DAO
layer.

– @Service: template for a component that provides service execution,


specialization of the @Component annotation for the Service layer.

– @Controller: template for a web component, specialization of the


@Component annotation for the web layer.

– @Configuration: configuration class containing bean definitions


(methods annotated with @Bean).

• Autowiring and initialization annotations are used to define which dependency


is injected and what the bean looks like. For example.
– @Autowired: core annotation for this group; is used on dependencies to instruct
the Spring IoC to take care of injecting them. Can be used on fields,
constructors, setters and even methods mentioned in the Injection Types
section.
Use with @Qualifier from Spring to specify name of the bean to inject.
– @Inject: equivalent annotation to @Autowired from javax.
inject package. Use with @Qualifier from [Link] to specify name
of the bean to inject.

– @Resource: equivalent annotation to @Autowired from javax. annotation


package. Provides a name attribute to specify name of the
bean to inject.
– @Required: Spring annotation that marks a dependency as mandatory. It can
be used on setter methods, but since Spring 5.1 was deprecated as of in favor of
using constructor injection for required settings.
– @Lazy: dependency will be injected the first time it is used.
Although this annotation exists, avoid using it if possible. When a Spring
application is started ApplicationContext implementations
Spring Bean LifeCyCLe and Configuration eagerly create and configure all
singleton beans as part of the initialization process, this is useful because
configuration errors in the

-The @Bean annotation tells Spring that the result of the annotated method will
be a bean that has to be managed by it. The @Bean annotation together with the
method are treated as a bean definition, and the method name becomes the
bean id, so be careful with the method naming. There are more ways to change
names, but this topic is covered later in the chapter. . Declaring aliases using
stereotype annotations is not supported at the moment, but it is possible using
the @Bean annotation

-The @PropertySource annotation adds a bean of type PropertySource to Spring’s


environment that will be used to read property values from a property file set as
argument.

The configuration also requires a bean of type


PropertySourcesPlaceholderConfigurer to replace the placeholders set as
arguments for the @Value annotated properties.

. Related to bean naming is the @Description annotation, which was added in


Spring 4.x.

@Value("true") or @Value(“${[Link]}”}
@AliasFor -> This annotation is set on annotation attributes to declare aliases for
them

Injection Types

- constructor injection: The Spring IoC container injects the dependency by


providing it as an argument for the constructor
- setter injection: The Spring IoC container injects the dependency as an
argument for a setter
- field injection: The Spring IoC container injects the dependency directly as
a value for the field (via reflection and this requires the open directive in the
[Link] file)

ProxyMode
ScopedProxyMode.TARGET_CLASS,[Link],
[Link], [Link],

Enum Values
1. DEFAULT
o The default behavior is determined by the scope type.

o For singleton-scoped beans, no proxy is created.

o For other scopes (like request or session), proxying may depend on


the container setup or the specifics of the scope implementation.
2. NO
o No proxy is created for the bean.

o The actual instance of the scoped bean is injected directly into the
dependent beans.
o This may lead to issues if the bean lifecycle does not align with the
lifecycle of its dependents.
3. INTERFACES
o Creates a JDK dynamic proxy for the scoped bean.

o Proxies are based on the interfaces implemented by the bean class.

o Best suited for beans that implement one or more interfaces.

4. TARGET_CLASS
o Creates a CGLIB-based proxy for the scoped bean.

o Proxies are based on subclassing the target bean class.

o This is necessary for classes that do not implement any interfaces.

A Spring application has a lifecycle of three phases.


• Initialization: In this phase, bean definitions are read, beans are created,
dependencies are injected, and resources are allocated, also known as the
bootstrap phase. After this phase is complete, the application can be used.
• Use: In this phase, the application is up and running. It is used by clients, and
beans are retrieved and used to provide responses for their requests. This is the
main phase of the lifecycle and covers 99% of it.
• Destruction: The context is being shut down, resources are released, and beans
are handed over to the garbage collector.

Since the propertySourcesPlaceholderConfigurer modifies the declaration of a


configuration class,

SpEL is the Spring Expression language. It is quite powerful, since it


supports querying and manipulating an object graph at runtime

TEST

The @DirtiesContext, it will remove the application context after the tests are
run. There is a lot more explaining in this article: DirtiesContext annotation

@ContextConfiguration()
@ActiveProfiles()
@RunWith([Link])

Unit Testing Using JUnit 5


JUnit 5 is also known as JUnit Jupiter, and compared to previous versions of JUnit,
it is composed of several different modules from three different subprojects.
• JUnit Platform: A foundation for launching testing frameworks on the JVM.
• JUnit Jupiter: The new library for writing JUnit 5 tests.
• JUnit Vintage: A library providing engines that support execution of JUnit 3 and
JUnit 4 test
: the @Sql family: @Sql, @SqlConfig, and @SqlGroup.
@Sql( scripts = "classpath:db/[Link]", config =
@SqlConfig(commentPrefix = "`", separator = "@@") )

) @Sql(statements = "DELETE FROM PERSON", executionPhase =


[Link].AFTER_TEST_METHOD

@ActiveProfiles("dev")
@ExtendWith([Link])

@SpringBootTest(webEnvironment = [Link])
public class ApplicationTest {

AOP

The Spring Framework is composed of a few libraries.


• spring-aop provides AOP alliance API compliant components that can define
method interceptors and pointcuts so that code with different responsibilities can
be cleanly decoupled.
• spring-aspects provides integration with AspectJ.

• spring-instrument provides class instrumentation support and classloader


implementations that can be used on application servers.

The template that a pointcut expression follows can be defined as follows.


execution( [Modifiers] [ReturnType] [FullClassName].[MethodName]
([Arguments]) throws [ExceptionType])
@Before("[Link](person,se
rvice)") public void beforeSave(Person person, PersonService service) {

@AfterReturning(value="execution (* [Link].*Service+.
save(..))", returning = "result")
public void afterServiceSave(JoinPoint joinPoint, Person result) {
@AfterThrowing(value="execution(public *
[Link].*.PersonRepo+.update(..))", throwing = "e")
public void afterBadUpdate(JoinPoint joinPoint, Exception e) {
@After("[Link]() ||
[Link]()")
public void afterFind(JoinPoint joinPoint) {
@Around("[Link]() ||
[Link]()")
public Object aroundFind(ProceedingJoinPoint joinPoint) throws Throwable {

This is pretty much all you need to know about


JdbcTemplate, so you can use it properly in your code.
To summarize,
• JdbcTemplate works with queries that specify parameters using the '?'
placeholder. Chapter 5 357
• use queryForObject when it is expected that execution of the query will return
a single result
. • use RowMapper when each row of the ResultSet maps to a domain object.
• use RowCallbackHandler when no value should be returned.
• use ResultSetExtractor when multiple rows, or multiple records from different
tables returned in a ResultSet map to a single object
• REQUIRED: An existing transaction will be used or a new one will be created to
execute the method annotated with @ Transactional(propagation =
[Link]).
• REQUIRES_NEW: A new transaction is created to execute the method annotated
with @Transactional(propagation = Propagation.REQUIRES_NEW). If a current
transaction exists, it will be suspended
. • NESTED: An existing nested transaction executes the method annotated with
@Transactional(propagation = Propagation. NESTED). If no such transaction
exists, it will be created. This approach is quite similar to REQUIRED, so if the
datasource supports I think it should be mandatory to use it because it reuses
existent resources.
• MANDATORY: An existing transaction must be used to execute the method
annotated with @Transactional(propagation = MANDATORY). If there is no
transaction to be used, an exception will be thrown.
• NEVER: Methods annotated with @Transactional(propagation =
[Link] must not be executed within a transaction. If a transaction
exists, an exception will be thrown

NOT_SUPPORTED: No transaction executes the method annotated with


@Transactional(propagation = Propagation.NOT_ SUPPORTED). If a transaction
exists, it will be suspended.
• SUPPORTS: An existing transaction executes the method annotated with
@Transactional(propagation = [Link]). If no transaction exists,
the method will be executed anyway, without a transactional context. In the
following code snippet, the findById method is executed in a transaction and the
getPersonAsHtml is executed within a nested transaction. Nested transactions
work only with transaction managers in an enterprise RDBMS. And as you can
see from the log at the end of the code snippet, DataSourceTransactionManager
does not support nested transactions working with an in-memory database. This
transaction manager supports nested transactions via the JDBC 3.0 “savepoint”
mechanism, but it needs a database management system that supports
savepoints, such as an enterprise RDBMS like Oracle or SQL Server.90 Nested
transactions allow complex behavior; a transaction can start before the enclosing
transaction is completed. Depending on the application’s specifications, a
commit in a nested transaction can have no effect, and all changes will be
applied to the database when the enclosing transaction is committed. If a nested
transaction is rolled back, the enclosing transaction is rolled back to prevent
leaving the database in an inconsistent state: partial changes will not be kept.
Nested transactions can force atomic execution of multiple methods.

In Spring, there are five isolation values that are defined in the org.
[Link] enum.
• DEFAULT: The default isolation level of the DBMS.
• READ_UNCOMMITED: Data changed by a transaction can be read by a different
transaction while the first one is not yet committed, also known as dirty reads.
Dirty reads are possible at this isolation level.
• READ_COMMITTED: Dirty reads are not possible when a transaction is used with
this isolation level. This is the default strategy for most databases. But a different
phenomenon could happen here: non-repeatable read: when the same query is
executed multiple times, different results might be obtained. (For example, a
person is extracted repeatedly within the same transaction. In parallel, a
different transaction edits the person and commits. If the first transaction has
Chapter 5 Data aCCess 389 this isolation level, it will return the person with the
new properties after the second transaction is committed.)
• REPEATABLE_READ: This level of isolation does not allow dirty reads, and
repeatedly querying a table row in the same transaction will always return the
same result, even if a different transaction has changed the data and committed
while the reading occurs. The process of reading the same row multiple times in
the context of a transaction and always getting the same result is called
repeatable read. But, at this level, phantom reads are still possible. A phantom
read happens when in the course of a transaction, the execution of identical
queries leads to different result sets returned.
• SERIALIZABLE: This is the most restrictive isolation level, since transaction are
executed in a serialized way. So no dirty reads, no repeatable reads, and no
phantom reads are possible.
• timeout: By default, the value of this attribute is defined by the transaction
manager provider, but it can be changed by setting a different value in the
annotation: @Transactional(timeout=3600). The value represents the number of
milliseconds after which a transaction is considered failed, and the default value
is 1 which means timeouts are not supported.
• rollbackFor attribute values should be one or more exception classes,
subclasses of Throwable. When this type of exception is thrown during the
execution of a transactional method, the transaction is rolled back. By default, a
transaction is rolled back only when a RuntimeException is thrown. In using this
attribute, the rollback can be triggered for checked exceptions as well

@Test @Sql(dcripts = "classpath:test/[Link]", config =


@SqlConfig(encoding = "utf-8", separator = ";", commentPrefix = "--"))
@Sql( scripts = "classpath:test/[Link]", config =
@SqlConfig(transactionMode = 92 Official Javadoc: [Link]
framework/docs/current/javadoc-api/
[Link]?org/springframework/test/context/jdbc/[Link] Chapter 5 Data
aCCess 397 [Link]), executionPhase =
[Link].AFTER_TEST_METHOD )

Although the syntax is obvious, in case extra clarifications are necessary, here
they are.
• The first @Sql annotation specifies a script to be executed to save some data
into the test database before executing the test method. The @SqlConfig
declares specific SQL syntax details, so Spring can execute the [Link]
script correctly.
• The second @Sql annotation executes the script that will clean the test
database after the test execution. The attribute that specifies when the script is
executed is executionPhase, and in this case, the value used to tell Spring to
execute the script after the test method is
[Link].AFTER_TEST_METHOD.
Spring web
• DAO, where data mapping components (domain objects or entity classes), and
repository classes to manage those components, are defined.
• Service (also known as Business), where all the classes needed to transform
the user data to be passed to the DAO layer are located. The business entities
are POJOs that help with this conversion. All components specific to this layer
implement how data can be created, displayed, stored, and changed.
• Presentation, where components that implement and display the user interface
and manage user interaction reside

Spring MVC infrastructure components


– handler mappings - they map requests to handler methods and a list of
interceptors (e.g., to apply a theme to view and internationalization)
– handler adapters to invoke a handler method mapped to a request
– view resolvers to identify a view that will be rendered as response
– personalization beans for theming and internationalization
– exception resolvers, which are special methods that handle exceptions thrown
by handler methods
• User-provided web components
– handler interceptors, which are beans that define functionality to be applied in
tandem with handler method functionality (before, after, or around)
– controllers, which are beans that provide handler methods

Spring Web MVC was built to respect the MVC design pattern.
• The entry point in a Spring web application is the DispatcherServlet that is a
front
controller for the application.
• The DispatcherServlet assigns HTTP requests to special methods from classes
called
controllers by using a collection of web-specific
infrastructure beans.
• To create a Spring Web MVC application: the DispatcherServlet must be
configured as
the entry point of the application and the application configuration must contain
infrastructure MVC beans and custom controllers and view beans.
• The @EnableWebMvc annotation is used on a configuration class for a classic
Spring
Web MVC application. This annotation is not necessary in a Spring Boot web
application, as its functionality is taken care of by Spring Boot autoconfiguration.
• The MVC configuration class must implement WebMvcConfigurer or extend a
class
implementing this interface to customize the imported configuration. (Although
the only
class left is WebMvcConfigurerAdapter, which is currently deprecated.)
• The @MVC model and an application server supporting Servlet 3.0+ allow an
application without any XML configuration.
• Spring Boot is a very good choice when building a Spring web application.
• Spring Boot default configurations can be easily customized.
• Spring Boot provides starter dependencies for a multitude of Spring
applications,
including secured web applications.
• Spring Boot comes with a wide set of embedded servers, so developers do not
have to
download, install and configure them on a development environment.
• Spring Boot does not generate code; it dynamically wires up the beans and
settings, and
applies them to the application context when the application is started according
the
dependencies and configurations set.
• Spring Boot is awesome, Thymeleaf is awesome, and writing web applications
with both
is a breeze

Spring Security
When talking about securing an application the following concepts are important.
• Principal is the term that signifies the user, device, or system that could
perform
an action within the application
• Credentials are identification keys that a principal uses to confirm its identity
• Authentication is the process of verifying the validity of the principal’s
credentials
• Authorization is the process of deciding if an authenticated user is allowed to
perform a certain action within the application
• Secured item is the term used to describe any resource that is being secured

To configure Spring Security the developer must take care of three things.
• declare the security filter for the application
• define the Spring Security context
• configure authentication and authorization

The expressions have obvious names that reflect their purpose, and can be
combined to
declare complex rules. The following listing depicts only a few of the possibilities.
• hasRole('AnyRole') checks if the principal has the role given as argument
• hasAnyRole('[RoleList]') checks if the principal has any of the roles in the
RoleList
• isAnonymous() allows access for unauthenticated principals
Spring SeCurity
• isAuthenticated() allows access for authenticated and remembered principals
• isAuthenticated() and hasIpAddress('[Link]/24') allows access for
authenticated and remembered principals in the network with this IP class:
[Link]/24
• hasRole('ROLE_ADMIN') and hasRole('ROLE_MANAGER')allows access
for principals that have role ROLE_ADMIN and ROLE_MANAGER

As this methods' signatures clearly say is also stated in the official


documentation
antMatcher(String antPattern) - Allows configuring the HttpSecurity to only be
invoked when matching the provided ant pattern.

mvcMatcher(String mvcPattern) - Allows configuring the HttpSecurity to only be


invoked when matching the provided Spring MVC pattern.
Generally mvcMatcher is more secure than an antMatcher. As an example:
 antMatchers("/secured") matches only the exact /secured URL
 mvcMatchers("/secured") matches /secured as well
as /secured/, /[Link], /[Link]
SPRING REST
For each method, the HTTP standard specifies whether it is idempotent or
not. GET, PUT
, and DELETE are idempotent, whereas POST and PATCH are not.

get read reads a resource, does not change it. it is considered safe. reading
the same resource always returns the same result. it is considered
idempotent. this does not apply when the resource is not cached
and modified by a parallel operation on the server that it is being
retrieved from.

pOSt Create Used to create a new resource. Neither safe nor idempotent. two
identical pOSt requests will result in two identical resources being
created or errors at the application level.

pUt Update Most often used for update capabilities. It is not safe, as it
modifies the state on the server, but is idempotent (unless
subsequent calls of the same pUt request increments a counter within
the resource for example). Although REST seems strongly connected to HTTP,
REST principles can be followed using other protocols too, for example, POP,
IMAP and any protocol that uses URL-like paths and supports GET and POST
methods.

DeLete Delete Used to delete resources. Not safe, but can be considered
idempotent. Because requests to delete a resource that no longer
exists will always return a 404 (not found).

StringhttpMessageConverter text/plain
MappingJackson2httpMessageConverter application/*+json Only if Jackson 2 is
present on the classpath
atomFeedhttpMessageConverter application/atom+xml Only if rome is present
on
the classpath
rssChannelhttpMessageConverter application/rss+xml Only if rome is present on
the classpath
MappingJackson2XmlhttpMessageConverter application/*+xml Only if Jackson 2
is
present on the classpath

AUDIT

/beans - do you remember the BeansController that was written for a classic
Spring web application? Well, this endpoint is the advanced version of that,
because it exposes all the beans in the context and their properties such as,
aliases, scope, and dependencies. If you access this endpoint for a Spring Boot
web application, the first thing you will notice is that there are a lot more
infrastructure beans than compared to a classic Spring web application. This
is the drawback of Spring Boot applications, the infrastructure is much more
complex, some beans are part of the context although you might not use them,
there are the beans that make up the embedded server and as expected beans
that make up the actuator.
Monitoring Spring appliCationS
Chapter 9
785
• /auditevents: Exposes audit events information (by default, only events
regarding security, failed and successful login/logout operations, but it can be
extended with customized audit events)
• /caches: Exposes available caches and when suffixed with /
{cacheName} exposes that cache’s details (supports filtering)
• /conditions: Exposes information about conditions and auto- configuration
• /health: Exposes basic application health information (supports filtering)
• /info: Exposes arbitrary application info
• /configprops: Exposes all properties (including those declared with
@ConfigurationProperties) used to configure the application (if you access
[Link] you can easily find the properties
read from the [Link] file)
• /env: Exposes environment details, including the application classpath. This
endpoint supports filtering, so accessing http://
localhost:8081/actuator/env/[Link] will expose only the application
classpath.
• /loggers: Exposes information about application logging, can customize
logging while the application is running and supports filtering
• /heapdump and /threadump: Performs a heapdump182 and a threadump.183
• /mappings: Exposes information about all @RequestMapping paths
(including information about the actuator endpoint mappings)
• /metrics: Exposes metrics for the application. This endpoint supports filtering.
Just access [Link]
The metrics can be grouped into a few categories.
• JVM, Garbage Collector activity, memory consumption, thread utilization,
number of
classes, and so forth (seems a lot like what we’ve seen in JConsole, right?)
• CPU usage
• Spring-specific components activity
• Cache activity
• Datasource and HikariCP activity
• Uptime
• Tomcat usage
• Spring MVC and WebFlux request latencies (available only for Spring Boot MVC
and
WebFlux application

You might also like