Spring Framework Notes
Spring Framework Notes
2. Deletion
● Destroy methods are invoked in following order:
1. @PreDestroy (JSR-250)
2. destroy method is invoked (DisposableBean interface)
3. Custom destruction method (destroyMethod element of @Bean annotation)
Page 2
● Methods named close() and shutdown() will automatically be registered as shutdown methods by the
Spring Application Context
○ Can avoid this by setting destroyMethod element of the @Bean annotation to empty string (“”)
● Using the InitializingBean and DisposableBean interfaces to specify init/destroy methods is not
recommended, because it results in unnecessary coupling to the Spring framework
Bean Scopes
● Bean scopes allow us to adjust the visibility of a Spring bean and how the bean lifecycle is managed by
the IoC container
● There are two classic bean scopes:
1. Singleton
● A single instance of the bean exists per Spring container
2. Prototype
● A new instance of the bean is created each time the bean is requested
● There are four additional bean scopes for web-aware Spring applications:
1. Request
● One bean per http request
2. Session
● One bean per http session
3. Application
● One bean per ServletContext
4. Websocket
● One bean per WebSocket
Page 3
@Bean Annotation
● @Bean annotation is used on methods in @Configuration annotated classes, to indicate that the
method will return an instance of a bean to be managed by the Spring Container
● Default name of a bean returned by the @Bean annotated method, is the name of the method itself,
unless specified otherwise by the name element of @Bean.
● @Bean annotated methods cannot be final, since the Spring context overrides @Bean methods to
properly manage Singleton beans (using a CGLIB proxy on @Configuration annotated classes)
○ Returns a new object during first invocation of @Bean annotated method, but then the same
object thereafter
● @Bean elements
○ autowire
■ Specify how the bean’s dependencies should be autowired:
● BY_NAME
● BY_TYPE
● NO (default)
○ initMethod
■ Specify the name of the init method to be called by Application Container after bean is
constructed
○ destroyMethod
■ Specify the name of the destroy method to be called by Application Container before
bean destruction
○ name
■ Specify 1 name or a primary name + aliases, which can be used to request this bean
from the Application Container
○ value
■ Alias for name
Bean Instantiation
● Default Instantiation Behaviour
○ Singleton beans are eagerly instantiated by default, when the application context is created
○ Prototype beans are lazily instantiated by default except for one scenario:
■ A prototype bean will be eagerly instantiated if it is a dependency of a singleton bean
● @Lazy annotation can be used to specify whether a bean should be lazily instantiated, or not
○ Lazy has an element, value, for which the default value is true.
■ Can specify @Lazy(false) to make the annotated bean eagerly instantiated
○ Can use @Lazy on:
■ Methods annotated with @Bean
■ Classes annotated with @Configuration
● @Lazy will apply to all beans declared in the class
■ Classes annotated with @Component or another stereotype annotation
Page 4
PostProcessors
BeanFactoryPostProcessor
● A BeanFactoryProcessor operates on metadata for bean definitions within its same container
○ Modifies bean definitions (before any beans are instantiated) but does not instantiate beans
○ Example:
■ PropertyPlaceholderConfigurer
● Allows for using property placeholders in Spring Bean properties and replaces
them with actual values, usually from a properties file
BeanPostProcessor
● A BeanPostProcessor operates on beans in the same container, after IoC container instantiates the
bean
○ Modifies bean instances after they are instantiated
■ May even replace a bean with an AOP proxy
○ Example:
■ AutowiredAnnotationBeanPostProcessor
● Implements support for dependency injection using @Autowired annotation
● It is recommended for @Bean annotated methods returning either type of PostProcessor to be static,
so that they can be invoked early in the bean creation process
Page 5
@Configuration Annotation
● The @Configuration annotation indicates that the annotated class declares one or more @Bean
methods which generate bean definitions to be managed by the Spring container
● @Configuration annotated classes cannot be final, because they are proxied at runtime using CGLIB
○ The reason for this proxying is to grant the Spring container more control over bean creation
■ Example:
● Requests to @Bean annotated methods within the Configuration class are
intercepted for singleton-scoped beans, such that:
○ Initial request for bean returns a new instance of the object
○ Subsequent requests return a reference to the original object created
during the first invocation
Dependency Injection
● Dependency Injection is a design pattern used to implement Inversion of Control (IoC)
○ An object has its dependencies injected, instead of creating them itself, typically during the
initialization phase of its lifecycle
Stereotype Annotations
● Stereotype Annotations are annotations which fulfill a certain distinct role
○ All of the stereotype annotations are found in the org.springframework.stereotype package:
■ @Component
■ @Controller
■ @Indexed
■ @Repository
■ @Service
○ Note that some annotations, such as @RestController, are treated as stereotype annotations
(picked up by component scanning, etc.) despite not actually being so.
■ This is because these annotations themselves are annotated with a stereotype
annotation.
■ Examples:
● @RestController is annotated with @Controller
● @Configuration is annotated with @Component
Component Scanning
● Component Scanning is the process of scanning the classpath to detect spring-managed components
● The @ComponentScan annotation is used to make Spring scan the current package, along with all its
sub-packages
● Component scanning detects spring-managed components on the class-path by looking for classes
annotated with stereotype annotations, or an annotation that is annotated with a stereotype
annotation.
Page 7
@Autowired Annotation
● The @Autowired annotation is Spring’s main annotation for dependency injection
○ It allows Spring to resolve and inject dependencies from Spring’s IoC container
● @Autowired has an explicit series of steps it takes to resolve a dependency from the IoC container:
1. If exactly one instance of that type exists in the IoC container
● Inject the matching bean
2. If more than one instance of that type exists, but the dependency is annotated with @Qualifier
● Use the info associated with the @Qualifier (such as name) to select the bean
3. If more than one instance of that type exists and one is annotated with @Primary
● Use the bean annotated with @Primary
● Summary of steps:
○ Type
○ @Qualifier
○ @Primary
○ If not found, throw exception
○ Spring beans which type is a Collection or Map can be autowired, but if there were a conflict
between this bean and a Collection of Beans, preference will be given to the collection of beans
Page 8
1. Constructor Injection
● Require all constructor arguments to be resolved, unless individual arguments are
specified as non-required, by either:
1. Declaring the argument as a Java 8 Optional
● Recommended way of specifying non-required fields
2. Annotating the argument with @Nullable
2. Method Injection
● Can specify arguments as non-required by either:
1. Declaring the argument as a Java 8 Optional
● Recommended way of specifying non-required fields
2. Annotating the argument with @Nullable
3. If method is annotated with @Autowired(required = false)
3. Field Injection
● Fulfilled via reflection under-the-hood
@Qualifier Annotation
● The @Qualifier annotation adds additional control over selecting a bean to inject if there are multiple
beans of that type which exist in the IoC Container
1. Define the qualifier (name) of a bean to be created, so it can be found with this name later:
● At bean definitions
● At stereotype annotations
○ i.e. when you define a bean using either a @Bean method, or a stereotype
annotation such as @Component, you can additionally use @Qualifier to
specify the name Spring will use to refer to the bean that is created
Application Context
● The ApplicationContext is a central interface to provide configuration for an application
○ Some of the features it supports (non-exhaustive):
■ Access to environment (via getEnvironment()) → Inherited from EnvironmentCapable
■ Bean factory methods for accessing application components
■ Ability to load file resources in a generic fashion → Inherited from ResourceLoader
■ Ability to publish events to listeners → Inherited from ApplicationEventPublisher
● FileSystemXmlApplicationContext
○ Configuration classes declared and loaded from an XML file on the system
● ClassPathXmlApplicationContext
○ Configuration classes declared and loaded from an XML file on the classpath
● WebXmlApplicationContext
○ Configuration classes declared and typically loaded from XML file in /WEB-INF/
● AnnotationConfigApplicationContext
○ Beans declared in Java using @Configuration and stereotype annotations
○ For non-web application, also requires Component Scanning to discover these classes
● AnnotationConfigWebApplicationContext
○ Equivalent to AnnotationConfigApplicationContext, but for web application
○ Can use web.xml or WebApplicationInitializer (Spring 3.1+) to register servlets
Environment Abstraction
● The Environment is an interface representing the environment in which the application is running
2. Properties
● A property is a value which can originate from a variety of sources, such as:
○ JVM system properties
○ System environment variables
○ XML or YAML property files on the classpath
● The Environment object provides a convenient interface to configure property
sources and resolve property values
● Application-level beans should typically not interact with the Environment directly
○ Should instead inject property values by using @Value annotation with a property placeholder
specified in the format ${ … }
■ At runtime, property values will be replaced by a property placeholder configurer such as
PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware
■
● EnvironmentAware vs. EnvironmentCapable:
○ Standard (non-web)
■ StandardEnvironment is the basic environment for non-web applications
○ In a web environment:
■ ContextLoaderListener is in charge of creating a WebApplicationContext
Page 12
@Value Annotation
● The @Value annotation is used to inject scalar/literal values into Spring
● ${ foo.bar } is the format for specifying a property name to be injected, where foo.bar is the property
● A default value can be specified using colons if the original value is not available.
○ Examples:
■ @Value(“${original.value:${fallback.value}}”)
■ @Value(“${original.value:#{null}}”)
■ @Value(“${original.value:my default string val}”)
■ @Value(“${object.boolean:true}”)
● #{...} syntax is used for SpEL, where the expression would be placed within the brackets
● The ‘T()’ operator can be used to specify an instance of java.lang.Class (the ‘type’)
○ T() references to types within java.lang do not need to be fully qualified but all other type
references must be fully qualified
● SpEL supports:
○ Literal expressions (String, Numeric, Boolean, null)
○ Collections (arrays, lists) and Maps
○ Method invocation
○ Operators (+, -, /, %, <, >, ==, =) and Ternary Operator (cond == val ? yes : no)
● Spring beans
○ To reference Spring beans in the context, use @. For example:
■ #{ @beanName }
■ #{ @beanName.method() }
■ #{ @beanName.value }
○ OFF
■ Compiler is off (default)
○ IMMEDIATE
■ Expressions are compiled ASAP
● Typically after the first interpretation
■ If the compiled expression fails (typically due to a type changing) then the caller of the
expression will receive an exception
○ MIXED
■ In mixed mode, expressions silently switch between interpreted and compiled mode over
time
● After some number of successful runs, expressions switch to compiled form
● If something goes wrong (such as a type changing), then the expression will
switch back to interpreted form again
○ Will switch back and forth continuously
○ The exception that would have been thrown in the IMMEDIATE mode, is
instead handled internally
Page 15
Proxies
● A proxy object is a decorator
○ Proxy objects are indistinguishable from the objects they proxy
■ Same public methods
■ The proxy object has a reference to the object it proxies
■ Other objects interact with the proxy class, instead of the proxied class
● If an object is proxied, the IoC container will provide the proxy object, instead of the original object
● Advantages of Proxy
○ Can add behaviour to existing beans
■ Examples: transaction management, logging, security
○ Separate cross-cutting concerns from business logic
● Disadvantages of Proxy
○ May make code confusing, especially if multiple layers of proxies
○ Can only throw checked exceptions as declared on the original method
○ May incur overhead
○ Proxy may cause identity issues
■ Comparing objects will result in error
CGLIB Proxy
● A subclass of the proxied class
● Limitations:
○ Proxied class must be non-final
■ Subclasses cannot be created from a final class
○ Proxied class methods must be non-final
■ Final methods cannot be overridden
○ Requires a 3rd party library
■ Included in Spring framework, just not native to Java
○ Does not support self-invocation
● AOP benefits
○ Avoid code duplication
○ Avoid mixing business logic with cross-cutting concerns
■ E.g., it is beneficial to separate logging from the core business logic
○ Also:
■ Cleaner implementation of cross-cutting concerns
■ Easily modify existing code
■ Easily trace code
Page 17
AOP Terms
● Aspect
○ Spring beans implementing advice
○ Done in spring using @Aspect annotation
● Pointcut
○ A pointcut selects one or more join points in an application
○ Done in Spring using @Pointcut annotation
● Join Point
○ A joinpoint is a point in the execution of a program where additional behaviour
can be inserted using AOP
○ Spring AOP only supports method invocation join points
■ Other types exist outside of Spring AOP (constructor invocation, etc.)
● Advice
○ Additional behaviour to be executed at join points
○ Advice is functionality that is implemented before/after/around a join point and
referenced by a pointcut
@Aspect Annotation
● Spring beans implementing advice are annotated with the @Aspect annotation
○ These beans are effectively aspects
@Pointcut Annotation
● Methods that are part of an aspect can be annotated to represent a pointcut using the
@Pointcut annotation
● Pointcuts (and methods annotated with pointcuts, which are thus representing a
pointcut) can later be combined with logical operators ( &&, ||, ! ) when referencing them
in advice annotations
Example pointcuts
bean(myService) Selects join points on the Spring bean with the name
“myService”
Pointcut Designators
execution The most common designator for matching execution join points
Usage:
execution([method visibility] [return type] [package].[class].[method]([parameters] [throws exceptions]))
Usage: within(path.to.className)
this Matches join points where the bean reference (Spring AOP proxy) is an instance of the given type
(proxy object) ● Use this for CGLIB-based proxy, since the proxy itself is a subclass
CGLIB
Usage: this(path.to.interface)
target Matches join points where the target object (application object being proxied) is an instance of the
(proxied object) given type
JDK ● Use this for JDK-based proxy, since the proxy itself will implements interface, but is not a
subclass
Usage: target(path.to.proxied.class)
args Matches join points where the arguments are instances of the given type(s)
@target Matches join points where the class of the executing object has an annotation of the given type
Usage: @target(path.to.Annotation)
@args Matches join points where the runtime type of arguments passed has annotations of the given
type(s)
Usage: @args(path.to.Annotation)
@within Matches join points within types (Classes) that have the given annotation
Usage: @within(path.to.Class)
@annotation Matches join points where the executing method has specified annotation
Usage:@Annotation(path.to.Annotation)
Usage: bean(myBeanName)
Page 20
Advice
● Advice refers to the additional behaviour that is executed at join points using AOP
● Advice is associated with a pointcut expression, and runs before, after, or around
method executions matched by the pointcut
After Returning Executed after successful method execution (after join point has returned)
● Only executed if a join point has completed with no exceptions
Annotation:
@AfterReturning Example use-cases:
● Data validation → Validate data produced by method
● Statistics → Count # of successful method invocations
After Throwing Executed after execution of a join point which resulted in an exception being thrown
● Only executed if a join point threw an exception (but cannot catch exception)
Annotation:
@AfterThrowing Example use-cases:
● Error handling → Save additional info connected to error, raise alert
● Statistics → COunt # of errors related to invocation of method
Example use-cases:
● Around is the most powerful advice type, can be used for all above use-cases, and more
Page 21
● There are two primary types of objects you can add as arguments to your
advice-annotated methods to provide enhanced functionality, described below:
1. JoinPoint
● A parameter of the type JoinPoint can be added to methods implementing any
of the following advice:
○ Before, After (finally), After Returning, After Throwing
● If the JoinPoint parameter is present, it must be the first argument of the advice
method
● JoinPoint holds static information, such as method signature, and also stores
state information such as:
○ Reference to the target object through getTarget()
○ Reference to the currently executing object through getThis()
2. ProceedingJoinPoint
● A parameter of the type ProceedingJoinPoint is exclusively available to
methods implementing Around advice
○ Can invoke Around advice without using ProceedingJoinPoint
parameter, but would not be able to invoke the target method
○ Proceed()
■ Invokes the target method without passing parameters
■ Returns the result of the target method execution
■ May throw a Throwable exception
○ Proceed(Object[] args)
■ Same as Proceed(), except passes an array of objects as
argument to the method to be invoked
Page 22
Weaving
● Weaving is the process of combining advice implemented by aspects with join points:
○ Runtime Weaving
■ Proxy objects are created at runtime when the application is run
■ Proxy objects are used instead of original objects
■ Spring AOP uses runtime weaving exclusively
AOP Proxies
● There are two primary types of proxies:
1. JDK Dynamic Proxy
○ Default for Spring AOP
○ Included in Java Runtime Environment
○ A proxy that implements all interfaces that the target object
implements
2. CGLIB Proxy
○ 3rd party library, creates proxy objects at runtime
○ Used when Spring Bean to be proxied does not implement any
interfaces
○ Possible to set CGLIB to default by setting:
● @EnableAspectJAutoProxy(proxyTargetClass=true)
● Proxy Limitations:
● JDK proxy and CGLIB proxy both do not support self-invocation in Spring AOP
● CGLIB Proxy
○ Class to be proxied must not be final (cannot subclass otherwise)
○ Method(s) must not be final (cannot override in subclass otherwise)
○ Only public and and protected methods will be proxied
Page 23
1. Checked Exceptions
● Forces developers to implement error handling in the form of:
○ Try/catch blocks
○ Throwing exception in method signature
● Can result in cluttered code, unnecessary coupling to underlying methods
2. Unchecked Exceptions
● Gives developers the freedom to decide where to implement error
handling
● Removes coupling relating to exceptions
● The DataAccessException class and all of its subclasses are related to the data
access exception hierarchy
● This exception hierarchy aims to let user code find and handle errors that occur without
needing to know the details of the particular data access API (e.g. JDBC) in use
DataSource classes
● The DataSouce class is the preferred means of establishing a connection to a database
○ All Spring DataSource classes implement the javax.sql.DataSource interface
1. Standalone Application
○ Create it programmatically, like any other bean, for example:
○ Example:
spring.datasource.url = jdbc:mysql://localhost:8080/my-db
spring.datasource.username = user
spring.datasource.password = pass
JDBC Template
● The JdbcTemplate class simplifies the use of JDBC by implementing common
workflows for querying, updating, statement execution, etc.
JDBC Connections
● JdbcTemplate manages connections to db for every method called:
● Acquires connection immediately before executing operation
● Releases connection immediately after executing operation
● Connection pooling
○ Connection pooling is a strategy in which the application manages a cache of
database connections that can be reused for future requests to the database
■ Creating db connections can be expensive
● In connection pooling, connections are retrieved from the pool
when needed, and placed back in the pool after they’ve been used
○ This way, new connections never need to be established
■ Using a connection pool can enhance application performance
Page 26
ResultSet
● ResultSet is an interface provided by the java.sql package
○ A ResultSet represents a database result set, which is the result of executing a
statement which queries the database
○ The ResultSet interface provides getter methods (getBoolean, getLong, etc.) for
retrieving column values in the current row
■ Can retrieve column values using column name or column index number
batchUpdate(...) Issue multiple SQL updates on a single JDBC statement using batching
update(...) Issue single SQL update operation (i.e., insert, update, or delete)
Page 27
● When using JdbcTemplate for the above callbacks, don’t have to worry about
SQL-related exception handling
○ JdbcTemplate will catch SQLException and handle them
Page 25
JDBC Template
● The JdbcTemplate class simplifies the use of JDBC by implementing common
workflows for querying, updating, statement execution, etc.
JDBC Connections
● JdbcTemplate manages connections to db for every method called:
● Acquires connection immediately before executing operation
● Releases connection immediately after executing operation
● Connection pooling
○ Connection pooling is a strategy in which the application manages a cache of
database connections that can be reused for future requests to the database
■ Creating db connections can be expensive
● In connection pooling, connections are retrieved from the pool
when needed, and placed back in the pool after they’ve been used
○ This way, new connections never need to be established
■ Using a connection pool can enhance application performance
Page 26
ResultSet
● ResultSet is an interface provided by the java.sql package
○ A ResultSet represents a database result set, which is the result of executing a
statement which queries the database
○ The ResultSet interface provides getter methods (getBoolean, getLong, etc.) for
retrieving column values in the current row
■ Can retrieve column values using column name or column index number
batchUpdate(...) Issue multiple SQL updates on a single JDBC statement using batching
update(...) Issue single SQL update operation (i.e., insert, update, or delete)
Page 27
● When using JdbcTemplate for the above callbacks, don’t have to worry about
SQL-related exception handling
○ JdbcTemplate will catch SQLException and handle them
Page 28
Transactions
● A transaction is a task that takes place as a single unit of work
○ A transaction is a cross-cutting concern
○ A transaction is all or nothing
1. Local Transactions
● Local transactions are associated with one single resource
○ A resource refers to something such as a database
2. Global Transactions
● Global transactions are associated with multiple resources
○ For example, two or more databases within a transaction
● JDBC AutoCommit
○ AutoCommit is a property of a DB connection which causes each SQL statement
to be executed in its own transaction, committed upon statement completion
○ AutoCommit violates atomicity, since AutoCommit makes it impossible to perform
multiple SQL statements as a single unit of work
○ AutoCommit can be disabled using .setAutoCommit(false) on a JDBC connection
Page 29
Isolation levels
● Isolation levels determine how changes by other transactions are visible within the
current transaction, prior to being committed
Serializable Transaction can see no changes from other transactions (locking at all levels)
(highest isolation level) ● Read-Write locks are held until end of transaction
● Range locks are held until end of transaction
Repeatable Reads Transaction will always receive the same result set when repeating a read
● Read-Write locks held until end of transaction
Read Committed Transaction cannot read uncommitted data from other transactions
● Read locks held until end of select statement
● Write locks held until end of transaction
Read Uncommitted Transaction can read uncommitted data from other transactions
(lowest isolation level) ● No locks
● Other transactions can see changes by this transaction that are not
committed
● There are three main errors that may occur as a result of a transaction’s isolation level:
○ Phantom Read, Non-Repeatable Read, Dirty Read
● The errors and which isolation levels they occur in is categorized in the table below:
● To prevent phantom reads, use an isolation level that uses range locks
○ Serializable isolation level uses range locks
2. Non-Repeatable Reads
● Occur when data is read twice inside the same transaction, but second read
returns a different value
○ (Reading original value cannot be repeated, hence non-repeatable)
● To prevent non-repeatable reads, use an isolation level that uses read locks
and write locks
○ Serializable and Repeatable Read isolation levels use range locks
3. Dirty Reads
● Occur when uncommitted data has been read from a row that has been modified
by another running transaction
Transaction A - First Read In the scenario on the left, a dirty read occurs:
● select * where id = 5 ● The second read returns a different
Transaction B - Write (with/without commit) result than the first read, because it
● update table (change) where id = 5 captures the changes made by
Transaction A - Second Read transaction B’s write operation (even
● select * where id = 5 if the write was not committed)
@EnableTransactionManagement Annotation
● @EnableTransactionManagement enables Spring’s annotation-driven transaction
management capability
○ Exactly 1 class in a project should be annotated with this method
Element Description
mode Define the type of advice to be used with transactions. Two options:
● AdviceMode.ASPECTJ
● AdviceMode.PROXY (default)
order Precedence of transaction advice when more than one advice is applied:
● Default value = Ordered.LOWEST_PRECEDENCE
● Local Transactions
○ A transaction which uses exactly 1 resource (i.e., exactly one database)
○ Classes that allow for local transactions:
■ PlatformTransactionManager → Generic transaction manager
■ JpaTransactionManager → Transaction manager for JPA
Page 33
1. TransactionInterceptor
■ Used by Spring AOP proxy for two primary reasons:
2. PlatformTransactionManager
■ Used by TransactionInterceptor (at @Transaction annotated join points)
to handle transactions (create new, commit, rollback, etc.)
TransactionInterceptor
● TransactionInterceptor uses two classes to intercept & manage transaction
○ Note: Neither of these classes are stored as fields in the object.They are
expected to be passed into each TransactionInterceptor method invocation.
1. TransactionManager
● Used to manage transactions (create new, commit, rollback, etc.)
TransactionManager
● Classes implementing the TransactionManager interface are used to manage
transactions (evident from the name)
○ TransactionManagers are typically not to be used as an API - they are just
leveraged by AOP to support transactions in Spring applications
● One of the main classes used which implement the TransactionManager interface are
PlatformTransactionManager.
Transaction Propagation
● Transaction propagation determines how an existing transaction is used
Rollback Policy
● A rollback is the process of restoring a database or program to a previously defined
state, typically to recover from an error.
● To specify other types of exception that should cause rollback, use the rollbackFor
element of the @Transactional annotation
○ Can use the noRollbackFor to do the opposite
● Can control rollback behaviour in tests, which is covered in the testing section
Page 36
Entities
EntityManagerFactory
● EntityManagerFactory is an interface used to interact with a persistence unit (like a DB)
EntityManager
● EntityManager is an interface used to interact with entity instances
○ These entity instances exist within a persistence context
@Entity Annotation
● The @Entity annotation defines that a class can be mapped to a table
○ Essentially represents an instance in a database table
● When you create a new entity class, you have to do at least two things:
● Note: can also define custom primary key class, instead of using a
primitive data type, in which case you must use @EmbeddableId instead
Page 38
@Id Annotation
● @Id is used to mark a property within an entity class as the primary key
@Embeddable Annotation
● Custom classes representing primary keys are annotated with @Embeddable
@PersistenceContext Annotation
● @PersistenceContext injects a proxy of an EntityManager to a class
● The injected EntityManager proxy will vary based on whether a transaction exists:
○ If transaction exists:
■ Injects existing EntityManager proxy associated with current transaction
@PersistenceUnit Annotation
● Similar to @PersistenceContext, except inject an EntityManagerFactory
Component Concerns
● Advantages of MVC:
○ Re-use of model and controller, with different views
○ Separation of concerns → Increased maintainability and extensibility
● To leverage Spring MVC, you must have spring-mvc.jar on the classpath, or:
○ Spring-boot-starter-web starter
DispatcherServlet
● DispatcherServlet is a servlet (process which handles requests)
○ It implements the front controller design pattern
1. Handle requests
● Delegates requests to handlers
2. Resolve views
● Maps view names to view instances
3. Handle exceptions
● Handles exceptions, by mapping them to an error view
@Controller Annotation
● @Controller annotates classes that implement web controllers
@ResponseBody Annotation
● @ResponseBody annotation is used when you want the web response body to contain
the result produced by the controller method. @ResponseBody is applied at:
○ Class level → for which it applies to all methods in the class
○ Method level
● Web response body will contain the serialized result of the controller method’s return
value, after it has been processed by a HttpMessageConverter
@RestController Annotation
● The @RestController annotation is applied at class level.
● It is equivalent to applying both @Controller and @ResponseBody on a single class
Page 45
@RequestMapping Annotation
● The @RequestMapping annotation is used to control how a request URL will map to
controller methods
○ Is applied to @Controller/@RestController annotated classes
● Example, if the base URL is “http://localhost:8080”, then the helloWorld() function in the
code below will map to “http://localhost:8080/hello/world”:
@RestController
@RequstMapping(“/hello”)
public class MyRestController {
@RequestMapping(“/world”)
public String helloWorld() {
return “hello world!”
}
}
Element Description
@PatchMapping @DeleteMapping
● Example:
○ @GetMapping(...) == @RequestMapping(...method=RequestMethod.GET)
4. The method in the controller is executed, and returned in response. May either:
● May return a view (with model rendered)
● May return a model
Page 47
@RequestParam Annotation
● @RequestParam binds request parameters to method parameters
○ I.e., maps query string parameters to handler method arguments
@PathVariable Annotation
● @PathVariable binds a variable in the primary path of a request to method parameters
○ I.e., maps part of the URL to handler method arguments
○ Use {...} syntax to define placeholders in the @RequestMapping template String
for each path variable
Web.xml
● Web.xml is a configuration file for web applications in Java.
○ Helps servlet container decide:
■ Which classes to load
■ Which parameters to set in the context
■ How to intercept requests coming from browsers (i.e., URL patterns)
Page 49
Annotation Description
Annotation Description
@ResponseBody Response is created from the serialized result of the controller method
result, processed by an HttpMessageConverter
@ModelAttribute Model attribute with name specified in the annotation is added to the
model with value being the result of the controller method
Page 50
Class Description
WebRequest Contains:
● Context path (i.e., the prefix URL of the application)
● Request params
● User principal
● Etc.
Class Description
Reactive Types Alternative to DeferredResult for use with Reactor, RxJava, etc.
Module 5 - Security
Authentication vs. Authorization
● Authentication is the process of verifying that a user is who they claim to be
○ Example → Verifying username & password combination
SecurityContextHolder Object
● SecurityContextHolder is the heart of Spring
Security’s authentication model
Authentication Object
● Authentication serves two main purposes within
Spring Security:
1. Input to AuthenticationManager, to provide credentials to authenticate a user
2. Represents the currently authenticated user
● Authentication contains:
○ Principal
■ Identifies the user. (e.g., UserDetails)
○ Credentials
■ Often a password.
■ Usually cleared after authentication, to avoid a memory leak
○ Authorities
■ The high level permissions a user is granted.
■ .getAuthorities() → Returns a Collection of GrantedAuthority objects
Page 51
Class Description
Reactive Types Alternative to DeferredResult for use with Reactor, RxJava, etc.
Filter Object
● Spring Security’s servlet support is based on Servlet Filters
○ These filters implement javax.servlet.Filter interface
● Filters may:
○ Prevent downstream Filters or Servlet from being invoked
○ Modify request or response
DelegatingFilterProxy Object
● Spring provides a Filter implementation named
DelegatingFilterProxy
○ Allows bridging between the Servlet container’s lifecycle
and Spring’s ApplicationContext
AuthenticationManager Interface
● AuthenticationManager is the API
which defines how Spring Security’s
Filters perform authentication
ProviderManager Object
● The most common implementation of AuthenticationManager is ProviderManager
AuthenticationProvider Interface
● AuthenticationProviders are injected into ProviderManager
○ Can implement your own AuthenticationProvider as a bean which implements
the AuthenticationProvider interface
GrantedAuthority object
● A GrantedAuthority is a high-level (application-wide) permission that a user is granted
○ Stored by Authentication object within a SecurityContext
1. Web Security
● Based entirely on Servlet Filters
2. Method Security
● Uses a Spring AOP proxy that inherits from AbstractSecurityInterceptor
○ Applied to method invocation on objects secured with Spring
Security
Page 56
RequestMatcher
● A RequestMatcher is used to match incoming requests (HttpServletRequest)
● mvcMatchers("/services") matches:
○ “/services”
○ “/services/”
○ “/services.html”
○ “/services.abc”
FilterChainProxy Object
● Spring Security’s Servlet support is contained
within FilterChainProxy
● Advantages of FilterChainProxy:
● The order of which these SecurityFilterChains are defined matters, since the first one
to match the request will be the chosen delegate
SecurityFilterChain Object
● SecurityFilterChain is used by FilterChainProxy
○ Determines which one of its Security Filters should be invoked for a request
Step Description
1 The request is handled by a Servlet Filter bean (i.e. DispatcherServlet) which matches the request
● This Servlet Filter bean is wrapped in a DelegatingFilterProxy, so that the Servlet container can be
aware of it despite it being a Spring bean
2 The DelegatingFilterProxy passes the request to Spring Security’s provided FilterChainProxy instance
● The request is delegated to the first SecurityFilterChain which matches the request
○ Recall: The order of SecurityFilterChains within the FilterChainProxy is important
4 The SecurityFilterChain iterates over its list of Filters and applies them order
Method Security
● Spring Security allows you to enable security on a method level of granularity
● Method-level is the only level of security which does not expose a web interface
jsr250Enabled ● @RolesAllowed
securedEnabled ● @Secured
@PreAuthorize Determines an authenticated principal’s eligibility to invoke a method using a SpEL expression
@PostAuthorize
@PreAuthorize → Evaluates SpEL expression before a method is invoked
Apply at: @PostAuthorize → Evaluates SpEL expression after a method has been invoked
Method & Class levels
● Use built-in object returnObject in SpEL expression to reference return value of method
● If the SpEL expression returns false, an AccessDeniedException will be thrown
@PreFilter Filters a list by evaluating a SpEL expression for each element of the list
@PostFilter
@PreAuthorize → Filters a list passed as an input parameter before method is invoked
Apply at: @PostAuthorize → Filters a list returned from method after method is invoked
Method & Class levels
● Use built-in object filterObject in SpEL expression to reference list element
● If the SpEL expression returns false for an element, the element is removed from the list
@RolesAllowed Determines an authenticated principal’s eligibility to invoke a method using a SpEL expression
Apply at: ● @RolesAllowed is a JSR 250 annotation
Method & Class levels ● Not a part of Spring Security, must be on the classpath (javax.annotation.security)
@Secured Supports more than role-based security, but does not not support SpEL
Apply at: method level ● Considered legacy, use @PreAuthorize instead
Page 60
PreAuthorize/PostAuthorize Examples
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
public boolean isValidUsername(String username) { … }
● Will throw an exception if the principal does not have role of “ROLE_VIEWER” or “ROLE_EDITOR”
@PreAuthorize("#username == authentication.principal.username")
public String getMyRoles(String username) { … }
● Will throw an exception if the username parameter is not the same as the principal’s username
@PostAuthorize("returnObject.owner == authentication.name")
public String getMyRoles(String username) { … }
● Will throw an exception if the return object’s owner property is not the same as the principal’s name
PreFilter/PostFilter Examples
@PreFilter("filterObject != authentication.principal.username")
public String doSomethingWithUsernames(List<String> usernames) { … }
● Will filter the input list of Strings, such that the list does not include the principal’s username
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() { … }
● Will filter the returned list of Strings, such that the returned list by the method does not include the
principal’s username
RolesAllowed Examples
@RolesAllowed("ROLE_VIEWER")
public String getUsername() { … }
● Will throw an exception if the principal does not have role of “ROLE_VIEWER”
● Will throw an exception if the principal does not have role of “ROLE_VIEWER” or “ROLE_EDITOR”
Secured Example
@Secured("ROLE_VIEWER")
public String getUsername() { … }
● Will throw an exception if the principal does not have role of “ROLE_VIEWER”
Page 58
Step Description
1 The request is handled by a Servlet Filter bean (i.e. DispatcherServlet) which matches the request
● This Servlet Filter bean is wrapped in a DelegatingFilterProxy, so that the Servlet container can be
aware of it despite it being a Spring bean
2 The DelegatingFilterProxy passes the request to Spring Security’s provided FilterChainProxy instance
● The request is delegated to the first SecurityFilterChain which matches the request
○ Recall: The order of SecurityFilterChains within the FilterChainProxy is important
4 The SecurityFilterChain iterates over its list of Filters and applies them order
Module 6 - REST
REST
● REST stand for REpresentational State Transfer
● Allows clients to access and manipulate text representations of resources
REST Pillars
Pillar Description
● Statelessness
○ Ensures request can be processed by any node in a cluster of services
○ State (if necessary) is part of request
● Cacheability
○ REST responses can be cached
■ Request responses do not have to proceed to actual service
● Improve network efficiency, reduce load of service
● Layered System
○ A layered system allows for introducing intermediaries, such as a load balancer
Security REST itself does not supply security, but offers a layered system
● Can add security later in the application lifecycle, to one of the layers
● Examples:
○ Authentication → Control access to REST system
○ Encryption → Protect messages of REST system in transit
Interoperability REST supports different formats of representation for messages transferred to/from clients
● Clients can specify which format they wish to receive data in:
○ JSON, XML, HTML, etc.
● Resources are identified using URIs, and does not rely on a specific language or
implementation
○ REST allows for a fixed set of operations on resources
Page 63
HTTP Methods
Operation HTTP Verb
Create POST
Read GET
Update PUT
Delete DELETE
@RequestBody
● @RequestBody is applied to parameters of controller methods
@ResponseBody
● @ResponseBody is applied at:
○ Method level
○ Class level → For which it applies to every method in the class
● It is used to set the web response body to the result returned by the annotated
controller method’s return value
@RestController
● @RestController is a special stereotype annotation
○ Can be applied to classes
● A @RestController annotated class is identical to annotating that same class with the
above two annotations
@ResponseStatus
● @ResponseStatus is used to specify the HTTP response status and reason returned in
a response, using the following elements:
○ code → Status code of the response
○ reason → Reason used for the response
HttpMessageConverter
● The HttpMessageConverter interface specifies properties of a converter that can:
1. Convert HttpInputMessage to object of specified type
2. Convert an object to a HttpOutputMessage
● Example classes:
Class Name Description
RestTemplate
● RestTemplate implements a synchronous HTTP client which simplifies sending request
and enforces RESTful principles
○ Uses Template design pattern (similar to JdbcTemplate) but for REST instead
of persistence
● RestTemplate provides an API (abstraction layer) to easily send APIs and handles
many things automatically such as content-type, conversion of objects and types, etc..
delete(...), getForObject(...), Convenient methods for setting HTTP request types and sending request
postForObject(...), put(...), etc.
exchange(...) Most powerful, hardest to understand, used when no other functions fulfil needs
Page 64
@RequestBody
● @RequestBody is applied to parameters of controller methods
@ResponseBody
● @ResponseBody is applied at:
○ Method level
○ Class level → For which it applies to every method in the class
● It is used to set the web response body to the result returned by the annotated
controller method’s return value
@RestController
● @RestController is a special stereotype annotation
○ Can be applied to classes
● A @RestController annotated class is identical to annotating that same class with the
above two annotations
@ResponseStatus
● @ResponseStatus is used to specify the HTTP response status and reason returned in
a response, using the following elements:
○ code → Status code of the response
○ reason → Reason used for the response
Module 7 - TESTING
Spring in Tests
● Unit Tests
○ Spring Framework is not commonly used to perform unit tests
■ Dependency Injection is generally not needed
● Integration Tests
● Spring Framework is commonly used in integration tests
○ Ensures classes and files used by the framework are correct
● Integration tests are used to test several modules of software, when combined
together as a whole
2. ApplicationContext definition
■ Must be configured to be shared
■ Context definition is configured using the annotations:
● @ContextConfiguration
● @ActiveProfiles
● @TestPropertySource
○ Use a base class for all tests which will contain context configuration
○ Use a base interface for all tests classes which will contain context configuration
○ Use custom annotation for all test classes which will contain context configuration
● Context Instance is always reused in tests by default, as long as the following match:
○ @ContextConfiguration, @ActiveProfiles, and @TestPropertySource
@ContextConfiguration
● @ContextConfiguration annotation defines metadata for loading and configuring the
ApplicationContext for integration tests
Element Description
loader Classes implementing the ContextLoader interface that will be used to load the
application context
locations Locations of XML config files to create the application context from
@WebAppConfiguration Annotation
● @WebAppConfiguration is a class-level annotation which declares that the integration
test requires a WebApplicationContext
○ Triggers creation of a MockServletContext for the test’s ServletContext
Annotation Description
@ActiveProfiles Declares which active bean definition profiles should be used when
● class-level loading ApplicationContext for test classes
@DirtiesContext Marks the test as one which modifies the context state, meaning context
● class level will be recreated at a later point
● method level
Can specify the modes depending on where annotation is applied:
● Class-level (classMode element)
○ BEFORE_CLASS
○ AFTER_CLASS
○ BEFORE_EACH_TEST_METHOD
○ AFTER_EACH_TEST_METHOD
@TestPropertySource Configure locations of property files and declare inline properties which
● class-level should be used to configure the ApplicationContext for tests
○ These will register the loading of an ApplicationContext for the test class
@BeforeTransaction Used to indicate that the annotated void method should be executed
before a transaction is started
@AfterTransaction Used to indicate that the annotated void method should be executed
after a transaction is started
@Before Indicates that a method should be run before each test case
@After Indicates that a method should be run after each test case
@BeforeClass Indicates that a method should be run before the test class’s test
methods are invoked
@AfterClass Indicates that a method should be run before the test class’s test
methods are invoked
Page 67
Module 7 - TESTING
Spring in Tests
● Unit Tests
○ Spring Framework is not commonly used to perform unit tests
■ Dependency Injection is generally not needed
● Integration Tests
● Spring Framework is commonly used in integration tests
○ Ensures classes and files used by the framework are correct
● Integration tests are used to test several modules of software, when combined
together as a whole
2. ApplicationContext definition
■ Must be configured to be shared
■ Context definition is configured using the annotations:
● @ContextConfiguration
● @ActiveProfiles
● @TestPropertySource
○ Use a base class for all tests which will contain context configuration
○ Use a base interface for all tests classes which will contain context configuration
○ Use custom annotation for all test classes which will contain context configuration
● Context Instance is always reused in tests by default, as long as the following match:
○ @ContextConfiguration, @ActiveProfiles, and @TestPropertySource
@ContextConfiguration
● @ContextConfiguration annotation defines metadata for loading and configuring the
ApplicationContext for integration tests
Element Description
loader Classes implementing the ContextLoader interface that will be used to load the
application context
locations Locations of XML config files to create the application context from
● @SpyBean
○ The @SpyBean annotation injects a spy object into the ApplicationContext
■ Will replace any existing bean in the application context
● @LocalServerPort
○ Annotation at the field or method/constructor parameter level that injects the
HTTP port that got allocated for the application at runtime to a variable
■ Provides a convenient alternative for @Value("${local.server.port}")
Page 75
● Can execute Spring Boot applications using a simple command: “java -jar jarname”
Module Description
Spring Boot Actuator Monitoring and management of application (health checks, etc.)
Spring Boot Starters Dependency set for technologies to minimize setup time
Spring Boot Autoconfiguration Configuration templates for technologies to minimize setup time
Externalized Configuration
● Spring Boot supports external configuration for the application via property files which
can be in:
○ Java Properties File format (.properties)
○ YAML format (.yml)
■ Supported by snakeYAML library, included with spring-boot-starter
Starter POMs
● A Spring Boot Starter POM is a maven module that:
○ Represent an empty jar
○ Specifies set of dependencies required to work with a specified technology
○ Optionally provides autoconfiguration to create Spring beans to integrate project
with a technology
@WebAppConfiguration Annotation
● @WebAppConfiguration is a class-level annotation which declares that the integration
test requires a WebApplicationContext
○ Triggers creation of a MockServletContext for the test’s ServletContext
Annotation Description
@ActiveProfiles Declares which active bean definition profiles should be used when
● class-level loading ApplicationContext for test classes
@DirtiesContext Marks the test as one which modifies the context state, meaning context
● class level will be recreated at a later point
● method level
Can specify the modes depending on where annotation is applied:
● Class-level (classMode element)
○ BEFORE_CLASS
○ AFTER_CLASS
○ BEFORE_EACH_TEST_METHOD
○ AFTER_EACH_TEST_METHOD
@TestPropertySource Configure locations of property files and declare inline properties which
● class-level should be used to configure the ApplicationContext for tests
○ These will register the loading of an ApplicationContext for the test class
@BeforeTransaction Used to indicate that the annotated void method should be executed
before a transaction is started
@AfterTransaction Used to indicate that the annotated void method should be executed
after a transaction is started
@Before Indicates that a method should be run before each test case
@After Indicates that a method should be run after each test case
@BeforeClass Indicates that a method should be run before the test class’s test
methods are invoked
@AfterClass Indicates that a method should be run before the test class’s test
methods are invoked
Page 80
@PropertySource Annotation
● @PropertySource declaratively adds a PropertySource to Spring’s Environment
○ A PropertySource is a class representing a source of name/value property pairs
● You can adjust logging level using your application properties file:
Logging.level.root = WARN
● Can also use --debug or --trace argument when launching a Spring boot app, e.g.:
Java -jar myapp.jar --debug
● When using the default Logback setup in a Spring boot app, can customize the log
pattern using the application.properties file:
logging.pattern.file FILE_LOG_PATTERN Configure the pattern used for file log output
Page 81
Example:
spring.datasource.url = jdbc:mysql://localhost:8080/my-db
spring.datasource.username = user
spring.datasource.password = pass
● Can configure more than one datasource by naming custom properties, for example:
spring.datasource.db1.url = jdbc:mysql://localhost:8080/my-db1
Spring.datasource.db2.url = jdbc:mysql://localhost:8080/my-db2
Page 82
Fat Jars
● A fat jar (i.e. “executable jar”) is a jar which contains:
○ Compiled code of your application
○ All dependencies of your application as nested jars
● Fat jars are often called an “executable jar” because they use two components which
work together to execute a standalone jar:
Component Description
JarLauncher code Code for launching JAR based archives, which assumes:
● Dependency jars are located in /BOOT-INF/lib directory
● Application classes are located in /BOOT-INF/classes directory
● An embedded container is packed as a dependency inside the fat jar and will be
responsible for executing only a single application
● To create a fat jar with an embedded container in Spring Boot, your must satisfy the
required dependencies:
● WAR file structure vs. Spring Boot Fat Jar file structure is demonstrated below:
● Use features without having to implement them, simply by including the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
For example:
management.endpoint.health.enabled = true
management.endpoint.info.enabled = false
management.endpoint.web.exposure.exclude management.endpoint.jmx.exposure.exclude
For example:
Expose specific endpoints management.endpoint.web.exposure.include = info, health, env
● Can change the details exposed by .../actuator/health using the following properties:
management.endpoint.health.show-details
management.endpoint.health.show-components
Health Indicators
● Health Indicator status is used by Health Indicators to inform Spring Actuator whether
the component checked by the indicator is working or not
OUT_OF_SERVICE Component has been taken out of service, should not be used
Health Indicators
● Can change the Health Indicator status severity order using the property:
management.health.status.order = CUSTOM, DOWN, … , UP
● Spring Actuator maps Health Indicator status to HTTP Response Codes using
HealthStatusHttpMapper, which follows the following configuration:
Status HTTP Code
UP 200
UNKNOWN 200
DOWN 503
OUT_OF_SERVICE 503
● Each metric may have its own dedicated URI, for example:
○ .../actuator/metrics/jvm.memory.used?tag=area:heap
● Can define custom metrics using MeterRegistry class from MicroMeter (open source
application metrics facade by Pivotal), which gives many primitive types which can be
exposed via /actuator/metrics endpoint:
○ Counter, Timer, etc.
● You can filter HTTP requests to Actuator using tags - the tag is used to filter the query
● Tags are defined in the request as a request parameter, in the following way:
tag=KEY:VALUE
.../actuator/metrics/http.server.requests?tag=status:200&tag=method:GET
Page 89
Endpoint id Description
httptrace Lists HTTP trade info about the latest HTTP request-response exchanges
sessions Retrieval and deletion of user sessions from a Spring Session backend store
● Unavailable for reactive apps
● The following endpoints are additionally available in Spring Boot Apps if the application
is a web application (Spring MVC, Spring WebFlux, etc.), so long as they are exposed:
Endpoint id Description
heapdump Performs a heap dump and returns the heap dump file
logfile Allows retrieval of whole or part of the log file (as specified by logging.file or
logging.path properties)
Page 90
@SpringBootTest Annotation
● @SpringBootTest is an annotation provided by Spring Boot which provides the
following features in addition to the regular Spring TestContext Framework:
● @SpringBootTest is used for writing JUnit integration tests for Spring Boot applications
Property Description
args Application arguments that should be passed to the application under test.
properties Properties to be added to the Spring Environment before the test runs, specified
in the form key=value
Spring Boot Test Spring TestContext framework, helps test Spring Boot functionality
AssertJ An assertion library with helpful error messages and good code readability
JSONassert Converts a string into a JSON object which can be used for tests
● @SpyBean
○ The @SpyBean annotation injects a spy object into the ApplicationContext
■ Will replace any existing bean in the application context
● @LocalServerPort
○ Annotation at the field or method/constructor parameter level that injects the
HTTP port that got allocated for the application at runtime to a variable
■ Provides a convenient alternative for @Value("${local.server.port}")
@Mock vs @MockBean
● @Mock comes from Mockito Framework for easy mock creation
○ Used by MockitoJUnitRunner
■ Each annotated field has a mock class created, but not injected
■ To inject the created mocks, use @InjectMocks on the class itself
● @MockBean comes from spring-boot-test for easy mock injection into the context
○ Used by SpringRunner and SpringExtension, and when annotated to a field:
2. All beans which refer to this mocked class via @Autowired will get this
mock injected instead of the real class
2. Injection via @InjectMocks only injects to the annotated class, and not the whole
application