You are on page 1of 93

Page 1

Spring Framework Notes by Mitchell Marino

Module 1 - CONTAINER, DEPENDENCY, AND IOC


Bean Lifecycle
1. Creation
● Read config, create BeanDefinition objects
● BeanFactoryPostProcessor are invoked to edit bean metadata
● Instance of bean is created
● Init methods are invoked in following order:
1. @PostConstruct (JSR-250)
2. afterPropertiesSet method (InitializingBean interface)
3. Custom init method (initMethod element of @Bean annotation)
● Bean is ready

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

Spring Framework Notes by Mitchell Marino


Notes on Bean Lifecycle:
● Init/destroy methods will only run once, regardless of how many times they are referenced
○ E.g. if @PreDestroy method and destroyMethod reference the same function implementation,
the referenced function will only be called once during the earlier call (in this case, during the
@PreDestroy step)

● Init methods are always called, regardless of bean scope

● Destroy methods are not called for Prototype scoped beans


○ Spring keeping a reference of Prototype scoped beans would prevent garbage collection by
JVM and cause a memory leak

● 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

Supporting JSR-250 Annotations


● The CommonAnnotationBeanPostProcessor supports these JSR-250 annotations, among others
○ It is registered when creating a Spring Application Context which uses annotation-based
configuration, such as AnnotationConfigApplicationContext

● It is typically preferred to use JSR-250 annotations when available


○ Examples: @PostConstruct, @PreDestroy

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

Spring Framework Notes by Mitchell Marino

@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

Spring Framework Notes by Mitchell Marino

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

PostProcessors in the Configuration Lifecycle


● PostProcessors may implement the Ordered interface to set the priority of a PostProcessor thus
controlling the order in which PostProcessors are invoked
○ Can also use the @Order annotation
○ Lower number = higher precedence

● 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

Spring Framework Notes by Mitchell Marino

@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

Graphical representation of singleton bean handling by the proxied class:

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

● An object can declare its dependencies three ways:


○ Constructor args
○ Setter method args
○ Factory method args (@Bean)

● Dependency injection is done through annotations (e.g. @Autowired annotation) on:


○ Property
■ The property is injected
○ Setter Method
■ The method’s arguments are injected
○ Constructor
■ The constructor’s arguments are injected
Page 6

Spring Framework Notes by Mitchell Marino


■ @Autowired is only necessary for constructors if multiple constructors exist, to specify
which one to be used by Spring to initialize the object

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

● Behaviour of the @ComponentScan annotation can be adjusted by using its elements:


○ basePackages
■ Base packages to be scanned
○ basePackageClasses
■ Base packages to be scanned, defined by referencing a class in the package
■ Preferred way
○ excludeFilters
■ Exclude classes, by name or by annotation
○ includeFilters
■ Include classes, by name or by annotation

● 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

Spring Framework Notes by Mitchell Marino

@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

4. If no unique bean has been resolved in previous steps.


● Throw an exception (e.g. NoUniqueBeanDefinitionException)

● Summary of steps:
○ Type
○ @Qualifier
○ @Primary
○ If not found, throw exception

● @Autowired can be applied to constructors/methods/fields of any visibility (private, public, etc.)

● Dependencies injected through the use of @Autowired are required by default

● @Autowired functionality is fulfilled by the AutowiredAnnotationBeanPostProcessor


○ Autowiring happens after beans are created, but before initialization functions are called

● Autowiring special cases:


○ Injecting into a Collection
■ Spring will inject a collection containing all beans of the Collection’s type that are present
in the IoC Container
● These beans will be ordered according to their assigned order (if order has been
specified through the Ordered interface or @Ordered/@Priority annotations

○ Injecting into a Map


■ Spring will inject a Map of key value pairs with all beans of the Map’s type that are
present in the IoC container
● Key = the bean name
● Value = reference to the bean

○ 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

Spring Framework Notes by Mitchell Marino


● Methods of Dependency Injection:

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)

● If using option #1 or option #2 to specify an argument as non-required:


○ The method will always be invoked
○ If using Optional, Resolved object will be available through Optional API
○ If using @Nullable, unresolved objects will simply be null

● If using using option #3 (i.e. @Autowired(required = false))


○ The method will NOT always be invoked:
■ No dependency injection will take place unless ALL arguments are
successfully resolved

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

● @Quaifier is primarily used in one of two ways:

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

2. Define the qualifier (name) of a bean to be injected:


● This occurs when using @Qualifier at injection points
○ i.e. when you are using @Autowired to inject a bean, you can additionally use
@Qualifier to specify the name of the bean to inject
Page 9

Spring Framework Notes by Mitchell Marino

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

● The ApplicationContext is Spring’s advanced container


○ It is similar to BeanFactory - it can load bean definitions, wire beans together, and dispense
beans upon request

● Most commonly used ApplicationContext implementations are:

● 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

Closing Application Context


● Non-web Application Context
○ There are two ways to close a non-web aware application context:
1. ApplicationContext.close() method
● Close context immediately
2. ApplicationContext.registerShutdownHook() method
● Closes context when JVM shuts down normally
● Recommended way of closing ApplicationContext
● This method is used by Spring Boot to close ApplicationContext

● Web Application Context


○ Closing a web application context is handled by ContextLoaderListener
■ Receives a ServletContextEvent when web container stops the application
■ This method is used by Spring Boot to close ApplicationContext for web applications
Page 10

Spring Framework Notes by Mitchell Marino

Environment Abstraction
● The Environment is an interface representing the environment in which the application is running

○ The environment has two key considerations:


1. Profiles
● Profiles are a logical group of bean definitions to be registered with the container
only if the given profile is active
● Beans can be assigned a profile via @Profile annotation
● The Environment object determines which properties are currently active, and
which profiles (if any) should be active by default
● Setting profiles:
○ Use .setActiveProfiles(prof1, prof2, etc..) on environment object
Use spring.profiles.active property
● Can have 232-1 profiles (far more than ever needed)

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

● Can access environment via any class which implements EnvironmentCapable

● Configuration of the Environment object must be done through the ConfigurableEnvironment


interface, returned from all AbstractApplicationContext getEnvironment() methods

○ Almost all ApplicationContext implementation classes extend some


AbstractApplicationContext abstract class

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

○ EnvironmentAware has method setEnvironment(Environment environment)


■ Used to set the Environment that the object runs in

○ EnvironmentCapable has method getEnvironment()


■ Used to retrieve the Environment associated with the object (object exposes its
Environment)
Page 11

Spring Framework Notes by Mitchell Marino

Standard (non-web) Environment vs. Web Environment


● Environment in spring non-web applications have 2 property sources:
1. JVM system properties
2. System environment variables

● Environment in spring web applications have 3 additional property sources:


3. Servlet configuration property source
4. Servlet context property source
5. JNDI property source
● JNDI = Java Naming & Directory Interface

● Properties diagram for standard vs. web apps:

● The basic environment varies depending on the type of Spring application:

○ Standard (non-web)
■ StandardEnvironment is the basic environment for non-web applications

○ Web (both the following classes are subclasses of StandardEnvironment)


1. StandardServletEnvironment for regular web apps
2. StandardReactiveWebEnvironment for reactive web apps

ApplicationContext and Environment


○ ApplicationContext interface extends the EnvironmentCapable interface
■ Hence:
● It contains getEnvironment() method, returning object implementing
Environment interface
● An ApplicationContext has a relation to one single Environment object

○ In a web environment:
■ ContextLoaderListener is in charge of creating a WebApplicationContext
Page 12

Spring Framework Notes by Mitchell Marino

@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}”)

● Can apply the @Value annotation to:


○ Fields
○ Methods (and method/constructor parameters)
■ It will inject the value into all method arguments

● Use-cases for @Value


○ Inject a value into property or method/constructor parameters
■ Sources of this property may be:
● Property value
● Environment value
● SpEL expression evaluation result
● Values from another bean’s properties

● Property resolution vs. SpEL expression


○ @Value annotation is primarily used to do one of two things:

1. Inject a property value


● Done using ${ … } syntax
● Property would be a property name within the application’s Environment
● This syntax for property resolution can only be used in @Value annotations

2. Inject the result of a SpEL expression evaluation


● Done using #{ … } syntax
● Parsed by a SpEL parser and evaluated by a SpEL instance
Page 13

Spring Framework Notes by Mitchell Marino

Spring Expression Language (SpEL)


● Spring Expression Language (SpEL) is a powerful expression language that supports querying and
manipulating an object graph at runtime

● #{...} 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)

● SpEL can reference various objects and properties using SpEL:


● Static classes
○ To reference static classes, static methods, etc. use the T() operator
■ #{ T(path.to.java.class) }
■ #{ T(path.to.java.class).method() }
■ #{ T(path.to.java.class).variable }

● Spring beans
○ To reference Spring beans in the context, use @. For example:
■ #{ @beanName }
■ #{ @beanName.method() }
■ #{ @beanName.value }

● JVM System Properties


○ Available via systemProperties bean, available by default. For example:
■ #{ systemProperties['property.name'] }

● System Environment Properties


○ Available via systemEnvironment bean, available by default. For example:
■ #{ systemEnvironment['property.name'] }

● Spring Application Environment


○ Available via environment bean, available by default. For example:
■ #{ environment['property.name'] }
Page 14

Spring Framework Notes by Mitchell Marino

SpEL Compiler Configuration


● Compiled SpEL expressions
○ SpEL expressions are evaluated dynamically, but can be compiled to improve performance
■ Cannot be compiled if:
● Involves assignment ( = operator )
● Relies on conversion service
● Uses selection or projection

● SpEL compiler is off by default


○ Compiler modes can be changed using system property spring.expression.compiler.mode
■ If you are creating a SpelExpressionParser class, can register
SpelParserConfiguration instance instead

● There are multiple SpEL compiler modes:

○ 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

Spring Framework Notes by Mitchell Marino

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

Proxy Types (JDK Dynamic Proxy vs. CGLIB Proxy)


JDK Dynamic Proxy
● Implements all of the interfaces implemented by the proxied class
● Limitations:
○ Proxied class must implement at least one interface
■ Only methods implemented by the interface(s) will be exposed by the proxy
○ Proxied class must be referenced using an interface type
○ Does not support self-invocation

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

Recall - Limitations for both:


● Does not support self-invocation
○ Self-invocation bypasses the proxy and invokes the original method directly
○ Public method calls must originate from outside the bean to work with a proxy
Page 16

Spring Framework Notes by Mitchell Marino

Module 2 - ASPECT ORIENTED PROGRAMMING


Aspect Oriented Programming
● Aspect Oriented Programming is a programming paradigm which separates
cross-cutting concerns from other code

● A concern is a part of the system divided on the basis of functionality

● Cross Cutting Concerns are concerns which are system-wide


○ Applicable throughout the entire application, applied various places
■ Examples:
● Logging
● Caching
● Security
● Data validation
● Transaction management
● Error handling
● Monitoring (for example, processing time)
● Custom business rules

● 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

Spring Framework Notes by Mitchell Marino

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

● @Aspect annotated classes must be spring beans for advice to be created


○ Component scanning does not find @Aspect annotated classes by default,
because @Aspect is not a stereotype annotation. Therefore, @Aspect
annotation alone does not register the class as a Spring Bean
■ Two options to register an aspect as a bean:
1. Also annotate the @Aspect annotated classes with the
@Component annotation
2. Use a @Bean annotated method in a @Configuration class to
register the @Aspect annotated class as a bean

● @EnableAspectJAutoProxy annotation must be applied to a configuration class to


enable AOP in Spring
○ The aspectjweaver.jar library from AspectJ must be on the classpath
Page 18

Spring Framework Notes by Mitchell Marino

@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

● Whatever you specify in @Before, @After, etc. is also a pointcut expression


○ However, pointcut expressions are commonly extracted out into a separate
method using @Pointcut for better understanding, modularity, and control

● Example of @Pointcut usage, and referring to the pointcuts in an @Around annotation:

Example pointcuts

Pointcut Description of matching join points

execution(Entity *Repository.find*(..)) ● Class name ends in “Repository”


● Function name begins with “find”
● Function takes 0 or more parameters
● Returns object of type “Entity”

within(ab.cd.ef..) Selects join points within the package “ab.cd.ef” and


subpackages

bean(myService) Selects join points on the Spring bean with the name
“myService”

funcName() Selects join points if the function “funcName” is


annotated with a @Pointcut
Page 19

Spring Framework Notes by Mitchell Marino

Pointcut Designators

Pointcut Designator Description

execution The most common designator for matching execution join points

Usage:
execution([method visibility] [return type] [package].[class].[method]([parameters] [throws exceptions]))

within Matches join points within certain types (Classes)

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)

Usage: args(Arg1Type, Arg2Type, ...)

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

bean Matches join points within a Spring Bean


This is the only designator exclusively supported by spring AOP (not AspectJ)

Usage: bean(myBeanName)
Page 20

Spring Framework Notes by Mitchell Marino

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

Advice Types (Annotations)

Advice Type Description

Before Executed before a join point


● Will always proceed to join point, unless an exception is thrown
Annotation:
@Before Example use-cases:
● Access control → check user authorization, throw exception if user not authorized
● Statistics → count # of method invocations

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

After (finally) Executed always, after execution of a join point


● Is executed regardless if join point returned successfully, or threw an exception
Annotation: ● After advice cannot prevent exception propagation
@After
Example use-cases:
● Releasing Resources → After advice is always executed, so can make sure resources are released

Around Executed before and after (around) a join point


● Can choose whether or not to execute the join point or not
Annotation: ● Can return a value from execution of the join point, or a custom value if desired
@Around ● Can prevent exception propagation (using try/catch)

Example use-cases:
● Around is the most powerful advice type, can be used for all above use-cases, and more
Page 21

Spring Framework Notes by Mitchell Marino

Advice-Annotated Method Arguments


● Advice-annotated methods within spring AOP aspects can accept additional arguments,
which are supplied at runtime to provide additional functionality

● 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

● If the ProceedingJoinPoint parameter is present, it must be the first argument


of the advice method

● ProceedingJoinPoint is a subclass of JoinPoint so it contains all functionality


provided by JoinPoint, along with additional behaviour

● ProceedingJoinPoint provides the following additional methods:

○ 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

Spring Framework Notes by Mitchell Marino

Weaving
● Weaving is the process of combining advice implemented by aspects with join points:

○ Compile Time Weaving


■ Byte code of classes is modified at compile time
■ AspectJ compiler uses compile time weaving

○ Load Time Weaving


■ Byte code classes are modified at class loading time when the app is run

○ 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

● JDK Dynamic Proxy limitations


○ Class to be proxied must implement interface(s)
○ Only public methods in implemented interfaces will be proxied

● 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

Spring Framework Notes by Mitchell Marino

Module 3 - DATA MANAGEMENT: JDBC,


TRANSACTIONS, SPRING DATA JPA
Exceptions
● There are two primary types of exceptions relating to db access through Spring:

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

● Spring prefers unchecked exceptions


○ java.lang.Exception and all subclasses are checked exceptions
■ Except for RuntimeException and all its subclasses

DataAccessException Class Hierarchy


● Spring provides a convenient translation from technology-specific exceptions like
SQLException to its own exception class hierarchy with the DataAccessException as
the root exception
○ These exceptions wrap the original one, so there is no risk of information loss

● 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

● Makes it easier to:


○ Develop functionality without needing to worry about API details
○ Switch between different data access APIs at any time

● All exceptions in the DataAccessException hierarchy are unchecked


Page 24

Spring Framework Notes by Mitchell Marino

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

● Example Spring classes implementing the DataSource interface include:


○ DelegatingDataSource, AbstractDataSource, SmartDataSource,
EmbeddedDatabase

Configuring a DataSource object in Spring


There are three primary scenarios which you may want to configure a DataSource bean:

1. Standalone Application
○ Create it programmatically, like any other bean, for example:

2. Spring Boot Application


○ Create it by setting properties in the properties file

○ Example:
spring.datasource.url = jdbc:mysql://localhost:8080/my-db
spring.datasource.username = user
spring.datasource.password = pass

3. Application Deployed to Server


○ Can do a JNDI (Java Naming and Directory Interface) lookup in a @Bean
annotated method
○ If using Spring Boot for this application deployed to the server, can rely on a
single property:
Spring.datasource.jndi-name = java:comp/env/jdbc/myDatabase
Page 25

Spring Framework Notes by Mitchell Marino

Template Design Pattern


● The Template design pattern is a class representing an outline/template for an
algorithm, with room for customization
○ In this class, the algorithm’s steps are methods with protected visibility

○ Template classes may define default implementations of certain steps of the


algorithm, but allows subclasses to override certain steps as desired

JDBC Template
● The JdbcTemplate class simplifies the use of JDBC by implementing common
workflows for querying, updating, statement execution, etc.

● Benefits of using JdbcTemplate:


○ Simplification
■ Code reduction (less boilerplate code)
○ Handles exceptions
■ Translates exceptions to a member of the DataAccessException
hierarchy, which are more generic and not vendor related
○ Allows customization of functionality
■ Follows template design pattern
■ Can customize handling of query results using callbacks

● JdbcTemplate is thread-safe after created and configured

JDBC Connections
● JdbcTemplate manages connections to db for every method called:
● Acquires connection immediately before executing operation
● Releases connection immediately after executing operation

● This strategy for connection management is important to keep as many db connections


available as possible, since dbs only support a limited amount of concurrent connections

● 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

Spring Framework Notes by Mitchell Marino

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

○ A default ResultSet object maintains a cursor which is initially positioned before


the first row of data
■ This cursor moves forward only, using the ResultSet.next() method
■ Some ResultSet objects are scrollable and/or updateable

○ Objects implementing the ResultSet interface, such as SqlRowSet (from


org.springframework.jdbc.support.rowset) are used by Spring to handle the
results of database queries

Querying using JDBC Template


● JdbcTemplate class can execute SQL statements using one of the following methods:

Method Name Description

batchUpdate(...) Issue multiple SQL updates on a single JDBC statement using batching

execute(...) Execute a JDBC data access operation

query(...) Query using a prepared statement

queryForList(...) Execute a query for a result list


● 2 flavours of this function:
1. Takes class type as parameter, returns list of objects
2. Does not take class type parameter, returns list of maps

queryForMap(...) Execute a query for a result map


● Key → column name, Value → value

QueryforObject(...) Execute a query for a result object


● Can supply your own RowMapper for custom types

queryForRowSet(...) Execute a query for an SqlRowSet

update(...) Issue single SQL update operation (i.e., insert, update, or delete)
Page 27

Spring Framework Notes by Mitchell Marino

JdbcTemplate Callbacks (Functional Interfaces)


● A callback is a function passed as an argument to a method, which will be called at
some point during downstream execution
○ A callback can be either a Java Object implementing an interface (i.e.,
Functional Interface) or a Lambda expression

● There are 3 main functional interfaces present in org.springframework.jdbc.core that


can be used to handle query results:

Callback Interface Description

ResultSetExtractor Given a ResultSet, process the entire result set


● Typically stateless
Functional Interface: ○ Returns object representing entire result set
ResultSetExtractor<T>
● Will use ResultSet.next() to get next data
Function: ○ Should not .close() ResultSet, JdbcTemplate will do this
.extractData(...)
● May be multiple rows of data at once

RowMapper Given a ResultSet, map on a per-row basis


● Typically stateless
Functional Interface: ○ Returns object representing current row
RowMapper<T>
● Allows for processing rows in a result set one-by-one
Function: ○ Should not call ResultSet.next()
.mapRow(...)
● .mapRow(...) arguments include an integer representing row number

RowCallbackHandler Given a ResultSet, process the row and map it to an object


● Typically stateful
Functional Interface: ○ Does not return object representing current row
RowCallbackHandler ○ Keeps the result state within the object

Function: ● Allows for processing rows in a result set one-by-one


.processRow(...) ○ Should not call ResultSet.next()

● 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

Spring Framework Notes by Mitchell Marino

Template Design Pattern


● The Template design pattern is a class representing an outline/template for an
algorithm, with room for customization
○ In this class, the algorithm’s steps are methods with protected visibility

○ Template classes may define default implementations of certain steps of the


algorithm, but allows subclasses to override certain steps as desired

JDBC Template
● The JdbcTemplate class simplifies the use of JDBC by implementing common
workflows for querying, updating, statement execution, etc.

● Benefits of using JdbcTemplate:


○ Simplification
■ Code reduction (less boilerplate code)
○ Handles exceptions
■ Translates exceptions to a member of the DataAccessException
hierarchy, which are more generic and not vendor related
○ Allows customization of functionality
■ Follows template design pattern
■ Can customize handling of query results using callbacks

● JdbcTemplate is thread-safe after created and configured

JDBC Connections
● JdbcTemplate manages connections to db for every method called:
● Acquires connection immediately before executing operation
● Releases connection immediately after executing operation

● This strategy for connection management is important to keep as many db connections


available as possible, since dbs only support a limited amount of concurrent connections

● 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

Spring Framework Notes by Mitchell Marino

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

○ A default ResultSet object maintains a cursor which is initially positioned before


the first row of data
■ This cursor moves forward only, using the ResultSet.next() method
■ Some ResultSet objects are scrollable and/or updateable

○ Objects implementing the ResultSet interface, such as SqlRowSet (from


org.springframework.jdbc.support.rowset) are used by Spring to handle the
results of database queries

Querying using JDBC Template


● JdbcTemplate class can execute SQL statements using one of the following methods:

Method Name Description

batchUpdate(...) Issue multiple SQL updates on a single JDBC statement using batching

execute(...) Execute a JDBC data access operation

query(...) Query using a prepared statement

queryForList(...) Execute a query for a result list


● 2 flavours of this function:
1. Takes class type as parameter, returns list of objects
2. Does not take class type parameter, returns list of maps

queryForMap(...) Execute a query for a result map


● Key → column name, Value → value

QueryforObject(...) Execute a query for a result object


● Can supply your own RowMapper for custom types

queryForRowSet(...) Execute a query for an SqlRowSet

update(...) Issue single SQL update operation (i.e., insert, update, or delete)
Page 27

Spring Framework Notes by Mitchell Marino

JdbcTemplate Callbacks (Functional Interfaces)


● A callback is a function passed as an argument to a method, which will be called at
some point during downstream execution
○ A callback can be either a Java Object implementing an interface (i.e.,
Functional Interface) or a Lambda expression

● There are 3 main functional interfaces present in org.springframework.jdbc.core that


can be used to handle query results:

Callback Interface Description

ResultSetExtractor Given a ResultSet, process the entire result set


● Typically stateless
Functional Interface: ○ Returns object representing entire result set
ResultSetExtractor<T>
● Will use ResultSet.next() to get next data
Function: ○ Should not .close() ResultSet, JdbcTemplate will do this
.extractData(...)
● May be multiple rows of data at once

RowMapper Given a ResultSet, map on a per-row basis


● Typically stateless
Functional Interface: ○ Returns object representing current row
RowMapper<T>
● Allows for processing rows in a result set one-by-one
Function: ○ Should not call ResultSet.next()
.mapRow(...)
● .mapRow(...) arguments include an integer representing row number

RowCallbackHandler Given a ResultSet, process the row and map it to an object


● Typically stateful
Functional Interface: ○ Does not return object representing current row
RowCallbackHandler ○ Keeps the result state within the object

Function: ● Allows for processing rows in a result set one-by-one


.processRow(...) ○ Should not call ResultSet.next()

● 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

Spring Framework Notes by Mitchell Marino

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

● ACID principle → intended to guarantee data validity


○ Atomicity
■ All or nothing
● If one task in the transaction fails, none should be performed
○ Consistency
■ Integrity constraints should not be violated
● DB state should go from one valid state to another
○ Isolation
■ Transactions should be isolated
● Transactions should not affect each other
○ Durability
■ Changes are applied as a result of a successful transaction are durable

● There are two primary types of transactions

1. Local Transactions
● Local transactions are associated with one single resource
○ A resource refers to something such as a database

● A local transaction should not use more than one resource

2. Global Transactions
● Global transactions are associated with multiple resources
○ For example, two or more databases within a transaction

● Global transactions must ensure that operations on all resources


succeed, before changes are committed
○ If updating any resource fails, changes to all resources must be
rolled back

● 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

Spring Framework Notes by Mitchell Marino

Isolation levels
● Isolation levels determine how changes by other transactions are visible within the
current transaction, prior to being committed

Higher Isolation Level Lower Isolation Level

● Worse concurrent performance ● Worse concurrent performance


● Worse use of resources ● Worse use of resources
● Better concurrent safety ● Better concurrent safety

● There are four isolation levels offered by Spring framework transactions:

Isolation Level Description

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:

Isolation Level Phantom Read Non-repeatable Dirty Read Concurrency


Read

Serializable No No No Very Poor

Repeatable Reads Yes No No Poor

Read Committed Yes Yes No Good

Read Uncommitted Yes Yes Yes Very Good


Page 30

Spring Framework Notes by Mitchell Marino

Errors at Isolation Levels


1. Phantom Reads
● Occur when one a repeated read operation is done on the same records, but
new records in the result set are captured in the second read

Transaction A - First Read In the scenario on the left, a phantom read


● select * where id between 1 and 10 occurs:
Transaction B - Write ● The second read captures an
● Insert into table (object, id = 5) additional record in its result set,
Transaction A - Second Read which was inserted by transaction
● Select * where id between 1 and 10 B’s write operation

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

Transaction A - First Read In the scenario on the left, a non-repeatable


● select * where id = 5 read occurs:
Transaction B - Write ● The second read returns a different
● update table (change) where id = 5 result than the first read, because it
Transaction A - Second Read captures the changes made by
● select * where id = 5 transaction B’s write operation

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

● To prevent dirty reads, use an isolation level that prevents uncommitted


changes by other transactions being visible
○ Serializable, Repeatable Read, and Read Committed fulfill this req
Page 32

Spring Framework Notes by Mitchell Marino

@EnableTransactionManagement Annotation
● @EnableTransactionManagement enables Spring’s annotation-driven transaction
management capability
○ Exactly 1 class in a project should be annotated with this method

● @EnableTransactionManagement annotation registers the following components:


1. TransactionInterceptor
2. JDK Proxy or AspectJ Advice
● Intercepts methods annotated with @Transactional, handles them using:
1. TransactionInterceptor
2. A bean implementing the TransactionManager interface which
should be defined and present in the context

● @EnableTransactionManagement has the following three elements:

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

proxyTargetClass Specify the default type of proxy class:


● True = CGLIB proxy by default
Note: ● False (default) = JDK proxy by default
Affects proxies for ALL
Spring Beans in the Note:
application!!! ● ProxyTargetClass only if applicable mode = PROXY

Global vs Local Transactions


● Global Transactions
○ A transaction which spans more than 1 resource (i.e., more than one database)
○ Classes that allow for global transactions:
■ JtaTransactionManager → Java Transaction API

● 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

Spring Framework Notes by Mitchell Marino

Transactions - The Big Picture


● Spring transactions are facilitated using an AOP proxy, which uses two important
beans:

1. TransactionInterceptor
■ Used by Spring AOP proxy for two primary reasons:

1. Get transaction metadata (descriptive info about transaction)


● Done using a TransactionAttributeSource

2. Manage transactions (commit, rollback, etc.)


● Done by leverage an existing class which implements the
TransactionManager interface (e.g.
PlatformTransactionManager), which should be present
in the application context

2. PlatformTransactionManager
■ Used by TransactionInterceptor (at @Transaction annotated join points)
to handle transactions (create new, commit, rollback, etc.)

● Below is a diagram which demonstrates the flow of a transaction achieved through


Spring framework’s AOP solution:
Page 36

Spring Framework Notes by Mitchell Marino

JPA (Java Persistence API)


● JPA is a Java framework for managing relational data in applications

JPA with Spring (steps to configure)


● Enable JPA in Spring via the following steps:

1. Add Spring Data JPA dependency to the project:


<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>

2. Declare a DataSource bean


● Represents a connection to a physical data source (i.e. database)

3. Declare a EntityManagerFactory bean


● This will be shared by the Spring ApplicationContext
● Will be passed to JPA-based DAOs via dependency injection

4. Declare a TransactionManager bean


● Specifically use JpaTransactionManager to support JPA transactions

5. Use annotations, each applied to exactly 1 @Configuration annotated class:


@EnableJpaRepositories Enable JPA repository support

@EnableTransactionManagement Enable transaction support

JPA with Spring Boot


● Can use the Spring Boot starter titled spring-boot-starter-data-jpa to provide:

■ Default set of dependencies needed for using JPA in a Spring app

■ All Spring beans needed to use JPA


● These beans can be customized by overriding them

■ Default properties related to persistence and JPA


● Properties can be customized using the application properties file
Page 34

Spring Framework Notes by Mitchell Marino

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

2. TransactionAttributeSource (e.g. annotation-based)


● Used for determining transaction definitions for a particular
class/method

● TransactionInterceptor extends TransactionAspectSupport


○ This parent class is made to interface with any aspect system

● Follows Strategy design pattern, which allows selecting of transaction handling


algorithm at runtime

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.

● PlatformTransactionManager has three primary methods which are used


under-the-hood to manage transactions:

Function Name Function Description

commit(TransactionStatus status) Commit a given transaction, with regard to its status

getTransaction(TransactionDefinition definition) Depending on propagation behaviour, either:


1. Return a currently active transaction,
2. Or create a new transaction

rollback(TransactionStatus status) Perform a rollback of the given transaction


Page 35

Spring Framework Notes by Mitchell Marino

Transaction Propagation
● Transaction propagation determines how an existing transaction is used

● Propagation for a transaction is set when using the @Transactional annotation

● Seven different types of transaction propagation behaviour:

Propagation Propagation Behaviour

MANDATORY There must be an existing transaction when invoked


● Exception will be thrown otherwise

NESTED Method is executed as a nested transaction if one currently exists


● Else, will create a new transaction

NEVER Method is never executed inside a transaction


● Exception is thrown if transaction exists

NOT_SUPPORTED Method is executed outside a transaction


● Suspends existing transaction

REQUIRED Method is executed in the current transaction


● If no transaction exists, one is created
● This is the default

REQUIRES_NEW Method is executed in a new transaction


● Suspends existing transaction, if one exists

SUPPORTS Method is executed in the current transaction


● If no transaction exists, it is executed outside the transaction

Rollback Policy
● A rollback is the process of restoring a database or program to a previously defined
state, typically to recover from an error.

● The default rollback policy is to automatically rollback only if an unchecked exception is


thrown

● 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

Spring Framework Notes by Mitchell Marino

JPA (Java Persistence API)


● JPA is a Java framework for managing relational data in applications

JPA with Spring (steps to configure)


● Enable JPA in Spring via the following steps:

1. Add Spring Data JPA dependency to the project:


<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>

2. Declare a DataSource bean


● Represents a connection to a physical data source (i.e. database)

3. Declare a EntityManagerFactory bean


● This will be shared by the Spring ApplicationContext
● Will be passed to JPA-based DAOs via dependency injection

4. Declare a TransactionManager bean


● Specifically use JpaTransactionManager to support JPA transactions

5. Use annotations, each applied to exactly 1 @Configuration annotated class:


@EnableJpaRepositories Enable JPA repository support

@EnableTransactionManagement Enable transaction support

JPA with Spring Boot


● Can use the Spring Boot starter titled spring-boot-starter-data-jpa to provide:

■ Default set of dependencies needed for using JPA in a Spring app

■ All Spring beans needed to use JPA


● These beans can be customized by overriding them

■ Default properties related to persistence and JPA


● Properties can be customized using the application properties file
Page 37

Spring Framework Notes by Mitchell Marino

Entities

EntityManagerFactory
● EntityManagerFactory is an interface used to interact with a persistence unit (like a DB)

● Typically configures the following:

1. ORM (object-relational mapping) to be used by the application


○ Example: Hibernate

2. Type of database to be used by the application

3. The package(s) in the application to scan for entities

● EntityManagerFactory is used to create EntityManagers

EntityManager
● EntityManager is an interface used to interact with entity instances
○ These entity instances exist within a persistence context

● EntityManager is used as an API to:


○ Create and remove persistence entity instances
○ Find entities by their primary key
○ Query over entities

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

1. Annotate the class with @Entity


● This indicates that the class represents an entity relating to persistence

2. Create an id field and annotate it with @Id


● The @Id annotation indicates that the field in the class is a primary key

● 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

Spring Framework Notes by Mitchell Marino

@Id Annotation
● @Id is used to mark a property within an entity class as the primary key

● Applied at the property level within an entity class

@Embeddable Annotation
● Custom classes representing primary keys are annotated with @Embeddable

● If this @Embeddable class is used in an entity class as an id, it should be annotated


with @EmbeddableId

@PersistenceContext Annotation
● @PersistenceContext injects a proxy of an EntityManager to a class

● The @PersistenceContext annotation can be applied at:


○ Property level → (property of type = EntityManager)
○ Method level → (setter of type = EntityManager)

● The injected EntityManager proxy will vary based on whether a transaction exists:

○ If transaction exists:
■ Injects existing EntityManager proxy associated with current transaction

○ If transaction does not exist:


■ Creates a new EntityManager proxy

@PersistenceUnit Annotation
● Similar to @PersistenceContext, except inject an EntityManagerFactory

● Typically preferred to use @PersistenceContext instead


○ Unless you intend on managing the EntityManager lifecycle manually
Page 42

Spring Framework Notes by Mitchell Marino

Module 4 - SPRING MVC AND THE WEB LAYER


Model View Controller (MVC)
● Model-View-Controller (MVC) is a design pattern
○ Used to separate concerns of applications with a user interface, like web-apps

Component Concerns

Model ● Current data


● Business logic

View ● Presenting data to user


● User interacts with the view

Controller ● Mediator between model and view


● Sends results to view, to be rendered

● 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

● Diagram of Spring’s MVC architecture (front-controller pattern):


Page 43

Spring Framework Notes by Mitchell Marino

DispatcherServlet
● DispatcherServlet is a servlet (process which handles requests)
○ It implements the front controller design pattern

● DispatcherServlet has three main duties:

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

● A Spring application can define multiple dispatcher servlets


○ Each has its own:
■ Namespace
■ Application context
■ Set of mapping & handlers

● An application typically has only one DispatcherServlet, as the front controller

● Diagram of dispatcher servlet:


Page 44

Spring Framework Notes by Mitchell Marino

Web Application Context


● The WebApplicationContext interface is used in web applications
○ Helps provide configuration for a web application

● In addition to standard application context lifecycle capabilities, the


WebApplicationContext implementations detect ServletContextAware beans
and invoke the setServletContext(...) method accordingly

● A WebApplicationContext provides the getServletContext() method, which returns the


Servlet API ServletContext for the application

● A WebApplicationContext provides 3 additional scopes for beans:

Scope Name Description

Request Single bean instance per HTTP request

Session Single bean instance per HTTP session

Application Single bean instance per ServletContext

@Controller Annotation
● @Controller annotates classes that implement web controllers

● @Controller annotation is a specialization of the @Component annotation


○ I.e., @Controller is a stereotype annotation

@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

Spring Framework Notes by Mitchell Marino

@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

● @RequestMapping can be applied at:


○ Class level
■ Applies specified URL segment after base URL
○ Method level
■ Applies specified URL segment after class level @RequestMapping

● A method’s URL mapping is determined in the following way:


(Base URL + @RequestMapping on class + @RequestMapping on method)

● 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!”
}
}

● @RequestMapping for the class/method can be customized by annotation elements:

Element Description

path The path mapping URIs for this request


● @RequestMapping(“/foo”) == @RequestMapping(path=”/foo”)

headers Narrows mapping by headers of the mapped request

method Narrows mapping by HTTP request method (default=RequestMethod.GET)

consumes Narrows mapping by media types that can be consumed by method

produces Narrows mapping by media types that can be produced by method

params Narrows mapping by parameters of the mapped request


Page 46

Spring Framework Notes by Mitchell Marino

Specialized @RequestMapping Annotations


● There are specialized @RequestMapping annotations which are more readable
○ These annotations are @RequestMapping with a specific method / HTTP verb:

@GetMapping @PostMapping @PutMapping

@PatchMapping @DeleteMapping

● Example:
○ @GetMapping(...) == @RequestMapping(...method=RequestMethod.GET)

Enabling Request Mapping In Spring


● To enable request mapping, need to follow these steps:

1. Enable component scanning


● Annotate the main class with @ComponentScan or
@SpringBootApplication

2. Annotate exactly 1 configuration class with @EnableWebMvc


● In Spring Boot, can have one @Configuration class implementing
WebMvcConfigurer interface

3. Implement a controller class that is annotated with the @Controller annotation

4. Annotate a controller class (or method in controller) with @RequestMapping or


one of the specialized request mapping annotations, such as @GetMapping

How a Spring Application Handles Requests


● The application handles requests by following these steps:

1. The DispatcherServlet receives the request

2. The DispatcherServlet maps the request to a controller


● Has a list of classes implementing the HandlerMapping interface

3. The DispatcherServlet dispatches the request to the controller

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

Spring Framework Notes by Mitchell Marino

Annotations for handling URLs


● The two primary ways to provide dynamic data in request URLs is through:
1. Request parameters
2. Path variables

@RequestParam Annotation
● @RequestParam binds request parameters to method parameters
○ I.e., maps query string parameters to handler method arguments

● @RequestParam has the following primary elements:


Name Name of parameter in request
● Default = name of variable

Required Whether parameter is required


● Default = true

● For example, the URL “localhost:8080/greeting?name=Mitchell” will set the value of


the name variable to “Mitchell” when the URL is mapped to the handler function
@RequestMapping(“/greeting”)
public String greeting(@RequestParam(name=”name”, required=false) String name) { …. }

@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

● @RequestParam has the following primary elements:


Name Name of parameter in request
● Default = name of variable

Required Whether parameter is required


● Default = true

● For example, the URL “localhost:8080/firstName/Mitchell/lastname/Marino” will set


the variable values (firstName = Mitchell, lastName = Marino) when mapped to the
following handler function:
@RequestMapping(“/firstname/{firstName}/lastname/{lastName}”)
public String greeting(@Pathvariable(“firstName”) String firstName
@Pathvariable String lastName) { …. }
Page 48

Spring Framework Notes by Mitchell Marino

Map with @RequestParam and @PathVariable


● If you define a single method argument type of Map in your @RequestMapping
annotated handler function, you can receive a Map of all request parameters or path
variables on the URL.
○ In the example below, when handling a request with the URL
“localhost:8080/firstName/Mitchell/lastname/Marino”, the map variable will
have the following key value pairs:
■ firstName: Mitchell
■ lastName: Marino
@RequestMapping(“/firstname/{firstName}/lastname/{lastName}”)
public String greeting(@Pathvariable Map<String, String> map) { …. }

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

Spring Framework Notes by Mitchell Marino

Controller Method Parameter Annotations


● The following annotations are applied to arguments of controller methods
○ They affect the value which is injected to the annotated variable:

Annotation Description

@PathVariable Binds a part of the URL (a path segment) to a handler method


argument

@MatrixVariable Binds a name-value pair in part of the URL, a path segment, to a


handler method argument

@RequestParam Binds a query string parameter to a handler method argument

@RequestHeader Binds a request header to a handler method argument

@CookieValue Binds the value of a HTTP cookie to a handler method argument

@RequestBody Binds the body of a request to a handler method argument

@RequestPart Binds part of a “multipart/form-data” request to a handler method


argument

@SessionAttributes Causes selected model attributes to be stored in HTTP Servlet session


between requests

Controller Method Return Type Annotations


● The following annotations are applied to controller methods
○ They affecting the handling of return values of the annotated function:

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

Spring Framework Notes by Mitchell Marino

Controller Method Parameter Types


● The following table lists valid special parameters of controller methods, for which a
special object with specified functionality will be injected:

Class Description

WebRequest Contains:
● Context path (i.e., the prefix URL of the application)
● Request params
● User principal
● Etc.

ServletResponse Part of Servlet API, which helps send response

HttpSession An object representing an HttpSession


● Ensures an HTTP session exists
● If HTTP session does not exist, it will create one

Principal The currently authenticated user principal

HttpMethod The HTTP method of the request


● E.g., HttpMethod.GET

java.io.OutputStream, An output stream / writer


java.io.Writer ● When data is written to it, it will write to the response body

HttpEntity<B> Provides access to various attributes of the HTTP request:


● HTTP Headers
● Request Body

java.util.Map, Model used in controllers


org.springframework.ui.Model ● Can add attributes to the model (in case of Model object)
using addAttribute(String name, Object val)

This model will be exposed on the rendered to the view, if applicable

RedirectAttributes Extends Model interface


● Allows selection of attributes in redirect scenarios

Errors Stores data-binding and validation errors


● Can be accessed by method to determine errors that have
occurred

SessionStatus A simple interface for handling session status


● isComplete() → Check if session processing is complete
● setComplete() → Mark current handler session as complete
○ Will clean up session attributes
Page 51

Spring Framework Notes by Mitchell Marino

Controller Method Return Types


● The following table lists valid return types of controller methods:

Class Description

HttpHeaders Allows method to specify HTTP headers, with no response body

HttpEntity<B> Allows method to specify HTTP headers and response body

ResponseEntity Extension of HttpEntity that adds an HTTP status code

String Specify name of a view to be rendered

java.util.Map, A holder object for model attributes


org.springframework.ui.Model

View An object that renders a view, given:


● model → Model with {key = String, value = Object}
● request → Current HTTP request
● response → HTTP response to return

ModelAndView An object which makes it possible to return a model and a view as


a single value

Void Used in:


● Controller methods which write to output stream,
● Controller methods that do not return a response body
● Some other scenarios..

DeferredResult<V>, Asynchronously produce the return value of the controller method


ListenableFuture<V>, from another thread
CompletionState<V>,
CompletableFuture<V>,

Callable<V> Asynchronously produce the return value of the controller method


from a Spring MVC managed thread

ResponseBodyEmitter Asynchronously process requests allowing objects to be written to


the response

SseEmitter Specialization of ResponseboddyEmitter that allows for sending of


ServerSentEvents

StreamingResponseBody Asynchronously process requests allowing the application to write to


the response output stream

Reactive Types Alternative to DeferredResult for use with Reactor, RxJava, etc.

Any other return value type By default treated as a view name


Page 52

Spring Framework Notes by Mitchell Marino

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

● Authorization is the process of determining a user is permitted to perform an action


○ Example → Only admins may delete users

SecurityContextHolder Object
● SecurityContextHolder is the heart of Spring
Security’s authentication model

● Contains the SecurityContext

● Can specify default strategy to store SecurityContext:


1. Thread Local (default)
● SecurityContext will be stored in a thread-local variable
● SecurityContext will only be available in a single thread of execution
2. Inheritable Thread Local
● Same as Thread Local strategy, but child threads created by the original
thread will also have a reference to the SecurityContext
3. Global
● A SecurityContext is made available throughout the app (via any thread)

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

Spring Framework Notes by Mitchell Marino

Controller Method Return Types


● The following table lists valid return types of controller methods:

Class Description

HttpHeaders Allows method to specify HTTP headers, with no response body

HttpEntity<B> Allows method to specify HTTP headers and response body

ResponseEntity Extension of HttpEntity that adds an HTTP status code

String Specify name of a view to be rendered

java.util.Map, A holder object for model attributes


org.springframework.ui.Model

View An object that renders a view, given:


● model → Model with {key = String, value = Object}
● request → Current HTTP request
● response → HTTP response to return

ModelAndView An object which makes it possible to return a model and a view as


a single value

Void Used in:


● Controller methods which write to output stream,
● Controller methods that do not return a response body
● Some other scenarios..

DeferredResult<V>, Asynchronously produce the return value of the controller method


ListenableFuture<V>, from another thread
CompletionState<V>,
CompletableFuture<V>,

Callable<V> Asynchronously produce the return value of the controller method


from a Spring MVC managed thread

ResponseBodyEmitter Asynchronously process requests allowing objects to be written to


the response

SseEmitter Specialization of ResponseboddyEmitter that allows for sending of


ServerSentEvents

StreamingResponseBody Asynchronously process requests allowing the application to write to


the response output stream

Reactive Types Alternative to DeferredResult for use with Reactor, RxJava, etc.

Any other return value type By default treated as a view name


Page 54

Spring Framework Notes by Mitchell Marino

Filter Object
● Spring Security’s servlet support is based on Servlet Filters
○ These filters implement javax.servlet.Filter interface

● The container creates a FilterChain which contains the Filters and


Servlet which should process the request based on the request URL

● In a Spring application, the servlet will be an instance of


DispatcherServlet

● Relation between HTTP request and FilterChain:


○ 1 servlet per HTTP request
○ 1+ filters per HTTP request

● Filters may:
○ Prevent downstream Filters or Servlet from being invoked
○ Modify request or response

● The order of Filter invocation is extremely important

DelegatingFilterProxy Object
● Spring provides a Filter implementation named
DelegatingFilterProxy
○ Allows bridging between the Servlet container’s lifecycle
and Spring’s ApplicationContext

○ Generally, the Servlet container is only aware of filters


registered using its own standards (i.e., web.xml), so it is
unaware of Spring defined Beans

● DelegatingFilterProxy allows you to define Filters through Java


configuration (not via web.xml), by creating your own Filter bean
implementing the javax.servlet.Filter interface

● DelegatingFilterProxy uses the bean name to proxy the Filter


bean, using the targetBeanName property, for example:

○ DelegatingFilterProxy looks up BeanFilter0 from the


ApplicationContext and then invokes BeanFilter0
Page 53

Spring Framework Notes by Mitchell Marino

AuthenticationManager Interface
● AuthenticationManager is the API
which defines how Spring Security’s
Filters perform authentication

● The Authentication that is returned is


then set on the SecurityContext

ProviderManager Object
● The most common implementation of AuthenticationManager is ProviderManager

● AuthenticationProvider delegates to a list of AuthenticationProviders

● Each AuthenticationProvider has a decision it can make regarding authentication:


1. Success → Provide authentication successfully
2. Failure → Reject authentication fully (without visiting downstream providers)
3. Indicate cannot make decision → Allow downstream provider to decide

AuthenticationProvider Interface
● AuthenticationProviders are injected into ProviderManager
○ Can implement your own AuthenticationProvider as a bean which implements
the AuthenticationProvider interface

● Each AuthenticationProvider performs a specific type of authentication


○ E.g. DaoAuthenticationProvider supports username/password authentication

GrantedAuthority object
● A GrantedAuthority is a high-level (application-wide) permission that a user is granted
○ Stored by Authentication object within a SecurityContext

Spring Security Implementation


● Spring Security is implemented in two ways, depending on what is to be secured:

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

Spring Framework Notes by Mitchell Marino

RequestMatcher
● A RequestMatcher is used to match incoming requests (HttpServletRequest)

● Many RequestMatchers exist, the main two are:


1. AntPathRequestMatcher
2. MvcRequestMatcher

● RequestMatchers support the following wildcards:


Wildcard Description

** Matches anything up until the next forward slash ( / ) and past it

* Matches anything up until the next forward slash ( / )

● MvcRequestMatcher is the preferred choice for RequestMatcher usage for the


following reasons:
1. MvcRequestMatcher is more forgiving than AntPathRequestMatcher
■ For example:
● antMatchers("/services") matches:
○ “/services”

● mvcMatchers("/services") matches:
○ “/services”
○ “/services/”
○ “/services.html”
○ “/services.abc”

2. MvcRequestMatcher uses the same matching rules used by the


@RequestMapping annotation

● Note in the diagram on the right, BeanFilter0


represents FilterChainProxy, and it has a list
of SecurityFilterChains it may delegate to

● The order of Filters in the list matters, since the


first matching SecurityFilterChain will be have
the request delegated to it

● Recommended order of SecurityFilterChains


list to avoid unexpected matching behaviour:
○ Specific RequestMatchers first
○ Generic RequestMatchers after
Page 55

Spring Framework Notes by Mitchell Marino

FilterChainProxy Object
● Spring Security’s Servlet support is contained
within FilterChainProxy

● FilterChainProxy is a special Filter provided by


Spring Security which allows delegating to many
Filter instances through SecurityFilterChain

● Since FilterChainProxy is a bean, it is wrapped


by DelegatingFilterProxy

● Advantages of FilterChainProxy:

○ Performs mandatory tasks, such as


managing memory, applying HttpFirewall

○ Is more flexible when determining if a SecurityFilterChain should be invoked


■ Can match any part of request via RequestMatcher interface, in
comparison to Servlet container (which matches only URLs)

● A FilterChainProxy maintains a list of SecurityFilterChains


○ Will delegate to SecurityFilterChain A if A.match(request) == true

● 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

● Security Filters in SecurityFilterChain are


typically beans, but they are registered with
FilterChainProxy (not DelegatingFilterProxy)

● Each SecurityFilterChain can be unique, but


order of Filters in the SecurityFilterChain is
important, since Filters are applied in order

● The two main parts of a SecurityFilterChain are:


1. Request Matcher
2. Filters
Page 58

Spring Framework Notes by Mitchell Marino

Spring Security Web Infrastructure Overview

● Overview of Spring Security request handling lifecycle:

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

● FilterChainProxy contains a list of SecurityFilterChain instances, each of which have a


RequestMatcher and a list of Filters which should be applied to matching requests

3 The FilterChainProxy iterates over its list of SecurityFilterChain instances

● 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

● Each filter in the SecurityFilterChain is applied in order


○ Recall: The order of SecurityFilterChains within the FilterChainProxy is important, because
filters may prevent propagation of request to downstream Filters in the request
Page 59

Spring Framework Notes by Mitchell Marino

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

● Must explicitly enable method-level security using either:


1. @EnableGlobalMethodSecurity in a regular Spring application
2. @EnableReactiveMethodSecurity in a reactive Spring application

● @EnableGlobalMethodSecurity has elements which enable other annotations:


Element Annotations Enabled by setting Element = true

prePostEnabled ● @PreAuthorize ● @PreFilter


(Spring Security framework annotations) ● @PostAuthorize ● @PostFilter

jsr250Enabled ● @RolesAllowed

securedEnabled ● @Secured

Method Security Annotations


Annotation(s) Description

@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

Spring Framework Notes by Mitchell Marino

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”

@RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" })


public boolean isValidUsername(String username) { … }

● 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

Spring Framework Notes by Mitchell Marino

Spring Security Web Infrastructure Overview

● Overview of Spring Security request handling lifecycle:

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

● FilterChainProxy contains a list of SecurityFilterChain instances, each of which have a


RequestMatcher and a list of Filters which should be applied to matching requests

3 The FilterChainProxy iterates over its list of SecurityFilterChain instances

● 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

● Each filter in the SecurityFilterChain is applied in order


○ Recall: The order of SecurityFilterChains within the FilterChainProxy is important, because
filters may prevent propagation of request to downstream Filters in the request
Page 62

Spring Framework Notes by Mitchell Marino

Module 6 - REST
REST
● REST stand for REpresentational State Transfer
● Allows clients to access and manipulate text representations of resources

○ Any information which can be named is defined as a resource


■ May represent an object, an entity in a database, etc.

● REST supports CRUD operations


○ Create, Read, Update, Delete → the basic operations on REST resources

REST Pillars

Pillar Description

Scalability Rest is scalable for the following reasons:

● 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

Spring Framework Notes by Mitchell Marino

HTTP Methods
Operation HTTP Verb

Create POST

Read GET

Update PUT

Delete DELETE

Other, less-commonly used verbs: PATCH, TRACE, HEAD, OPTIONS

HTTP Status Codes

HTTP Status Codes indicate how a request has


been handled

● Can signify success, or an error of a


certain category, etc.

On the right of this box:


● A diagram showing common HTTP Status
Codes and their meanings

Below this box:


● A diagram showing HTTP Status Code
Categories. (1** means all codes starting
with 1, etc.)
Page 64

Spring Framework Notes by Mitchell Marino

@RequestBody
● @RequestBody is applied to parameters of controller methods

● It is used to bind the web request body to a method parameter


○ Then the request body can be processed however required

@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

● This annotation is frequently used when implementing back-end REST services

● @ResponseBody is not required if the class is annotated with @RestController

@RestController
● @RestController is a special stereotype annotation
○ Can be applied to classes

● @RestController is an annotation annotated with:


1. @Controller
2. @ResponseBody

● 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

● @ResponseStatus is applied at:


○ Method level
○ Class level → For which it applies to every method in the class
Page 65

Spring Framework Notes by Mitchell Marino

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

● On controller method invocation:


○ A HttpMessageConverter converts a HttpInputMessage created from the
request to the parameter type of the controller method

● On controller method return:


○ When the controller method has finished, a HttpMessageConverter converts the
object returned from the controller method to an HttpOutputMessage

● Example classes:
Class Name Description

AtomFeedHttpMessageConverter Convert to/from Atom feeds

ByteArrayHttpMessageConverter Convert to/from byte arrays

FormHttpMessageConverter Convert to/from HTML forms

MappingJackson2HttpMessageConverter Convert to/from JSON using Jackson 2.x.

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

● Methods provided by RestTemplate:


Method(s) Description

delete(...), getForObject(...), Convenient methods for setting HTTP request types and sending request
postForObject(...), put(...), etc.

execute(...) Can specify increased details compared to above row’s methods

exchange(...) Most powerful, hardest to understand, used when no other functions fulfil needs
Page 64

Spring Framework Notes by Mitchell Marino

@RequestBody
● @RequestBody is applied to parameters of controller methods

● It is used to bind the web request body to a method parameter


○ Then the request body can be processed however required

@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

● This annotation is frequently used when implementing back-end REST services

● @ResponseBody is not required if the class is annotated with @RestController

@RestController
● @RestController is a special stereotype annotation
○ Can be applied to classes

● @RestController is an annotation annotated with:


1. @Controller
2. @ResponseBody

● 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

● @ResponseStatus is applied at:


○ Method level
○ Class level → For which it applies to every method in the class
Page 67

Spring Framework Notes by Mitchell Marino

Module 7 - TESTING
Spring in Tests
● Unit Tests
○ Spring Framework is not commonly used to perform unit tests
■ Dependency Injection is generally not needed

○ Unit Tests should be done in isolation, outside the environment it is intended

● 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

Shared Application Context


● In Spring, you can share either:
1. ApplicationContext instance
■ Shared between all tests by default, as long as requested context
matches the cached one

2. ApplicationContext definition
■ Must be configured to be shared
■ Context definition is configured using the annotations:
● @ContextConfiguration
● @ActiveProfiles
● @TestPropertySource

● Sharing Context Definition can be done the following ways:

○ 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

● Can use @DirtiesContext to force Spring to create a new ApplicationContext instance


Page 68

Spring Framework Notes by Mitchell Marino

@ContextConfiguration
● @ContextConfiguration annotation defines metadata for loading and configuring the
ApplicationContext for integration tests

● @ContextConfiguration has the following optional elements:

Element Description

classes Points to @Configuration classes which will either:


1. Be annotated with @ComponentScan annotation
2. Provide @Bean definitions

inheritInitializers Whether initializers from test superclasses should be inherited


● Default: true

inheritLocations Whether locations or classes (@Configuration) from test superclasses should


be inherited
● Default: true

initializers Classes implementing the ApplicationContextInitializer interface that will be


invoked to initialize the application context
● Default: true

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

name Name of the context hierarchy level represented by this configuration

value Alias for locations

Configuration for Spring ApplicationContext can be from:


1. Annotation-based configuration (@Configuration classes) → classes element
2. XML configuration files → locations element

Configuration for initializing / loading can be from:


1. Initializing: Classes implementing ApplicationContextInitializer → initializers element
2. Loading: Classes implementing ContextLoader interface → loader element
Page 69

Spring Framework Notes by Mitchell Marino

@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

● @WebAppConfiguration must be used in conjunction with @ContextConfiguration

● Only has one element:


○ value → The resource path to the root directory of the application

Test ApplicationContext Configuration Annotations

Annotation Description

@ActiveProfiles Declares which active bean definition profiles should be used when
● class-level loading ApplicationContext for test classes

@BootstrapWith Declares which TestContextBootstrapper should be used to control


● class-level low-level Context creation for tests

@ContextHierarchy Defines a hierarchy of ApplicationContexts for integration tests


● class-level

@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

● Method-level (methodMode element)


○ BEFORE_METHOD
○ AFTER_METHOD

@TestPropertySource Configure locations of property files and declare inline properties which
● class-level should be used to configure the ApplicationContext for tests

@TestExecutionListeners Can register TestExecutionListeners to customize test execution


● class-level ● Example DirtiesContextTestExecutionListener
Page 70

Spring Framework Notes by Mitchell Marino

Test Class Configuration Annotations


● You can configure your test class to have extended functionality provided by Spring or a
3rd party library such as Mockito, by using a Runner (JUnit 4) or Extension (JUnit 5)

● Tests without Spring


○ When not using Spring framework features in your tests, but still need Mockito
features such as @Mock, use one of:
■ @RunWith(MockitoJUnitRunner.class)
■ @ExtendWith(MockitoExtension.class)

● Tests with Spring


○ When using Spring test framework features such as @MockBean, use one of:
■ @ExtendWith(SpringExtension.class)
■ @RunWith(SpringJUnit4ClassRunner.class)

○ These will register the loading of an ApplicationContext for the test class

● An overview of Test Class Configuration Annotations:


Annotation Description

@RunWith Used by JUnit to run the test in a specific class


● class-level
● Used for JUnit 4 Examples:
● @RunWith(SpringRunner.class)
● @RunWith(MockitoJUnitRunner.class)

@ExtendWith Used by JUnit to extend behaviour of test classes or methods


● class-level
● Used for JUnit 5 Examples:
● @RunWith(SpringExtension.class)
● @RunWith(MockitoExtension.class)

@SpringJUnitConfig Combines the following annotations:


● class-level ● @ContextConfiguration
● @ExtendWith(SpringExtension.class)

Has the same elements as @ContextConfiguration, except for loader

@SpringJUnitWebConfig Combines the following annotations:


● class-level ● @WebAppConfiguration
● @ExtendWith(SpringExtension.class)

Has the same elements as @ContextConfiguration, except for loader


Page 71

Spring Framework Notes by Mitchell Marino

Spring Boot Transaction Annotations


● The following annotations are used control transaction handling by test methods:
Annotation Description

@Transactional Used to alter some transactional resource in a test method


● class-level ● For example:
● method-level ○ Restore it to the same sate it had prior to the test

By default, transaction is rolled back after the test is done executing

@Commit Used to indicate that a test-managed transaction should be committed


after the test method is completed

@Rollback Used to indicate that a test-managed transaction should be rolled back


after the test method is completed

@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

JUnit Annotations for Testing


● The following annotations are used control how JUnit handles specific test methods:
Annotation Description

@Test Indicates that a public void method is executed as a test case

@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

Spring Framework Notes by Mitchell Marino

Module 7 - TESTING
Spring in Tests
● Unit Tests
○ Spring Framework is not commonly used to perform unit tests
■ Dependency Injection is generally not needed

○ Unit Tests should be done in isolation, outside the environment it is intended

● 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

Shared Application Context


● In Spring, you can share either:
1. ApplicationContext instance
■ Shared between all tests by default, as long as requested context
matches the cached one

2. ApplicationContext definition
■ Must be configured to be shared
■ Context definition is configured using the annotations:
● @ContextConfiguration
● @ActiveProfiles
● @TestPropertySource

● Sharing Context Definition can be done the following ways:

○ 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

● Can use @DirtiesContext to force Spring to create a new ApplicationContext instance


Page 68

Spring Framework Notes by Mitchell Marino

@ContextConfiguration
● @ContextConfiguration annotation defines metadata for loading and configuring the
ApplicationContext for integration tests

● @ContextConfiguration has the following optional elements:

Element Description

classes Points to @Configuration classes which will either:


1. Be annotated with @ComponentScan annotation
2. Provide @Bean definitions

inheritInitializers Whether initializers from test superclasses should be inherited


● Default: true

inheritLocations Whether locations or classes (@Configuration) from test superclasses should


be inherited
● Default: true

initializers Classes implementing the ApplicationContextInitializer interface that will be


invoked to initialize the application context
● Default: true

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

name Name of the context hierarchy level represented by this configuration

value Alias for locations

Configuration for Spring ApplicationContext can be from:


1. Annotation-based configuration (@Configuration classes) → classes element
2. XML configuration files → locations element

Configuration for initializing / loading can be from:


1. Initializing: Classes implementing ApplicationContextInitializer → initializers element
2. Loading: Classes implementing ContextLoader interface → loader element
Page 74

Spring Framework Notes by Mitchell Marino

More Spring Boot Annotations for Testing


● @MockBean
○ The @MockBean annotation injects a mock object into the ApplicationContext
■ Will replace any existing bean in the application context

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

Spring Framework Notes by Mitchell Marino

Module 8 - SPRING BOOT


Spring Boot
● Spring Boot is a Java framework which allows you to easily create stand-alone,
production-grade Spring based Java applications

● Can execute Spring Boot applications using a simple command: “java -jar jarname”

● Spring Boot provides many modules:

Module Description

Spring Boot DevTools Live-reload, speeds up development

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

● Spring Boot is opinionated, because it provides default configurations, module setups,


etc. for the application
○ It comes with a general idea of how the application should be organized, and
intelligently fits a default configuration based on defined dependencies

● Advantages of an opinionated framework:


○ Simplify setup → Minimize boilerplate code, work, etc.
○ Maximize productivity → focus on business code, not setting up tech
○ Easy integration with other technology modules

● Disadvantages of an opinionated framework:


○ May harm productivity if the application requirements do not fit most
default configurations

● The biggest benefits to Spring Boot are:


○ External configuration
■ Can specify configuration properties in a configuration/properties file
○ Autoconfiguration
■ Starter modules → Empty jars with dependencies & versions specified
● May also include auto-configuration code
Page 76

Spring Framework Notes by Mitchell Marino

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

● Spring Boot Starter benefits:


○ Focus on business code, instead of setting up technology
○ Guarantee all dependencies are present, and versions are set correctly
○ If the starter provides autoconfiguration,technology may be automatically
integrated with Spring Framework
Page 69

Spring Framework Notes by Mitchell Marino

@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

● @WebAppConfiguration must be used in conjunction with @ContextConfiguration

● Only has one element:


○ value → The resource path to the root directory of the application

Test ApplicationContext Configuration Annotations

Annotation Description

@ActiveProfiles Declares which active bean definition profiles should be used when
● class-level loading ApplicationContext for test classes

@BootstrapWith Declares which TestContextBootstrapper should be used to control


● class-level low-level Context creation for tests

@ContextHierarchy Defines a hierarchy of ApplicationContexts for integration tests


● class-level

@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

● Method-level (methodMode element)


○ BEFORE_METHOD
○ AFTER_METHOD

@TestPropertySource Configure locations of property files and declare inline properties which
● class-level should be used to configure the ApplicationContext for tests

@TestExecutionListeners Can register TestExecutionListeners to customize test execution


● class-level ● Example DirtiesContextTestExecutionListener
Page 70

Spring Framework Notes by Mitchell Marino

Test Class Configuration Annotations


● You can configure your test class to have extended functionality provided by Spring or a
3rd party library such as Mockito, by using a Runner (JUnit 4) or Extension (JUnit 5)

● Tests without Spring


○ When not using Spring framework features in your tests, but still need Mockito
features such as @Mock, use one of:
■ @RunWith(MockitoJUnitRunner.class)
■ @ExtendWith(MockitoExtension.class)

● Tests with Spring


○ When using Spring test framework features such as @MockBean, use one of:
■ @ExtendWith(SpringExtension.class)
■ @RunWith(SpringJUnit4ClassRunner.class)

○ These will register the loading of an ApplicationContext for the test class

● An overview of Test Class Configuration Annotations:


Annotation Description

@RunWith Used by JUnit to run the test in a specific class


● class-level
● Used for JUnit 4 Examples:
● @RunWith(SpringRunner.class)
● @RunWith(MockitoJUnitRunner.class)

@ExtendWith Used by JUnit to extend behaviour of test classes or methods


● class-level
● Used for JUnit 5 Examples:
● @RunWith(SpringExtension.class)
● @RunWith(MockitoExtension.class)

@SpringJUnitConfig Combines the following annotations:


● class-level ● @ContextConfiguration
● @ExtendWith(SpringExtension.class)

Has the same elements as @ContextConfiguration, except for loader

@SpringJUnitWebConfig Combines the following annotations:


● class-level ● @WebAppConfiguration
● @ExtendWith(SpringExtension.class)

Has the same elements as @ContextConfiguration, except for loader


Page 71

Spring Framework Notes by Mitchell Marino

Spring Boot Transaction Annotations


● The following annotations are used control transaction handling by test methods:
Annotation Description

@Transactional Used to alter some transactional resource in a test method


● class-level ● For example:
● method-level ○ Restore it to the same sate it had prior to the test

By default, transaction is rolled back after the test is done executing

@Commit Used to indicate that a test-managed transaction should be committed


after the test method is completed

@Rollback Used to indicate that a test-managed transaction should be rolled back


after the test method is completed

@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

JUnit Annotations for Testing


● The following annotations are used control how JUnit handles specific test methods:
Annotation Description

@Test Indicates that a public void method is executed as a test case

@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

Spring Framework Notes by Mitchell Marino

@PropertySource Annotation
● @PropertySource declaratively adds a PropertySource to Spring’s Environment
○ A PropertySource is a class representing a source of name/value property pairs

● @PropertySource is applied at class level to @Configuration classes

● @PropertySource has mandatory field:


○ value → The path of the properties file to be loaded

Logging with Spring Boot


● The default logger for Spring Boot is Logback, which is always used if available:
○ Spring-boot-starter dependency auto-configures all required beans

● By default, Spring Boot only logs to console


○ This can be changed via application.properties file, by setting:
logging.file The name of the file to log

logging.path The path to the directory for which to log

● You can adjust logging level using your application properties file:

Base Logging Level Example:

Logging.level.root = WARN

Service Logging Level Examples:

logging.level.path.to.YourClass = INFO logging.level.path.to.* = DEBUG

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

Property Name System Property Use

logging.pattern.console CONSOLE_LOG_PATTERN Configure the pattern used for console output

logging.pattern.file FILE_LOG_PATTERN Configure the pattern used for file log output
Page 81

Spring Framework Notes by Mitchell Marino

Spring Boot Database Configuration

Configuring External SQL Database Connection


● To configure an external SQL database you only need to configure 3 properties:
○ Username, Password, URL

Example:
spring.datasource.url = jdbc:mysql://localhost:8080/my-db
spring.datasource.username = user
spring.datasource.password = pass

● Can optionally specify the JDBC driver, for example:


spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

● Must also specify the connector dependency in Maven/Gradle


○ For example: artifact mysql-connector-java

● Must also have a way to access the database


○ For example: artifact spring-boot-starter-data-jdbc

Configuring Default Schema and Data


● Spring boot uses the following scripts to configure default schema and initial data:

schema.sql Contains DDL for db object creation


schema-${platform}.sql ● Customize name using spring.datasource.schema

data.sql Contains data to be inserted upon DB initialization


data-${platform}.sql ● Customize name using spring.datasource.data

● Above, ${platform} is the value of spring.datasource.platform property


○ Can easily switch between platform-specific scripts this way

● Spring Boot will only automatically initialize embedded databases.


○ To automatically initialize non-embedded databases, must add the following:
spring.datasource.initialization-mode = always

● 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

Spring Framework Notes by Mitchell Marino

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 jar differs from a regular jar because:


1. Regular jar does not contain all dependencies
2. Regular jar is not executable by default

● Fat jars are often called an “executable jar” because they use two components which
work together to execute a standalone jar:

Component Description

MANIFEST.MF file File which contains entries:


● Main-Class entry → Specifies entry point of application
● Smart-Class entry →

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

● To create a fat jar in your project, you must use spring-boot-maven-plugin

● To execute an application, simply use one command, for example:


Java -jar spring-boot-app.jar

Fat Jars with Embedded Containers


● An embedded container is used to execute executable jars / fat jars

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

1. Include spring-boot-starter-web artifact

2. Include spring-boot-maven-plugin plugin


Page 83

Spring Framework Notes by Mitchell Marino

WAR vs Embedded Container


● WAR (Web Application Archive) is a file which represents a web module

● A WAR cannot be executed in stand-alone mode


○ Instead, it must be deployed to an Application Server such as Tomcat

● WAR file structure vs. Spring Boot Fat Jar file structure is demonstrated below:

WAR file structure Spring Boot Executable Jar structure

● JSP Pages, static HTML pages ● BOOT-INF/


● Meta-INF/ ○ Classes/
● Web-INF/ ○ Lib/
○ web.xml ■ Embedded tomcat, etc.
○ classes/ ● META-INF
○ tags/ ○ MANIFEST.MF
○ lib/ ● org/springframework/boot/loader
○ JarLauncher.class
Page 84

Spring Framework Notes by Mitchell Marino

Spring Boot Actuator


● Spring Boot Actuator provides features which help to monitor and manage the Spring
Boot application:
● Monitoring
● Health-checks
● Metrics
● Audit Events

● 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>

● Default actuator endpoints include:


○ /actuator/health
○ /actuator/info

● Can enable or disable Actuator endpoints using property:


management.endpoint.${ENDPOINT_NAME}.enabled = true

For example:
management.endpoint.health.enabled = true

management.endpoint.info.enabled = false

● Can disable endpoints by default using the property:


Management.endpoint.enabled-by-default = false

● Can adjust which endpoints are exposed using the properties:


management.endpoint.web.exposure.include management.endpoint.jmx.exposure.include

management.endpoint.web.exposure.exclude management.endpoint.jmx.exposure.exclude

For example:
Expose specific endpoints management.endpoint.web.exposure.include = info, health, env

Expose all endpoints Management.endpoint.web.exposure.include = *


● Use wildcard (*)
Page 85

Spring Framework Notes by Mitchell Marino

info - Actuator Endpoint


● The info endpoint is used to provide arbitrary, non-sensitive, and custom data at runtime
○ Examples:
■ Application name, description, version
■ Java runtime, Git information

● info endpoint is exposed by default via protocols


○ HTTP → .../actuator/info

● Two ways to supply data to info endpoint:


1. Defining info.* properties in property files, for example:
info.app.name=My Application
info.app.version=1.0.0
Info.java-vendor = ${java.specification.vendor}

2. Implementing InfoContributor bean


● Use a builder → builder.withDetail(“property”, “value”)

loggers - Actuator Endpoint


● The loggers endpoint lets you list loggers and configure loggers

● loggers endpoint is exposed (not by default for HTTP) via protocols:


○ HTTP → .../actuator/logger

● To enable loggers endpoint for HTTP, do:


management.endpoints.web.exposure.include=loggers

● To view logging level for a logger via HTTP:


Use Endpoint → .../actuator/loggers/${LOGGER_NAME}

● Returns configuredLevel and effectiveLevel of the logger in response body

● Can change logging level via an HTTP POST request to:


Use Endpoint → .../actuator/loggers/${LOGGER_NAME}

● Pass the configuredLevel in the request body, for example:

● To change logger level to debug → {configuredLevel: ‘debug’}

● To clear logging level, pass empty request body → {}


Page 86

Spring Framework Notes by Mitchell Marino

health - Actuator Endpoint


● Health is an endpoint exposed by Actuator allowing system state to be checked
○ Health endpoints are usually used by monitoring software to check system status

● loggers endpoint is exposed by default via protocols:


○ HTTP → .../actuator/health

● The .../actuator/health endpoint returns aggregated information on system status


○ Evaluates all health indicators registered in HealthIndicatorRegistry

● Can change the details exposed by .../actuator/health using the following properties:
management.endpoint.health.show-details

management.endpoint.health.show-components

○ The above properties both support the following values:


never Detailed health information is never shown (default value)

when-authorized Show detailed health information only to users with roles in


property management.endpoint.health.roles

always Detailed health information is shown to all users

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

○ Health indicator statuses may be one of the following predefined statuses:


UP Component or system is functioning as expected

DOWN Component has suffered an unexpected failure

OUT_OF_SERVICE Component has been taken out of service, should not be used

UNKNOWN Component is in an unknown state

● Spring Actuator uses a HealthAggregator, (usually OrderedHealthAggregator) to


aggregate the status of all health indicators and decide on a final status

● OrderedHealthAggregator → Sorts all the statuses from all Health Indicators


○ Returns the highest priority status as the system’s final status
Page 87

Spring Framework Notes by Mitchell Marino

Health Indicators
● Can change the Health Indicator status severity order using the property:
management.health.status.order = CUSTOM, DOWN, … , UP

○ The default order of health indicators is:


■ DOWN > OUT_OF_SERVICE > UP > UNKNOWN

● 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

○ Can change default health indicator mapping using property:


management.health.status.http-mapping.${STATUS}=${HTTP CODE #}

Health Indicators Provided Out-of-Box


● Many health indicators provided out-of-the-box
○ They follow the format: ${TechnologyName}HealthIndicator

● Here are a list of some commonly-used health indicators provided by Actuator:

Health Indicator Name Description

ApplicationHealthIndicator Default implementation


● Always up

DataSourceHealthIndicator Checks status of a DataSource


● Optionally runs a rest query

DiskSpaceHealthIndicator ● Checks for low disk space

ElasticsearchHealthIndicator Checks that an Elasticsearch cluster is up

MongoHealthIndicator Check that a Mongo database is up

MailHealthIndicator Checks that a mail server is up


Page 88

Spring Framework Notes by Mitchell Marino

metrics - Actuator Endpoint


● Actuator provides a metrics endpoint, used to examine metrics collected during runtime

● Each metric may have its own dedicated URI, for example:
○ .../actuator/metrics/jvm.memory.used?tag=area:heap

● Metrics are not enabled by default

● The metrics endpoint allows you to view many out-of-the-box metrics:


○ CPU usage, memory usage, memory available
○ Thread info, Garbage collector statistics
○ Request info
○ Custom metrics

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

● Spring-metrics artifact helps with:


○ Facilitating metric collection within apps
○ Interacting with 3rd-party application monitoring systems

Actuator Endpoint Tags


● A Tag is used to filter results of a query (HTTP Request) by one or more dimensions
○ Tags are often used with metrics endpoint to filter data

● 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

● You can also combine tags:


tag=KEY:VALUE1&tag=KEY2:VALUE2

● Examples of tag usage:


.../actuator/metrics/http.server.requests?tag=status:200

.../actuator/metrics/http.server.requests?tag=status:200&tag=method:GET
Page 89

Spring Framework Notes by Mitchell Marino

Actuator - Other Significant Endpoints


● The following endpoints are available in all Spring Boot apps, so long as they are
exposed:

Endpoint id Description

auditevents Support for application auditing events

beans List of Spring beans in the application context

conditions Conditions evaluated and the results for:


● Configuration
● Auto-configuration

configprops Lists all @ConfigurationProperties

env Lists properties from the Spring ConfigurableEnvironment

health Application health information

httptrace Lists HTTP trade info about the latest HTTP request-response exchanges

info Arbitrary application information

loggers Allows for viewing/modifying applications log info

metrics Application metrics information

mappings Lists the @RequestMapping paths of the application

scheduledtasks Lists the scheduled tasks of the application

sessions Retrieval and deletion of user sessions from a Spring Session backend store
● Unavailable for reactive apps

shutdown Shutdown of the app

threaddump Expose results of a thread-dump

● 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

Spring Framework Notes by Mitchell Marino

Spring Boot Testing

@SpringBootTest Annotation
● @SpringBootTest is an annotation provided by Spring Boot which provides the
following features in addition to the regular Spring TestContext Framework:

1. Uses SpringBootContextLoader as the default context loader

2. Searches for a default configuration class annotated with


@SpringBootConfiguration unless configuration classes are specified

3. Registers a RestTestTemplate and/or WebTestClient for use in web tests using


a fully-running web server

● @SpringBootTest is used for writing JUnit integration tests for Spring Boot applications

● @SpringBootTest also offers the following unique and useful elements:

Property Description

args Application arguments that should be passed to the application under test.

classes Configuration classes to be used for loading the ApplicationContext

properties Properties to be added to the Spring Environment before the test runs, specified
in the form key=value

webEnvironment The type of web environment to create, when applicable (default=MOCK)

value An alias for properties

● To use @SpringBootTest annotation:


If using JUnit4 You must add @RunWith(SpringRunner.class) on your test class

If using JUnit5 @SpringBootTest already has @ExtendWith(SpringExtension.class)

● May leverage test autoconfiguration annotations such as @AutoConfigureMockMvc


○ More specifically, may be better to leverage @${Technology}Test annotations
■ For example: @WebMvcTest, @JdbcTest, etc.

● ${Technology}Test annotations leverage autoconfiguration annotations to make testing


easier
Page 91

Spring Framework Notes by Mitchell Marino

Testing Annotations Provided By Spring Boot


● Spring offers the autoconfiguration test annotations to make testing easier, which all also
include @ExtendWith(SpringExtension.class) for JUnit5 use

● Based on currently defined dependencies, beans, properties, etc., the following


annotations only auto-configure the test environment with what is needed for the test:
Annotation Description

@JsonTest Annotation to autoconfigure tests only focused on JSON serialization

@WebMvcTest Annotation to autoconfigure tests only focused on Spring MVC components


● @Controller, Converter, Filter, WebMvcConfigurer, etc., but not
@Component, @Service, or @Repository beans

@JdbcTest Annotation to autoconfigure tests only focused on JDBC-based components


● By default, the test is transactional and rolled back after each test
● Uses an embedded in-memory database, but can override this

@DataJpaTest Annotation to autoconfigure tests only focused on JPA components


● By default, the test is transactional and rolled back after each test
● Uses an embedded in-memory database, but can override this

@DataMongoTest Annotation to autoconfigure tests only focused on MongoDB components


● Will use an embedded in-memory MongoDB process (if available)

@RestClientTest Annotation to autoconfigure tests only focused on beans which use


RestTemplateBuilder

Spring Boot provides spring-boot-starter-test module


● Starter module spring-boot-starter-test provides these test-scope dependencies:
Dependency Description

JUnit A unit testing framework for Java

Spring Test Spring TestContext framework, helps test Spring-based functionality

Spring Boot Test Spring TestContext framework, helps test Spring Boot functionality

AssertJ An assertion library with helpful error messages and good code readability

Hamcrest A matching library which can help with assertions

Mockito A mocking framework for Java unit tests

JSONassert Converts a string into a JSON object which can be used for tests

JsonPath A query language for JSON


Page 92

Spring Framework Notes by Mitchell Marino

More Spring Boot Annotations for Testing


● @MockBean
○ The @MockBean annotation injects a mock object into the ApplicationContext
■ Will replace any existing bean in the application context

● @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}")

Web Environments in Spring Boot


● Spring boot offers the following Web Environments for testing:

Web Environment Description

NONE Creates a regular ApplicationContext (no web environment)

MOCK Creates a WebApplicationContext with a mock servlet environment

DEFINED_PORT Creates an ApplicationContext, with port to be defined by developer


● Does not specify any server.port Environment property

RANDOM_PORT Created an ApplicationContext, setting


● Specifies Environment property server.port = 0

When to use @WebMvcTest


● @WebMvcTest is used for integration tests that are focused on the app’s web layer
○ Creates an ApplicationContext which only contains web components
■ Other components can be mocked if required

● @WebMvcTest can be used in two ways:


1. Single controller configuration
● Specify the controller class → @WebMvcTest(CityController.class)

2. Multiple (all found) controller configuration


● Don’t specify any classes → @WebMvcTest
Page 93

Spring Framework Notes by Mitchell Marino

When to use @DataJpaTest


● You should use @DataJpaTest for integration tests regarding JPA components of your
application such as Entities or Repositories

● @DataJpaTest will configure:


○ In-memory database
■ Disable this by @AutoconfigureTestDatabase(replace=replace.NONE)
○ @Entity beans
○ @Repository annotated classes, or classes extending DataSource, etc.
○ TestEntityManager

● @DataJpaTest will ignore components unrelated to JPA, such as:


○ @Component annotated classes, @Service annotated classes, etc.

● Every @DataJpaTest is transactional by default → Will roll-back after tests by default


○ To adjust rollback behaviour, use @Transactional annotation or @Commit, etc.

● Can access TestEntityManager which contains a subset of EntityManager methods


that are useful for testing

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

1. A mock bean of the field’s type injected into ApplicationContext created


by @SpringBootTest

2. All beans which refer to this mocked class via @Autowired will get this
mock injected instead of the real class

● Hence the main differences:


1. @MockBean creates a mock and injects the mock into the Application Context
● Whereas @Mock just creates a mock, does not inject to anywhere

2. Injection via @InjectMocks only injects to the annotated class, and not the whole
application

You might also like