Spring in Action Notes
Personal notes from going through Spring in Action 6th Edition.
Part 1: Getting started with Spring
-
Spring was created more than 18 years ago, with the fundamental mission of making Java application development easier.
-
Central to the Spring framework is the Spring application context, a container that creates and manages application components
-
The different application components are known as beans, and are wired together to make a complete application
-
The pattern of wiring beans together is known as dependency injection
-
Each bean does not have to worry about the creation and lifecycle of other dependencies (beans)
-
The Spring application container will create, maintain, and inject those dependencies into the beans
flowchart LR
subgraph Spring application context
A[Inventory Service] -- Injected into --> B[Product Service]
end
-
The
@Configurationannotation indicates to Spring that this class will provide beans to the Spring application context- Within the configuration class, there are methods annotated with
@Beanthat indicate that the objects they return are beans that should be added to the application context
- Within the configuration class, there are methods annotated with
-
Automatic configuration
- component scanning: Spring can automatically discover components from the application’s classpath, and then will create and inject them as beans in the application context
- autowire: Spring can automatically inject components with the beans that they depend on
-
Spring Boot, is an extension of the Spring Framework that increases productivity. It can make reasonable guesses at what components need to be configured and wired together.
pom.xml File
- Used for Maven projects
- Many initial dependencies are labeled with
starterin the artifact ID. These are special dependencies that don’t have any library code, but instead transitively pull in other libraries. - The Spring Boot plugin performs three functions:
- Provides a Maven goal that enables you to run the application using Maven
- Ensures that all dependency libs are included in the executable JAR file and available on the runtime classpath
- Creates a manifest file in the JAR file the denotes the bootstrap class as the main class
Handling web requests
- Spring MVC is a web framework
- controller is a core Spring MVC concept. It handles requests and responds with information.
- Controller classes are annotated with
@Controller. This lets component scanning identify the class as a controller and create an instance of the controller as a bean in the Spring application context.
Spring Boot DevTools
Hand development-time tools, including:
- Automatic application restarted on code change
- Automatic browser refresh on browser resource changes
- Automatic disabling of template caches
- Built in H2 console, if an H2 database is used
Spring Boot autoconfiguation library
When the application starts, Spring Boot autoconfiguration performs the following tasks:
- Configures the beans in the Spring application context to enable Spring MVC
- Configures the embedded Tomcat server in the Spring application context
- Configures the Thymeleaf view resolver to render Spring MVC views with Thymeleaf templates
MVC
- Model is an object that ferries data between a controller and the associated view.
- To add form validation to Spring MVC
- Add Spring Validation starter to the build
- Declare validation rules on the class to be validated
- Specify that validation should be performed in the controller methods that require it
- Update form views to display validation errors
Part 3: Reactive Spring
- When we develop application code, there are two styles of code that can be written, imperative and reactive
- Imperative - A series of tasks, that run one at a time. The next tasks isn’t run until the previous is finished. Data is processed in bulk
- Reactive - A set of tasks is defined to process data, but they can run in parallel. And each task can work on a subset of a dataset and hand it off to the next task
- Project Reactor is a Spring project
Reactive programming
- Reactive programming is an alternative to imperative programming
- In imperative programming, each step is executed, and then for I/O steps the thread is blocked and it can’t do anything until the blocking I/O step is complete
- Most programming languages support concurrent programming, where another thread will spin up and be able to do work in the meantime
- Reactive programming is function and declarative, it describes a pipeline, or stream, through which data flows
- Reactive streams process data as it becomes available, rather than processing data as a whole
- Reactive Streams aim to provide a standard for asynchronous stream processing with nonblocking backpressure.
- Backpressure enables data consumers of data to manage the velocity of a data source
Reactive Streams spec
- Has four main interface definitions:
- Publisher
- Subscriber
- Subscription
- Processor/Transformer
A Publisher produces data that is sends to a Subscriber per a Subscription
public interface Publisher<T> {
void subscribe(Subscriber<? super T> subscriber);
}
Once a Subscriber has subscribed, it can receive events from a Publisher. Those events are sent over the methods on the Subscriber interface.
public interface Subscriber<T> {
void onSubscribe(Subscription sub);
void onNext(T item);
void onError(Throwable ex);
void onComplete();
}
The first call to a Subscriber is when the Publisher calls onSubscribe(). It passes a Subscription object to the Subscriber, which allows the Subscriber to manage the Subscription.
public interface Subscription {
void request(long n);
void cancel();
}
The Subscriber will call request with the number of data it wants to receive (backpressure). After it has received the given count, it can call request again. It can call cancel() if it no longer wants to receive items. onNext will be called for each item given. When all data has been sent, the Publisher will call onComplete.
A Processor/Transformer is a combination of a Publisher and a Subscriber.
public interface Processor<T, R>
extends Subscriber<T>, Publisher<R> {}
As a Subscriber, a Processor will receive data and process it in some way. Then is will switch and act as a Publisher to publish the results to its Subscribers.
Project Reactor is an implementation of the React Streams specification that provides a functional API for composing Reactive Streams.
- Reactive programming means building a pipeline through which data will flow, as opposed to imperative programming where a set of steps to be taken is described.
MonoandFlushare both implementations of Reactive Stream’sPublisherFluxrepresents a pipeline of zero, one, or many data itemsMonois a specialized reactive type that’s optimized for when the dataset is known to have no more than one data itemFluxandMonooffer more than 500 operations that can be categorized into: Creation, Combination, Transformation, and Logic- When you create a
MonoorFlux, you have to subscribe to the data in order for it to flow
Developing reactive APIs
- Spring WebFlux is Spring’s reactive web framework. It’s very similar to Spring MVC.
- Typical servlet web frameworks, like Spring MVC, are blocking and multithreaded, using a single thread per connection
- As requests are handled, a worker thread is pulled from a thread pool to process the request. Meanwhile, the request thread is blocked until it’s notified by the worker thread that it’s finished.
- Blocking web frameworks don’t scale effectively under a heavy request volume
- Asynchronous web frameworks achieve higher scalability with fewer threads, generally one per CPU core
- By using a technique called event looping, these frameworks can handle many requests per thread, making the per-connection cost more economical