0% found this document useful (0 votes)
28 views106 pages

1.1 What Is Spring Framework

Uploaded by

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

1.1 What Is Spring Framework

Uploaded by

nghia250803
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 106

1.

Spring Essentials Overview


1.1 What is Spring Framework
-Spring is an Open Source, Lightweight, DI
Container and Framework for building Java
enterprise applications.
-Open Source: Spring binary and source
code are freely available. Apache 2 license
-Lightweight:
+Spring app don’t require a Java EE
application server, but they can be deployed
on one.
+Spring is not invasive: Doesn’t require to
extend framework classes or implement
framework interfaces for most usage. You
write POJOs
+Low overhead: Spring jars are small
-DI Container
+Your objects don’t have to worry about
finding/connecting to each other.
+Spring instantiates and injects dependencies
into your objects.
+Spring also serves as a lifecycle manager.
+DI container is sometimes called Inversion
of Control (IoC) Container.
-More than just a DI Container
+Enterprise apps must deal with a wide
variety of technologies:
Containerization: Cloud, Microservices
JDBC, Transactions, ORM/JPA, NoSQL
Events, Streaming, Reactive, Messaging, JMS,
AMQP, Tasks, Scheduling
Security, OAuth2, OpenID Connect
Monitoring, Observability
+Spring provides framework classes,
interfaces, and annotations to simplify
working with lower-lwevel technologies.
+Highly extensible and customizable.
1.2 Goal of Spring Framework
-Provide comprehensive infrastructural
support for developing enterprise Java
applications.
+Spring deals with the plumbing
+You focus on solving the business domain
problems
-Key principles
+Don’t Repeat Yourself (DRY)
+Separation of Concerns
+Convention over Configuration
+Testability
-DI Example: Banking Application
Configuration
-A typical application consists of several parts
working together to carry out a use case.
-Parts are Just Plain Old Java Objects (POJOs)
1.3. Spring Framework History
-Started in early 2000s with Rod Johnson’s
book
-Java ecosystem was radically different than
today
+J2EE Apis were often difficult to use and test.
+Spring aimed to simplify: Configuration via
DI, Transaction management and JDBC data
access, support for multiple deployment
environments.
-Spring becomes popular as an example of
creating enterprise applications.
-Integration with selected JSR Specs.
-Why is Spring successful:
+Provide choice at every level
+Embrace change and different perspectives
+Strong backwards compatibility
+Careful API design
+High standard for code quality
+OSS community
+Developer support on forums, Stack
Overflow
+Support of conferences and user groups.
-Spring excels at being adaptable to change
+Initial integration with other open source
projects: Hibernate, Quartz, Multiple View
Technologies
+Spring projects created for common
enterprise domains: Spring Security, Batch,
Integration
+Spring projected created for new domains:
Spring Data: NoSQL + JPA, Spring Cloud
+Spring Boot created to further simplify
DevEx
+Spring Framework support for Kotlin.
-What is Spring used for
+Spring deals with the plumbing, so you can
focus on solving the business domain.
+Spring used to build enterprise applications
dealing with: web apps, messaging,
persistence, batch/tasks,
integration/streaming
-Spring continues to adapt and innovate: JDK
Versions, Native Compilation, Reactive
Programming, Stream Processing, Kotlin
Support, Kubernetes.
1.4. Spring Overview Lab
-Preview project dependencies:
mvn -pl “project” dependency:tree
-Check 00 and 10
-Sequence diagram:
1.5. Demo-Spring Overview Lab
-Research the code carefully: 00 and 10

2. Java Configuration
2.1 Quick Start with Java Configuration
-How Spring DI Container works
-Your Application classes as POJO’s with
Dependencies

-Configuration Instructions with Dependencies

-Configuration Instructions with


Dependencies-Alternative
-Creating and Using the Application

-Accessing a Bean programmatically


-Inside the Spring Application Context

-Quick Start Summary


+Spring separates application configuration
from application objects (beans)
+Spring manages your application objects:
Creating them in the correct dependency
order + Ensuring they are fully initialized
before use.
+Each bean is given a unique id/name.
2.2 The Application Context
-Creating a Spring Application Context
+Spring application context represents Spring
DI container-Spring beans are managed
through the application context.
+Spring application context can be created in
any environment: standalone application, web
application, Junit test
-Application Context Example: create
application context in a system test
2.3 Handling Multiple Configurations
-Create an Application Context from Multiple
Configurations
+Your @Configuration class can get too big.
Instead use multiple config. files combined
with @Import.
Define a single Application Context. Beans
sourced from multiple files.

-Creating an Application Context from multiple


files
+Separation of Concerns principle: Keep
related beans in the same @Configuration
+Beast practice: separate “application” &
“infrastructure”. Infrastructure often changes
between environments.
-Mixed Configuration

-Partitioning Configuration

-Java Configuration with Dependency Injection


+Use @Autowired to inject a bean defined
elsewhere

-Avoid Tramp Data

2.4 Bean Scopes


-Default scope is singleton
-Implication for Singleton Beans
+Typical Spring application – back-end web-
server
Multiple request in parallel: Handled by
multiple thread
Implications: Multiple threads accessing
singleton beans at the same time.
+Handle multi-threading issues
Use Stateless or Immutable beans
Use synchronized (harder)
Use a different scope
-Scope Prototype: new instance created every
time bean is referenced.
-Common Spring Scopes
+Singleton: a single instance is used
+Prototype: A new instance is created each
time the bean is referenced
+Session: A new instance is created one per
user session-web environment only.
+Request: A new instance is created once per
request -web environment only.
-Other scopes:
+Spring has other more specialized scopes:
Web Socket scope, Refresh Scope, Thread
Scope (defined but not registered by default)
+Custom scopes (rarely): You define a factory
for creating bean instances + register to
define a custom scope name.
-Dependency Injection Summary

2.5 Java Configuration Lab


-Use 12
-Figure 1 Rewards Application Configuration
+Components in Application Configuration:
written by you and make up the application
logic
+Components in Application Configuration:
not written by you and are lower-level
services used by application.
-@Configuration: tell Spring to treat this class
as a set of configuration instruction to be
used when the applications is starting up.
-@Bean: create factory methods, each
method instantiates and return one of beans.
-Construction injection
-Import RewardsConfig to Test class.
2.6 Demo-Java Configuration Lab

3. More on Java Configuration


3.1 Use External Properties
-Setting property values:
+Hard-coding these properties is Bad
practice.
+Better practice is to “externalize” these
properties. One way is using property file.
-Spring’s Environment Abstraction
+Environment bean represents loaded
properties from runtime environment.
+Properties derived from various sources, in
this order: JVM System Properties
(System.getProperty)-System Environment
Variables (System.getenv)-Java Properties
Files.
-Property Sources: Environment bean obtains
values from “property sources”
+Environment variables and Java System
Properties always populated automatically.
+@PropertySource: contributes additional
properties
+Available resource prefixes: classpath:, file:,
http:

-Accessing Properties using @Value


3.2 Spring Profiles
-Beans can be grouped into profiles
+Profiles can represent environment: dev,
test, production
+Or implementation: jdbc, jpa
+Or deployment platform: on-premise, cloud
+Beans included/excluded based on profiles
membership.
-Defining Profiles
+Using @Profile annotation on configuration
class. Everything in Configuration belong to
profile

+Using @Profileon @Bean methods

+Beans when a profile is not active


-Ways to activate profiles: Profiles must be
activated at run-time
+System property via command-line:

+System property programmatically

+Integration Test only: @ActiveProfiles


-Property Source selection: @Profile can
control which @PropertySource are included
in Environment
3.3 Spring Expression Language (SpEL)
-SpEL:
+Inspired by Expression Language used in
Spring WebFlow
+Based on Unified Expression Language used
by JSP and JSF.
+Pluggable/extendable by other Spring-based
frameworks.
-Using @Value
-Accessing Spring Beans

-Access Properties
+Can access properties via environment

+Properties are Strings

-Fallback Values
-SpEL
+EL Attributes can be:
Spring beans (like strategyBean_
Implicit references: Spring’s environment,
systemProperties, systemEnvironment
available by default and others depending on
context
+SpEL allows to create custom functions and
references
Widely used in Spring projects: Spring
Security, Spring WebFlow, Spring Batch,
Spring Integration
Each may add their own implicit references
4. Component Scanning
4.1 Annotation-based Configuration
-Before-Explicit Bean Definition
+Configuration is external to bean-class:
Speration of concerns + Java-based
dependency injection

-After: Implicit Configuration


+Annotation-based configuration within bean-
class + Component-scanning

-Usage of @Autowired: Unique dependency of


correct type must exist
-@Autowired
+Default behavior: required

+Use required attribute to override default


behavior

-Java 8 Optional<T>: reduce null pointer


errors
-Constructor vs Setter Dependency Injection

+Follow the same rules as standard Java:


Constructor injection is generally preferred +
be consistent across your project team.
-Autowiring and Disambiguatino

+Use @Qualifier
+Autowiring resolution rules: Look for unique
bean of required type – Use @Qualifier if
supplied-Try to find a matching bean by name.

-Component Names
+When not specified: Names are auto-
generated.
De-capitalized non-qualified class name by
default + But will pick up implementation
details from class name
Recommendation: never rely on generated
names
+When specified: Allow disambiguation when
2 bean classes implement the same interface.
+Common strategy: avoid using qualifier
when possible. Usually rare to have 2 beans
of the same type in ApplciationContext.
-Use @Value to set Attributes

-Delayed Initialization
+Beans normally created on startup when
application context created
+Lazy beans created 1st time used: When
dependency injected + By
ApplicationContext.getBean()
+Useful if bean’s dependencies not available
at startup
+Careful-often misused. Most beans are not
lazy.

-Annotation syntax vs Java Config

4.2 Configuration Choices


-Autowiring Constructors
+If a class only has a default constructor ->
Nothing to annotate
+If a class has only one non-default
constructor
It is the only constructor available, Spring will
call it
@Autowired is optional
+If a class has more than one constructor
Spring invokes zero-argument constructor by
default (if it exists)
Or you must annotate with @Autowired the
one you want Spring to use.
-About Component Scanning
+Components are scanned at startup
JAR dependencies also scanned
Could result in slower startup time if too many
files scanned, especially for large applications
-Component Scanning Best Practices
-Mixing Java Config and Annotations
+Annotations:
In some cases, Spring will give no other
choice.
Stereotype annotations
+Java configuration
When it’s desired or required to keep beans
decoupled from Spring (legacy code, or code
that can be used outside of Spring runtime)
When managing configuration in a single
logical location is an important issue.
Can be used for all classes
4.3 Adding Startup and Shutdown Behaviors
-@PostContruct and @PreDestroy: add
behavior at startup and shutdown

-@PostConstruct & @PreDestroy


+Beans are created in the usual ways:
Returned from @Bean methods
Found and created by component-scanner
+Spring then invokes these methods
automatically during bean-creation process.
+These are not Spring annotations: Defined
by JSR-250, part of Java since Java 6 + In
javax.annotation package + Supported by
Spring, and by Java EE.
-@PostConstruct: called after setter injections
are performed
-@PreDestroy
+Called when a
ConfigurableApplicationContext is closed.
Useful for releasing resources & ‘cleaning up’
Not called for prototype beans
+Note: PreDestroy methods called if
application shuts down normally, not if the
process dies or is killed

-Lifecycle method attributes of @Bean


annotation
+Alternatively, @Bean has options to define
these life-cycle methods

+Use @PostConstruct/@PreDestroy for your


own classes. Use Lifecycle Method attributes
of @Bean annotation for classes you didn’t
write and can’t annotate.
-Use a JVM Shutdown Hook
+Shutdown hooks: automatically run when
JVM shuts down
+SpringApplication.run
Does this automatically + returns a
ConfigurableApplicationContext
4.4 Stereotype and Meta Annotations
-Stereotype Annotations
+Component scanning also checks for
annotations that are themselves annotated
with @Component, so-called stereotype
annotations

-Predefined Stereotype Annotations

-Meta-annotations
+Annotation which can be used to annotate
other annotations. E.g. all service beans
should be configurable using component
scanning and be transactional.
-Summary
+Spring beans can be defined
Explicitly using @Bean methods inside
configuration class.
Implicitly using @Component and component-
scanning
+Application can use both
Implicit for your classes
Explicit for the rest-prefer for large apps
+Can perform initialization and clean-up:
@PostConstruct and @PreDestroy
+Use Spring’s stereotypes and/or define your
own meta annotations.
4.5 Annotation and Component Scanning Lab
5. Inside the Spring Container
-Container Lifecycle: Spring Bean container
runs through 3 distinct phases
+Initialization: Spring Beans are created +
Dependency Injection occurs
+Usage: Beans are available for use in the
application
+Destruction: Beans are released for garbage
collection.

-Lifecycle of a Spring Application Context


5.1 Initialization Phase
-When a context is created, the initialization
phase completes

-In this phase, it has 2 separate steps


+Step A: Load & Process Bean Definitions
+Step B: Perform Bean Creation
-Bean Initialization Steps

-Step A: Load & Process Bean Definitions

+@Configuration classes are processed


And/or @Component annotated classes are
scanned for.
+Bean definitions added to a BeanFactory,
each indexed under its id and type.
+Special BeanFactoryPostProcessor beans
invoked, can modify the definition of any bean
-Load Bean Definitions

-BeanFactoryPostProcessor: Internal Extension


Point
+Applies transformation to bean definitions
before objects are actually created.
+Several useful implementations provided in
Spring: reading properties, registering a
custom scope..
+You can write your own (not common):
implement BeanFactoryPostProcessor
interface

-BeanFactoryPostProcessor: most common


example
+Recall @Value and ${…} variables

+Use a PropertySourcesPlaceHolderConfigurer
to evaluate them (this is a
BeanFactoryPostProcessor)
-BeanFactoryPostProcessor: Declaration
+Simply create as a bean in the usual way:
@Bean
-BeanFactoryPostProcessor: Considerations
+It’s an internal bean invoked by Spring (not
your code)
+It needs to run before any bean are created
-> Use of static @Bean method is
recommended

-PropertySouresPlaceHolderConfigurer:
Considerations
+Typically you don’t need to setup this bean
yourself. Spring Boot sets it up for you
automatically + Spring from 4.3 sets up a
basic value-resolver for you if none of this
bean exists
+When to create one manually: Use Spring
<=4.2 + you wish to configure how it work, it
can ignore System Environment and/or
System Variables
-Step B: Perform Bean Creation
+Each Bean created in turn
Dependencies injected
Optionally, may be post processed

-Bean Creation sequence of Events-Singleton


+Bean creation
Created with dependencies injected
Each singleton bean eagerly instantiated,
unless marked as lazy
+Next each bean goes through a post-
processing phase: BeanPostProcessors
+Now bean is fully initialized & ready to use,
tracked by id until the context is destroyed.
-The Initializer Extension Point
+Special case of a bean post-processing
Causes initialization methods to be called:
@PostConstruct, init-method
+Internally Spring uses serveral initializer
BPPs: CommonAnnotationBeanPostProcessor
enables @PostConstruct, @Resource

-BeanPostProcessor Extension Point:


Important extension point in Spring
+Can modify bean instances in any way.
+Powerful enabling feature
+Will run against every bean
+Can modify a bean before and/or after
initialization
BeforeInit runs before the initializer
AfterInit runs after the initializer
-BeanPostProcessor Interface
+Spring provides several implementations,
you can write your own (not common),
typically implement the after initialization
method
-Example: CustomBeanPostProcessor

-Configuration Lifecycle

5.2 Use and Destroy phases


-The Use Phase: When you invoke a bean
obtained from the context
-Case 1: Your bean is just a bean
+The bean is just your raw object: simply
invoked directly (nothing special)

-Case 2: Your bean is a Proxy


+Transactions, security exception handling…
+Your bean is wrapped in a proxy

+Proxy created during initialization phase by


a BeanPostProcessor

-Proxy Power Example: Transactions


+BeanPostProcessor may wrap your bean in a
proxy, adds behavior to your bean
transparently

-Kinds of Proxies: JDK or CGLib


-The Destruction Phase: The context is closed
(or shutdown hook invoked)

-Bean Clean Up
+All beans are cleaned up: Any registered
@PreDestroy methods are invoked + Beans
released for the Garbage Collector to destroy
+Also happens when any bean goes out of
scope, except Prototype scoped beans
+Note: Only happens if application shuts
down gracefully, not if it is killed or fails
5.3 Bean Creation Order and Injection Issues

-Creating Dependencies
+Beans have to be created in the right order:
Beans must be created after their
dependencies+
+2 steps
Evaluate dependencies for each bean
Get each dependency needed, created any if
need be, this is recursive
-You can force dependency order

-Determining Bean name & type

+1 typically returns an interface


+2 provides actual implementation class
-Why won’t this work
+No @Bean method exists returning a
BankService
+Solution 1: Return Implementation Type-
Recommended

+Solution 2: Return composite interface


-Defining Spring Beans-Best Practice
+Aim to be “sufficiently expressive”
Return interfaces, except: where multiple
interfaces exits + they are needed for
dependency injection
Writing to interface is god practice
+Warning: Even if you return implementation
types:
Still use interfaces when injecting
dependencies
Injection implementation types is brittle: DI
may fail if the bean is proxied or a different
implementation returned
-Summary
+Spring Bean Lifecycle
3 phases: initialize, use, destroy
BeanFactoryPostProcessor: Processes bean
definitions (no beans yet) + Allocate using
static @Bean method
BeanPostProcessor: Processes Beans +
Perform initialization, creates proxies
Care with @Bean Definitions: When to
consider your return types

6. Introduce Aspect Oriented Programming


6.1 What problems does AOP solve?
-AOP enables modularization of cross-cutting
concerns. The code for a cross-cutting
concern is in a single place, in a module-In
Java, a class represents a module
-What are Cross-Cutting Concerns
+ Generic functionality that is needed in
many places in your application.
+Examples of cross-cutting concerns: Logging
and Tracing, Transaction Management,
Security, Caching, Error Handling,
Performance Monitoring, Custom Business
Rules.
-An Example Requirement: Perform a role-
based security check before every application
method
+”every”: A sign this requirement is a cross-
cutting concern
-Implementing Cross Cutting Concerns
without Modularization: 2 problems
+Code tangling: Coupling of concerns

+Code scattering: The same concern spread


across modules.
+System Evolution without Modularization

+AOP enables modularization of cross-cutting


concerns-> avoid code tangling + eliminate
code scattering
-How to use AOP in application
+Implement your mainline application logic:
Focusing on the core problem
+Write aspects to implement your cross-
cutting concerns: Spring provides many
aspects immediately
+Weave the aspects into your application:
Add the cross-cutting behaviours to the right
places.
-System Evolution: AOP based

-Leading AOP Technologies


+AspectJ
Original AOP technology (1st version in 1995)
A full-blown AOP language: uses bytecode
modification for aspect weaving
+Spring AOP
Java-based AOP framework with AspectJ
integration: uses dynamic proxies for aspect
weaving
Focus on using AOP to solve enterprise
problems
6.2 Core AOP Concepts and Quick Start
-Core AOP Concepts
+Join Point: A point in the execution of a
program such as a method call or exception
thrown
+Pointcut: An expression that selects one or
more Joint Points
+Advice: Code to be executed at each
selected Join Point
+Aspect: a module that encapsulates
pointcuts and advice
+Weaving: Technique by which aspects are
combined with main code.
-Core AOP Concepts: Proxy
+Proxy: Someone who stands in place of
someone else, such as an auction or an
official meeting
+AOP Proxy: An “enhanced” class that stands
in place of your original, with extra behavior
(Aspect) added (woven) into it.
-AOP Quick Start:
+Consider this basic requirement

-An application object whose properties could


change

-Implement the Aspect

-Configure Aspect as a Bean


+Must enable use of @Aspect: Spring uses all
beans annotated with @Aspect as aspects
-Include Aspect Configuration

-Test the Application

-How Aspects are applied


-Which Setter is Proxied

-Tracking Property Changes – With Context


6.3 Define AOP Pointcut Expressions
-Defining Pointcuts
+Spring AOP uses ApsectJ’s pointcut
expressions language for selecting where to
apply advice
+Complete expression language reference
available
https://docs.spring.io/spring-framework/
reference/core/expressions.html
+Spring AOP supports a practical subset
-Common Pointcut Designator
-Example Expression:

-Execution Expression Examples:


+any class or package

+Implementation vs Interfaces
+Using Annotations

+Working with Packages

6.4 Advice Types


-Advice Types: Before
-Before Advice Example

-Advice Types: After Returning

-After Returning Advice-Example


+Use @AfterReturning with returning attribute
-Advice Types: After Throwing

-After Throwing Advice-Example


+Use @AfterThrowing with throwing attribute,
only invokes advice if the right exception type
is thrown

-After Throwing Advice-Propagation


+@AfterThrowing advice won’t stop the
exception from propagating. However it can
throw a different type of exception.

-Advice Types: After

-After Advice Example


+Use @After: It called regardless of whether
an exception has been thrown by the target or
not.
-Advice Types: Around

-Around Advice Example


+@Around and ProceedingJoinPoint, inherits
from JoinPoint and adds proceed()

-Limitations of Spring AOP


+Can only advise non-private methods
+Can only apply aspects to Spring Beans
+Limitations of weaving with proxies
When using proxies, support a() calls b() on
the same class/interface, advice will never be
executed for method b().
-Summary
+AOP modularizes cross-cutting concerns
+An aspect is a module (Java class)
containing the cross-cutting behavior.
Annotated with @Aspect
Behavior is implemented as an advice method
Pointcuts select joinpoints (methods) where
advice applies
5 advice types: Before, AfterThrowing,
AfterReturning, After and Around
6.5 Introduce AOP Lab

7.Testing Spring Applications


7.1 JUnit 5
-Testing with JUnit 5
+JUnit 5
JUnit 5 support is a major feature of Spring 5.3
JUnit 5 is the default JUnit version from Spring
Boot 2.6
Requires Java 8+ at runtime, leverages
Lambda
+Components
JUnit Platform: A foundation for launching
testing frameworks on JVM
JUnit Jupiter: An extension model for writing
tests and extensions in JUnit 5
JUnit Vintage: A TestEngine for running JUnit 3
& 4 tests on the platform.
-JUnit 5: New Programming Models
-Writing Test-JUnit 5 Style

7.2 Write Integration Tests using Spring


-Unit Testing
+Tests one unit of functionality
+Keeps dependencies minimal
+Isolated from the environment (including
Spring)
+Uses simplified alternative for
dependencies: Stubs and/or Mocks
-Integration Testing
+Integration Testing:
Tests the interaction of multiple units working
together, all should work individually first
(unit tests showed this)
+Test application classes in context of their
surrounding infrastructure
Out-of-container testing, no need to run up
full App.
Infrastructure may be scaled down, use
ActiveMQ instead of commercial messing
servers
Test Containers: Use lightweight, throwaway
instances of common databases or anything
else than can run in a Docker container.
-Integration Test Example

-Spring Support for Testing


+Spring has rich testing support
Based on TestConnect framework: Defines an
ApplicationContext for your tests
@ContextConfiguration: Defines the Spring
configuration to use
+Packaged as a separate module: spring-
test.jar
-@ExtendWith in JUnit 5
+JUnit 5 has extensible architecture via
@ExtendWith
Replace JUnit 4’s @RunWith
JUnit 5 supports multiple extensions-hence
the name
+Spring’s extension point is SpringExtension
class: A Spring aware test-runner
-Using Spring’s Test Support
-@SpringJunitConfig
+A composed annotation that combines:
@ExtendWith(SpringExtension.class) from
JUnit 5
@ContextConfiguration from Spring

-Alternative Autowiring for Tests

-Including Configuration as an Inner Class


-Multiple Test Methods

-@DirtiesContext
+Forces context to be closed at end of test
method, allows testing of @PreDestroy
behavior
+Next test gets a new Application Context,
cached context destroyed, new context
cached instead.

-Test Property Sources


+Custom properties just for testing:
Specify one or more properties: Has higher
precedence than sources
Specify location of one or more properties
files to load: Defaults to looking for
[classname].properties

-Benefits of Testing with Spring


+No need to deploy an external container to
test application functionality
Run everything quickly inside IDE or CI/CD
pipeline
Supports Continuous Integration testing
+Allows reuse of your configuration between
test and production environments
Application configuration logic is typically
reused
Infrastructure configuration is environment-
specific: DataSources, JMS Queues.
7.3 Configure Tests using Spring Profiles and
working with Databases
-Activating Profiles for a Test
+@ActiveProfiles inside test class
Define one or more profiles
Beans associated with that profile are
instantiated
Also beans not associated with any profile
+Example: 2 profiles activated-jdbc and dev
-Profiles Activation with JavaConfig

-Profiles Activation with Annotations


+@Profiles on a Component class

-Testing with Databases


+Integration testing against SQL database is
common
+In-memory database useful for this kind of
testing, no prior install needed
+Common requirement: populate DB before
test runs: Use @Sql annotation

-@Sql Options
+When/how does SQL run?
executionPhase: before (default) or afer test
method
config: Options to control SQL scripts
What to do if script fails? FAIL_ON_ERROR,
CONTINUE_ON_ERROR,
IGNORE_FAILED_DROPS, DEFAULT= whatever
@Sql defines at class level, otherwise
FALL_ON_ERROR
SQL syntax control: comments, statement
separator

-Summary
+Testing is an essential part of any
development
+Unit testing tests a class in isolation
External dependencies should be minimized
Consider creating stubs or mocks to unit test
You don’t need Spring to unit test
+Integration testing tests the interaction of
multiple units working together
Spring provided good integration testing
support
Profiles for different test & deployment
configurations
Built-in support for testing with Database
7.4 Testing Spring Applications Lab

8. JDBC Simplification with Jdbc Template

8.1 Problems with traditional JDBC and into


JdbcTemplate
-Template Design Pattern
+Widely used and useful pattern:
https://en.wikipedia.org/wiki/Template_method
_pattern
+Define the outline or skeleton of an
algorithm: Leave the details to specific
implementations later + Hide away large
amounts of boilerplate code
+Spring provides many template classes
JdbcTemplate, JmsTemplate
RestTemplate, WebServiceTemplate…
Most hide low-level resource management
-Spring’s JdbcTemplate
+Greatly simplifies use of JDBC API:
Eliminates repetitive boilerplate code +
Alleviate common causes of bugs + Handles
SQLExceptions properly
+Without sacrificing power: Provides full
access to the standard JDBC constructs.
-JdbcTemplate in a nutshell

-Use Callbacks
-Creating a JdbcTemplate
+Requires a DataSource

+Create a template once and re-use it: Don’t


create one for each thread + Thread safe
after construction
+Uses: Anytime JDBC is needed, In utility or
test code, to clean up messy legacy code
8.2 JdbcTemplate Basic Usage
-Implementing a JDBC-based Repository
-Querying with JdbcTemplate
+JdbcTemplate can query for: Simple types
(int, long, String, Date…), Generic Maps,
Domain Objects
-Query for Simple Java Types
+Query with no bind variables:

+Query with Bing Variables


Can query using bind variables -?

-Database Writes
+Insert a new row: return number of rows
modified

+Update an existing row


8.3 Working with ResultSets using Callbacks
-Generic Queries
+JdbcTemplate can return each row of a
ResulSet as a Map
When expecting a single row: queryForMap()
When expecting multiple rows: queryForList()
Useful for ad hoc reporting, testing use cases:
The data fetched doesn’t need mapping to a
Java object
Ad hoc: created or done for a particular
purpose as necessary+sometimes called
“window-on-data” queries
-Query for generic maps
-Domain Object Queries
+Often it’s useful to map relational data into
domain objects: e.g a ResultSet to an Account
+Spring’s JdbcTemplate supports this using a
callback approach
+You may prefer to use ORM for this:
Need to decide between JdbcTemplate queries
and JPA mappings. Some tables may be too
hard to map with JPA
-RowMapper for mapping a row
+Spring provides a RowMapper interface for
mapping a single row of a ResultSet to an
object: can be used for both single and
multiple row queries + Parameterized to
define its return-type
-Query for Domain Objects

-ResultSetExtractor
+Spring provides a ResultSetExtractor
interface for processing an entire ResultSet at
once: You are responsible for iterating the
ResultSet. Example: mapping entire ResultSet
to a single object.
-Using a ResultSetExtractor

-Summary of Callback Interfaces


+RowMapper: Best choice when each row of a
ResultSet maps to a domain object
+ResultSetExtractor: Best choice when
multiple rows of a ResultSet map to a single
object
+RowCallbackHandler: Yet another handler
that writes to alternative destinations.
8.4 Exception Handling
-Exception Handling and Spring
+Checked Exceptions
Force developers to handle errors, but if you
can’t handle it, must declare it.
Bad: Intermediate methods must declare
exception(s) from all methods below, a form
of tight-coupling.
+Unchecked Exceptions
Can throw up the call hierarchy to the best
place to handle it.
Good: Methods in between don’t know about
it, better inn an Enterprise Application
Spring always throws Runtime (unchecked)
Exceptions
-Data Access Exceptions
+SQLExcpetion
To general-one exception for every database
error
Calling class knows you are using JDBC
Tight coupling
+Spring provides DataAccessException
hierarchy
Hide whether you are using JPA, Hibernate,
JDBC
Actually a hierarchy of sub-exceptions: not
just one exception for everything
Consistent across all supported Data Access
technologies
Unchecked
-Example: BadSQLGrammerException

-Spring Data Access Exceptions


8. JDBC Simplification with JdbcTemplate Lab

9. Transaction Management with Spring

9.1 Why Transactions and how Java support


-What is a Transaction
+A set of tasks which take place as a single,
indivisible action
Atomic: Each unit of work is an all-or-nothing
operation
Consistent: Database integrity constraints are
never violated
Isolated: Isolating transactions from each
other
Durable: Committed changes are permanent.
+Enable concurrent access to a shared
resource
-Transactions in RewardNetwork
+rewardAccountFor(Dinning) represents a
unit-of-work that should be atomic.
-Naive Approach
+Connection per Data Access Operation
This unit-of-work contains 4 data access
operations. Each acquires, uses, and releases
a distinct Connection. The unit-of-work is non-
transactional
+Running non-Transactionally

-Partial Failures (in non-Transactional


operation)
+Suppose an Account is being rewarded

-Correct per Unit-of-Work


+More efficient: Same connection reused for
each operation
+Operations complete as an atomic unit:
Either all succeed or all fail
+The unit-of-work can run in a transaction
-Running in a Transaction
9.2 Spring Transaction Management
-Spring Transaction Management
+Spring separates transaction demarcation
from transaction implementation
Demarcation expressed declaratively via AOP,
Programmatic approach also available
PlatformTransactionManager abstraction hides
implementation details, several
implementations available
+Spring uses the same API for global vs local
Change from local to global or vice versa is
minor, just change the transaction manager
+There are only 2 steps:
Declare a PlatformTransactionManager bean
Declare the transaction methos: Using
Annotations (recommend) or Programmatic +
Can mix and match
Add @EnableTransactionManagement to a
configuration class.
-PlatformTransactionManager
implementations
+This is the base interface for abstraction
+Several implementations:
DataSourceTransactionManager,
JmsTransactionManager,
JpaTransacionManager,
JtaTransactionManager,
WebLogicJtaTransactionManager,
WebSphereUowTransactionManager
+Spring allows you to configure whether you
use JTA or not. It doesn’t have any impact on
your Java classes.
-Deploy Transaction Manager
+Create the required implementation:
Just like any other Spring bean, configure it as
appropriate.

+Bean id “transactionManager” is
recommended
-Accessing a JTA Transaction Manager
+Use a JNDI lookup for container-managed
DataSource

+Or use container-specific subclasses:


WebLogicJtaTransactionManager,
WebSphereUowTransactionManager
-@Transactional Configuration

-Declarative Transaction Management


+Target service wrapped in a proxy, uses an
around advice
+Caller injected with proxy reference
-@Transactional: What happens exactly?
+Proxy implements the following behavior
Transaction started before entering the
method
Commit at the end of method
Rollback if method throws a
RuntimeException: Default behavior+can be
overridden+Checked exception don’t cause
Rollback
All controlled by configuration
-Transaction Bound to Current Thread
+Transaction context bound to current thread:
Holds the underlying JDBC
connection+Hibernate sessions, JTA (Java EE)
work similarly
+JdbcTemplate used in @Transactional
method: Uses that connection automatically
+You can access it manually:
DataSourceUtils.getConnection(dataSource)
-@Transactional-Class Level
+Applies to all methods declared by
interface(s)

+Alternatively @Transactional can be


declared on interface instead-since Spring
Framework 5.0
-@Transactional-Class and method levels
+Combining class and method levels
-Java’s @Transactional
+Java also has an annotation:
javax.transaction.Transactional
+Not used in these examples.
9.3 Configure Transaction Propagation
-Understand Transaction Propagation
+What should happen if ClientServiceImpl
calls AccountServiceImpl

-Understand Transaction Propagation


-Transaction Propagation with Spring
+7 levels of propagation
+The following examples show REQUIRED and
REQUIRES_NEW
+Can be used as follows:

-REQUIRED
+Default value
+Execute with a current transaction, create a
new one if none exists

-REQUIRES-NEW
+Create a new transaction, suspending the
current transaction if one exists

-Propagation Rules are Enforced by a Proxy


+In example below, 2nd propagation rule
doesn’t get applied because the call doesn’t
go through a proxy

9.4 Setup Rollback Rules and Testing Support


-By default, a transaction is rolled back only if
a RuntimeException has been thrown. Could
be any kind of RunTimeException:
DataAccessException, HibernateException…
-rollbackFor and noRollbackFor
+Default settings can be overridden with
rollbackFor and/or noRollbackFor attributes

-@Transactional within Integration Test


+Annotate test method (or class) with
@Transactional:
Runs test methods in a transaction
Transaction will be rolled back afterwards: No
need to clean up your database after testing
-Control Transactional Tests

9.5 Transaction Management with Spring Lab

You might also like