Master the Spring Framework, its fundamentals and core topics, and share the authors’ insights and real-world experiences. This book goes well beyond the basics: you'll learn how to leverage the latest Spring Framework 6 to build the various tiers and parts of today's modern, complex enterprise Java applications systems, top to bottom, including data access, SQL generation with jOOQ, persistence with Hibernate, transactions, set up security, classic web and presentation tiers and adding in some reactivity. Spring 6 will be based on the latest available Long Term Support (LTS) release, Java 17. So, you will be able to do the following in your Spring applications: use records, use new utility methods in String class; utilize Local-Variable Syntax for Lambda Parameters; Nested Based Access Control, and more. Integrating Spring with the most used frameworks and libraries is covered in this book, such as Testcontainers, Hibernate, jOOQ, Kafka and many others. A full sample application allows you to apply many of the technologies and techniques covered in Pro Spring 6 and see how they work together. This book updates the perennial bestseller with the latest that Spring Framework 6 has to offer. Now in its sixth edition, this popular title is by far the most comprehensive and definitive treatment of Spring available. After reading this book, you'll be armed with the power of Spring to build complex applications, top to bottom. The agile, lightweight, open-source Spring Framework continues to be the de facto leading enterprise Java application development framework for today's Java programmers and developers. What You Will Learn What’s new in Spring Framework 6 and how to use it with the latest LTS version of Java, Java 17 How to integrate Spring with the most renowned and practical frameworks and dependencies How to build complex enterprise cloud-native applications using Spring 6 How to master data access, persistence and transactions How to use with Spring Batch, Integration and other key Spring projects This Book Is ForExperienced Java and enterprise Java developers and programmers. Some experience with Spring highly recommended.
Author(s): Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho
Edition: 6
Publisher: Apress
Year: 2023
Language: English
Pages: 949
Table of Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: Introducing Spring
About This Book
What Is Spring?
Evolution of the Spring Framework
Spring Projects
Inverting Control or Injecting Dependencies?
Evolution of Dependency Injection
Beyond Dependency Injection
The Spring Community
Alternatives to Spring
Summary
Chapter 2: Getting Started
Conventions
Who This Book Is For
What You Need for This Book
Prepare Your Development Environment
Understanding Spring Packaging
Choosing Modules for Your Application
Accessing Spring Modules on the Maven Repository
Accessing Spring Modules Using Gradle
Using Spring Boot Dependency Management
Using Spring Documentation
Putting a Spring into Hello World
Building the Sample Hello World Application
Refactoring with Spring
Using Spring XML Configuration
Spring Configuration Using Annotations
Summary
Chapter 3: Introducing IoC and DI in Spring
Inversion of Control and Dependency Injection
Types of Inversion of Control
Dependency Pull
Contextualized Dependency Lookup
Constructor Dependency Injection
Setter Dependency Injection
Injection vs. Lookup
Setter Injection vs. Constructor Injection
Inversion of Control in Spring
Dependency Injection in Spring
Beans and BeanFactory
Configuring ApplicationContext
Basic Configuration Overview
Declaring Spring Components
Using Setter Injection
Using Constructor Injection
Using Field Injection
Using Injection Parameters
Injecting Simple Values
Injecting Values Using SpEL
Injection and ApplicationContext Nesting
Injecting Collections
Using Method Injection
Lookup Method Injection
Considerations for Lookup Method Injection
Understanding Bean Naming
Default Bean Naming Style for Beans Declared with @Component
Customizing Bean Naming Style
Bean Naming Style for Beans Declared with @Bean
Explicit Bean Naming
The @AliasFor Annotation
Understanding Bean Instantiation Mode
Choosing an Instantiation Mode
Additional Bean Scopes
Resolving Dependencies
Autowiring Your Bean
Constructor Autowiring
byType Autowiring
byName Autowiring
Yet Another Pickle
When to Use Autowiring
Summary
Chapter 4: Advanced Spring Configuration and Spring Boot
Spring’s Impact on Application Portability
Bean Life-Cycle Management
Hooking into Bean Creation
Executing a Method When a Bean Is Created
Implementing the InitializingBean Interface
Using the JSR-250 @PostConstruct Annotation
Understanding Order of Resolution
Hooking into Bean Destruction
Executing a Method When a Bean Is Destroyed
Implementing the DisposableBean Interface
Using the JSR-250 @PreDestroy Annotation
Understanding Order of Resolution
Using a Shutdown Hook
Making Your Beans “Spring Aware”
Using the BeanNameAware Interface
Using the ApplicationContextAware Interface
Use of FactoryBeans
FactoryBean Example: The MessageDigestFactoryBean
Accessing a FactoryBean Directly
JavaBeans PropertyEditors
Using the Built-in PropertyEditors
Creating a Custom PropertyEditor
More Spring ApplicationContext Configuration
Internationalization
Internationalization with MessageSource
Using the getMessage() Method
Why Use ApplicationContext As a MessageSource?
Using MessageSource in Stand-Alone Applications
The MessageSourceResolvable Interface
Events Publication
Using Application Events
Considerations for Event Usage
Accessing Resources
Advanced Java Configuration Classes
Profiles
An Example of Using the Spring Profiles Feature
Considerations for Using Profiles
Environment and PropertySource Abstraction
Testing Spring Applications
Using Spring Test Annotations
Implementing Logic Unit Tests
Implementing an Integration Test
Configuring Profile for Integration Testing
Implementing a Front-End Unit Test
Introducing Selenium
Configuration Using Groovy
Using Spring Boot
Summary
Chapter 5: Spring AOP
AOP Concepts
Types of AOP
Static AOP
Dynamic AOP
Choosing an AOP Type
AOP in Spring
The AOP Alliance
Spring AOP Architecture
Joinpoints in Spring
Aspects in Spring
The ProxyFactory Class
Creating Advice in Spring
Interfaces for Advice
Creating Advice Programmatically
A Few Conclusions
Choosing an Advice Type
Advisors and Pointcuts in Spring
The Pointcut Interface
Available Pointcut Implementations
Using DefaultPointcutAdvisor
Using StaticMethodMatcherPointcut
Using DynamicMethodMatcherPointcut
Using Simple Name Matching
Creating Pointcuts with Regular Expressions
Creating Pointcuts with AspectJ Pointcut Expression
Creating Annotation Matching Pointcuts
Understanding Proxies
Using JDK Dynamic Proxies
Using CGLIB Proxies
Comparing Proxy Performance
Choosing a Proxy to Use
Advanced Use of Pointcuts
Using Control Flow Pointcuts
Using a Composable Pointcut
Composition and the Pointcut Interface
Pointcut Summary
Getting Started with Introductions
Introduction Basics
Object Modification Detection with Introductions
Using the IsModified Interface
Creating a Mixin
Creating an Advisor
Putting It All Together
Introduction Summary
Framework Services for AOP
Configuring AOP Declaratively
Using ProxyFactoryBean
Using ProxyFactoryBean for Introductions
ProxyFactoryBean Summary
Using @AspectJ-Style Annotations
Declarative Before Advice with AspectJ Annotations
Declarative Around Advice with AspectJ Annotations
Declarative After Advice with AspectJ Annotations
Declarative Introductions with AspectJ Annotations
Aspect Instantiation Models
Spring Boot AOP
Considerations for Declarative Spring AOP Configuration
Summary
Chapter 6: Spring Data Access with JDBC
Sample Data Model for Example Code
Exploring the JDBC Infrastructure
Spring JDBC Infrastructure
Overview and Used Packages
Database Connections and DataSources
Embedded Database Support
Using DataSources in DAO Classes
Exception Handling
The JdbcTemplate Class
Initializing JdbcTemplate in a DAO Class
Using Named Parameters with NamedParameterJdbcTemplate
Retrieving Domain Objects with RowMapper
Retrieving Nested Domain Objects with ResultSetExtractor
Spring Classes That Model JDBC Operations
Querying Data by Using MappingSqlQuery
Updating Data by Using SqlUpdate
Inserting Data and Retrieving the Generated Key
Batching Operations with BatchSqlUpdate
Calling Stored Functions by Using SqlFunction
Spring Data Project: JDBC Extensions
Spring JDBC Testing Annotations
Introducing Testcontainers
Considerations for Using JDBC
Spring Boot JDBC
Summary
Chapter 7: Spring with Hibernate
Sample Data Model for Example Code
Configuring Hibernate’s SessionFactory
ORM Mapping Using Hibernate Annotations
Simple Mappings
One-to-Many Mappings
Many-to-Many Mappings
The Hibernate Session Interface
Querying Data by Using the Hibernate Query Language
Simple Querying with Lazy Fetching
Querying with Associations Fetching
Inserting Data
Updating Data
Deleting Data
Executing SQL Native Queries
Executing Projections with Hibernate
Calling Stored Functions with Hibernate
Configuring Hibernate to Generate Tables from Entities
Annotating Methods or Fields?
Considerations When Using Hibernate
Introducing jOOQ
Summary
Chapter 8: Spring with JPA
Introducing JPA 3.1
Sample Data Model for Example Code
Configuring JPA’s EntityManagerFactory
Using JPA Annotations for ORM Mapping
Performing Database Operations with JPA
Using the Java Persistence Query Language to Query Data
Querying with Untyped Results
Querying for a Custom Result Type with a Constructor Expression
Inserting Data
Updating Data
Deleting Data
Using a Native Query
Using a Simple Native Query
Native Querying with SQL ResultSet Mapping
Executing Stored Functions and Procedures
Using the JPA Criteria API for a Criteria Query
Summary
Chapter 9: Spring Transaction Management
Exploring the Spring Transaction Abstraction Layer
Transaction Types
Implementations of the PlatformTransactionManager
Analyzing Transaction Properties
The TransactionDefinition Interface
The TransactionStatus Interface
Sample Data Model and Infrastructure for Example Code
Using Declarative Transactions
Rolling Back Transactions
Using Programmatic Transactions
Considerations on Transaction Management
Transactional Configuration with Spring Boot
Transactional Tests
Considerations on Transaction Management
Summary
Chapter 10: Spring Data with SQL and NoSQL Databases
Introducing Spring Data JPA
Using Spring Data JPA Repository Abstraction for Database Operations
Using JpaRepository
Spring Data JPA with Custom Queries
Projection Queries
Keeping Track of Changes on the Entity Class
Keeping Entity Versions by Using Hibernate Envers
Adding Tables for Entity Versioning
Configuring EntityManagerFactory for Entity Versioning
Enabling Entity Versioning and History Retrieval
Custom Implementations for Spring Data Repositories
Spring Boot Data JPA
Considerations Using Spring Data JPA
Spring Data with MongoDB12
MongoDB Concepts
Considerations Using Spring Data
Summary
Chapter 11: Validation, Formatting, and Type Conversion
Converting String Values Using PropertyEditors
Introducing Spring Type Conversion
Implementing a Custom Converter
Converting Between Arbitrary Types
Field Formatting in Spring
Validation in Spring
Using the Spring Validator Interface
Using JSR-349/Jakarta Bean Validation
Dependencies
Defining Validation Constraints on Domain Object Properties
Configuring Bean Validation Support in Spring
Creating a Custom Validator
Using AssertTrue for Custom Validation
Deciding Which Validation API to Use
Configuring Validation in a Spring Boot Application
Summary
Chapter 12: Task Execution and Scheduling
Task Executing in Java
Task Executing in Spring
Task Scheduling in Spring
Introducing the Spring TaskScheduler Abstraction
Exploring a Sample Task
Asynchronous Task Execution in Spring
Summary
Chapter 13: Spring Remoting
Communication via HTTP Using Spring REST
Using JMS in Spring
Working with Apache ActiveMQ Artemis
Using Spring for Apache Kafka
Summary
Chapter 14: Spring MVC
Setting Up the Data and Lower-Level Layers
Introducing MVC
Introducing Spring MVC
Spring MVC WebApplicationContext Hierarchy
Spring MVC Request Life Cycle
Spring MVC Configuration
Creating the First View in Spring MVC
Configuring DispatcherServlet
Implementing Spring Controllers
Implementing the View
Testing the Home View
Understanding the Spring MVC Project Structure
Enabling Internationalization (i18n)
Configuring i18n in the DispatcherServlet Configuration
Modifying Views for i18n Support
Using Theming and Templating
Theming Support
Designing the Template Layout
Implementing More Complex Views
Implementing the List Singers View
Implementing the Show Singer View
Handling a Delete Request
Implementing the Edit Singer View
Implementing the Create Singer View
Enabling JSR-349 (Bean Validation)
Exception Handling
Switching to Spring Boot
Testing a Spring Boot Web Application
Summary
Chapter 15: Spring REST Support
Introducing RESTful Web Services
Using Spring MVC to Expose RESTful Web Services
Implementing SingerController
Testing the RESTful-WS Application
REST Exception Handling Using ResponseEntity
REST Exception Handling Using @RestControllerAdvice
RESTful-WS with Spring Boot
Summary
Chapter 16: Spring Native and Other Goodies
Spring Native Images
The Application
The Configuration
Spring for GraphQL
Spring Kotlin Applications
The Configuration
The Code
Summary
Chapter 17: Securing Spring Web Applications
Configuring Spring Security: The Classic Way
JDBC Authentication
Testing Secured Web Applications
Configuring Spring Security: The Spring Boot Way
Summary
Chapter 18: Monitoring Spring Applications
JMX Support in Spring
Exporting a Spring Bean to JMX
Using VisualVM for JMX Monitoring
Monitoring Hibernate Statistics
JMX with Spring Boot
Monitoring Applications with Spring Boot Actuator
Spring Boot Actuator Endpoints
Using Spring Boot Actuator with Micrometer
Summary
Chapter 19: Spring WebSocket Support
Introducing WebSocket
Using WebSocket with Spring
Using the WebSocket API
Using SockJS
Sending Messages with STOMP
Spring Boot Equivalent Application
Summary
Chapter 20: Reactive Spring
Introduction to Reactive Programming in Spring
Introducing Spring WebFlux
Spring Boot Configuration for a Reactive application
Reactive Repository and Database
Reactive Services
Reactive Controllers
Handler Classes and Functional Endpoints
Reactive Error Handling
Testing Reactive Endpoints with WebTestClient
Reactive Web Layer
Handler Functions Validation
Summary
Appendix A
Setting Up Your Development
Introducing project pro-spring-6
Understanding the Gradle Configuration
Understanding the Maven Configuration
Using Docker
Building and Troubleshooting
Index