Home Page Icon
Home Page
Table of Contents for
Table of Contents
Close
Table of Contents
by Ravi Kant Soni, Rajesh RV, Amuthan Ganeshan
Spring: Developing Java Applications for the Enterprise
Spring: Developing Java Applications for the Enterprise
Table of Contents
Spring: Developing Java Applications for the Enterprise
Spring: Developing Java Applications for the Enterprise
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Introducing the Spring Framework
Introducing Spring
Features of Spring
Other features of Spring
Evolution of the Spring Framework
Spring Framework Architecture
Spring Core Container
The AOP module
Data access/integration
The Web module
The Test module
Benefits of the Spring Framework
Creating an application in Spring
Obtaining Spring JAR files
Understanding Spring packaging
SpringSource Tool Suite
The Spring application
Creating a Spring project
Adding required libraries
Creating source files
Creating the Spring bean configuration file
Running the program
Exercise
Summary
2. Inversion of Control in Spring
Understanding Inversion of Control
What is a container
Spring Container
Beans
XML-based bean configuration
BeanFactory
What is a factory pattern?
Spring BeanFactory
Implementation of BeanFactory
ApplicationContext
Implementation of ApplicationContext
Dependency Injection
Dependency Injection in Spring
The Has-A relationship
Constructor-based Dependency Injection
The <constructor-arg> element
Constructor Injection – injecting simple Java types
Constructor Injection – resolving ambiguity
No ambiguity
Solution – use index attribute
Parameter ambiguity
Solution – use type attribute
The setter-based Dependency Injection
The <property> element
Setter Injection – injecting a simple Java type
Setter Injection – injecting collections
Injecting inner beans
Injecting null and empty string values in Spring
Case 1 – injecting an empty string
Case 2 – injecting a null value
Bean definition inheritance
Inheritance with abstract
Autowiring in Spring
Autowiring modes
Autowiring using the no option
Autowiring using the byname option
Case 1 – if id=" employeeDao"
Case 2 – if id=" employeeDaoBean"
Autowiring using the byType option
Autowiring using the constructor
The bean's scope
Singleton
Prototype
Request
Session
Global session
The Spring bean life cycle
Initialization
Activation
Destruction
Initialization callbacks
Implementing the org.springframework.beans.factory.InitializingBean interface
Using init-method in the XML configuration
Destruction callbacks
Implementing the org.springframework.beans.factory.DisposableBean interface
Using destroy-method in the XML configuration
Exercise
Summary
3. DAO and JDBC in Spring
Overview of database
The DAO design pattern
The DAO layer
JDBC without Spring
Sample code
ADD drivers specific to database into the project
Directory structure of the application
The Employee.java file
The EmployeeDao.java file
The EmployeeDaoImpl.java file
The HrPayrollSystem.java file
Spring JDBC packages
JDBC with Spring
DataSource
DataSource in the DAO class
Directory structure of the application
The EmployeeDaoImpl.java file
The HrPayrollSystem.java file
What is JdbcTemplate
Configuring the JdbcTemplate object as Spring bean
The Spring.xml file
Functionality exposed by the JdbcTemplate class
Querying (select)
Updating (Insert-Update-Delete)
Other JdbcTemplate operations
Directory structure of the application
The Employee.java file
The EmployeeDao.java file
The EmployeeDaoImpl.java file
JDBC batch operation in Spring
Directory structure of the application
The EmployeeDaoImpl.java file
The HrPayrollBatchUpdate.java file
Calling a stored procedure
Using the SimpleJdbcCall class
Calling a stored procedure
The EmployeeDaoImpl.java file
Exercise
Summary
4. Hibernate with Spring
Why Object/Relational Mapping?
Introducing ORM, O/RM, and O/R mapping
Introducing Hibernate
Hibernate architecture
Configuration
SessionFactory
Session
Transaction
Query
Criteria
The Persistent object
Integrating Hibernate with the Spring Framework
Sample data model for example code
Integrating Hibernate
Required JARs for the Spring-Hibernate project
Configuring Hibernate SessionFactory in Spring
XML Spring configuration for Hibernate
hibernate.properties
Annotated domain model class
The Hibernate sessions
The Session interface methods
Persistence layer – implement DAOs
The EmployeeDao interface
The EmployeeDaoImpl class
Service layer – implement services
The EmployeeService interface
The EmployeeServiceImpl class
Directory structure of the application
Running the application
The DBUtils class
The SpringHibernateMain class
Output to console
Populated data in the Employee table
Hibernate Query Language
The Query interface
Database operation using HQL
The FROM clause
The AS clause
The SELECT clause
The WHERE clause
The ORDER BY clause
The GROUP BY clause
Using the named parameter
The UPDATE clause
The DELETE clause
Pagination using Query
Hibernate Criteria Query Language
The Criteria interface
Restrictions with Criteria
The eq method
The gt method
The lt method
The like method
The ilike method
The between method
The isNull method
The isNotNull method
The And or OR condition
Restrictions.and
Restrictions.or
Pagination using Criteria
Sorting the results
Exercise
Summary
5. Spring Security
What is Spring Security?
Major operations
Servlet filters review
Security use case
Spring Security configuration
Spring Security setup
Adding JARs to the classpath
Spring Security dependencies – pom.xml
Namespace configuration
Securing web application's URL access
The first step – web.xml
Separating security configurations
Logging into web application
HTTP basic authentication
Form-based login service
Logout service
Anonymous login
Remember Me support
Users authentication
Users authentication with in-memory definitions
Users authentication against database
Encrypting passwords
Method-level security
Let's get down to business
Project structure
Adding filters to web.xml
Resolving your view
Let's add a custom login
Mapping your login requests
Obtaining the employee list
Let's see some credentials
Time to log out
Running the application
Exercise
Summary
6. Spring Testing
Testing using JUnit 4
JUnit 4 annotations
Assert methods
An example of JUnit 4
Testing using TestNG
TestNG annotations
Example of TestNG
Agile software testing
Unit testing
Unit testing for isolated classes
Unit testing for dependent class using mock objects
The Mockito framework
Integration testing
Create unit tests of the Spring MVC controller
Spring MVC test framework
Required dependencies
Annotations in Spring testing
The @ContextConfiguration annotation
The @WebAppConfiguration annotation
MockMvc
Assertion
@RunWith(SpringJUnit4ClassRunner.class)
Exercise
Summary
7. Integrating JavaMail and JMS with Spring
E-mail support in Spring
Introducing the JavaMail API
Using the JavaMail API
The Spring API for JavaMail
Developing a Spring Mail Application
Configuration file – Spring.xml
Spring's e-mail sender
The MailerTest class
Spring Java Messaging Service
What is a message and messaging?
What is JMS?
The JMS application
JMS components
MOM Service Provider
Configuring ActiveMQ – message queue
The Spring bean configuration (Spring.xml)
MessageSender.java – Spring JMS Template
App.java
Start ActiveMQ
Output
Monitoring the broker
Exception on running App.java
Exercise
Summary
A. Solutions to Exercises
Chapter 1, Introducing the Spring Framework
Chapter 2, Inversion of Control in Spring
Chapter 3, DAO and JDBC in Spring
Chapter 4, Hibernate with Spring
Chapter 5, Spring Security
Chapter 6, Spring Testing
Chapter 7, Integrating JavaMail and JMS with Spring
B. Setting up the Application Database – Apache Derby
2. Module 2
1. Configuring a Spring Development Environment
Setting up Java
Time for action - installing JDK
Time for action - setting up environment variables
Configuring a build tool
Time for action - installing the Maven build tool
Installing a web server
Time for action - installing the Tomcat web server
Configuring a development environment
Time for action - installing Spring Tool Suite
Time for action - configuring Maven on STS
Time for action - configuring Tomcat on STS
Creating our first Spring MVC project
Time for action - creating a Spring MVC project in STS
Time for action - adding Java version properties in pom.xml
What just happened?
Spring MVC dependencies
Time for action - adding Spring jars to the project
What just happened?
A jump-start to MVC
Time for action - adding a welcome page
What just happened?
The Dispatcher servlet
Time for action - configuring the Dispatcher servlet
What just happened?
Deploying our project
Time for action - running the project
Summary
2. Spring MVC Architecture – Architecting Your Web Store
Dispatcher servlet
Time for action - examining request mapping
What just happened?
Pop quiz – request mapping
Understanding the Dispatcher servlet configuration
Time for action - examining the servlet mapping
What just happened?
Servlet mapping versus request mapping
Pop quiz - servlet mapping
Web application context
View resolvers
Time for action - understanding web application context
What just happened?
Understanding the web application context configuration
Pop quiz - web application context configuration
Model View Controller
Overview of the Spring MVC request flow
The web application architecture
The Domain layer
Time for action - creating a domain object
What just happened?
The Persistence layer
Time for action - creating a repository object
What just happened?
The Service layer
Time for action - creating a service object
What just happened?
Have a go hero - accessing the product domain object via a service
An overview of the web application architecture
Have a go hero - listing all our customers
Summary
3. Control Your Store with Controllers
The role of a Controller in Spring MVC
Defining a Controller
Time for action - adding class-level request mapping
What just happened?
Default request mapping method
Pop quiz - class level request mapping
Handler mapping
Using URI template patterns
Time for action - showing products based on category
What just happened?
Pop quiz - request path variable
Using matrix variables
Time for action - showing products based on filters
What just happened?
Understanding request parameters
Time for action - adding a product detail page
What just happened?
Pop quiz - the request parameter
Time for action - implementing a master detail View
What just happened?
Have a go hero - adding multiple filters to list products
Summary
4. Working with Spring Tag Libraries
The JavaServer Pages Standard Tag Library
Serving and processing forms
Time for action - serving and processing forms
What just happened?
Have a go hero - customer registration form
Customizing data binding
Time for action - whitelisting form fields for binding
What just happened?
Pop quiz - data binding
Externalizing text messages
Time for action - externalizing messages
What just happened?
Have a go hero - externalizing all the labels from all the pages
Summary
5. Working with View Resolver
Resolving Views
RedirectView
Time for action - examining RedirectView
What just happened?
Pop quiz - RedirectView
Flash attribute
Serving static resources
Time for action - serving static resources
What just happened?
Pop quiz - static view
Time for action - adding images to the product detail page
What just happened?
Multipart requests in action
Time for action - adding images to a product
What just happened?
Have a go hero - uploading product user manuals to the server
Using ContentNegotiatingViewResolver
Time for action - configuring ContentNegotiatingViewResolver
What just happened?
Working with HandlerExceptionResolver
Time for action - adding a ResponseStatus exception
What just happened?
Time for action - adding an exception handler
What just happened?
Summary
6. Internalize Your Store with Interceptor
Working with interceptors
Time for action - configuring an interceptor
What just happened?
Pop quiz - interceptors
LocaleChangeInterceptor - internationalization
Time for action - adding internationalization
What just happened?
Have a go hero - fully internationalize the product details page
Mapped interceptors
Time for action - mapped intercepting offer page requests
What just happened?
Summary
7. Incorporating Spring Security
Using Spring Security
Time for action - authenticating users based on roles
What just happened?
Pop quiz - Spring Security
Have a go hero - play with Spring Security
Summary
8. Validate Your Products with a Validator
Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding more validation in the Add new product page
Custom validation with JSR-303/Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding custom validation to a category
Spring validation
Time for action - adding Spring validation
What just happened?
Time for action - combining Spring validation and Bean Validation
What just happened?
Have a go hero - adding Spring validation to a product image
Summary
9. Give REST to Your Application with Ajax
Introduction to REST
Time for action - implementing RESTful web services
What just happened?
Time for action - consuming REST web services
What just happened?
Handling web services in Ajax
Time for action - consuming REST web services via Ajax
What just happened?
Summary
10. Float Your Application with Web Flow
Working with Spring Web Flow
Time for action - implementing the order processing service
What just happened?
Time for action - implementing the checkout flow
What just happened?
Understanding flow definitions
Understanding checkout flow
Pop quiz - web flow
Time for action - creating Views for every view state
What just happened?
Have a go hero - adding a decision state
Summary
11. Template with Tiles
Enhancing reusability through Apache Tiles
Time for action - creating Views for every View state
What just happened?
Pop quiz - Apache Tiles
Summary
12. Testing Your Application
Unit testing
Time for action - unit testing domain objects
What just happened?
Have a go hero - adding tests for Cart
Integration testing with the Spring Test context framework
Time for action - testing product validator
What just happened?
Time for action - testing product Controllers
What just happened?
Time for action - testing REST Controllers
What just happened?
Have a go hero - adding tests for the remaining REST methods
Summary
Thank you readers!
A. Using the Gradle Build Tool
Installing Gradle
The Gradle build script for your project
Understanding the Gradle script
B. Pop Quiz Answers
Chapter 2, Spring MVC Architecture - Architecting Your Web Store
Chapter 3, Control Your Store with Controllers
Chapter 4, Working with Spring Tag Libraries
Chapter 5, Working with View Resolver
Chapter 6, Internalize Your Store with Interceptor
Chapter 7, Incorporating Spring Security
Chapter 10, Float Your Application with Web Flow
Chapter 11, Template with Tiles
3. Module 3
1. Demystifying Microservices
The evolution of microservices
Business demand as a catalyst for microservices evolution
Technology as a catalyst for the microservices evolution
Imperative architecture evolution
What are microservices?
Microservices – the honeycomb analogy
Principles of microservices
Single responsibility per service
Microservices are autonomous
Characteristics of microservices
Services are first-class citizens
Characteristics of services in a microservice
Microservices are lightweight
Microservices with polyglot architecture
Automation in a microservices environment
Microservices with a supporting ecosystem
Microservices are distributed and dynamic
Antifragility, fail fast, and self-healing
Microservices examples
An example of a holiday portal
A microservice-based order management system
An example of a travel agent portal
Microservices benefits
Supports polyglot architecture
Enabling experimentation and innovation
Elastically and selectively scalable
Allowing substitution
Enabling to build organic systems
Helping reducing technology debt
Allowing the coexistence of different versions
Supporting the building of self-organizing systems
Supporting event-driven architecture
Enabling DevOps
Relationship with other architecture styles
Relations with SOA
Service-oriented integration
Legacy modernization
Service-oriented application
Monolithic migration using SOA
Relations with Twelve-Factor apps
A single code base
Bundling dependencies
Externalizing configurations
Backing services are addressable
Isolation between build, release, and run
Stateless, shared nothing processes
Exposing services through port bindings
Concurrency to scale out
Disposability with minimal overhead
Development and production parity
Externalizing logs
Package admin processes
Microservice use cases
Microservices early adopters
The common theme is monolithic migrations
Summary
2. Building Microservices with Spring Boot
Setting up a development environment
Developing a RESTful service – the legacy approach
Moving from traditional web applications to microservices
Using Spring Boot to build RESTful microservices
Getting started with Spring Boot
Developing the Spring Boot microservice using the CLI
Developing the Spring Boot Java microservice using STS
Examining the POM file
Examining Application.java
Examining application.properties
Examining ApplicationTests.java
Testing the Spring Boot microservice
Developing the Spring Boot microservice using Spring Initializr – the HATEOAS example
What's next?
The Spring Boot configuration
Understanding the Spring Boot autoconfiguration
Overriding default configuration values
Changing the location of the configuration file
Reading custom properties
Using a .yaml file for configuration
Using multiple configuration profiles
Other options to read properties
Changing the default embedded web server
Implementing Spring Boot security
Securing microservices with basic security
Securing a microservice with OAuth2
Enabling cross-origin access for microservices
Implementing Spring Boot messaging
Developing a comprehensive microservice example
Spring Boot actuators
Monitoring using JConsole
Monitoring using SSH
Configuring application information
Adding a custom health module
Building custom metrics
Documenting microservices
Summary
3. Applying Microservices Concepts
Patterns and common design decisions
Establishing appropriate microservice boundaries
Autonomous functions
Size of a deployable unit
Most appropriate function or subdomain
Polyglot architecture
Selective scaling
Small, agile teams
Single responsibility
Replicability or changeability
Coupling and cohesion
Think microservice as a product
Designing communication styles
Synchronous style communication
Asynchronous style communication
How to decide which style to choose?
Orchestration of microservices
How many endpoints in a microservice?
One microservice per VM or multiple?
Rules engine – shared or embedded?
Role of BPM and workflows
Can microservices share data stores?
Setting up transaction boundaries
Altering use cases to simplify transactional requirements
Distributed transaction scenarios
Service endpoint design consideration
Contract design
Protocol selection
Message-oriented services
HTTP and REST endpoints
Optimized communication protocols
API documentations
Handling shared libraries
User interfaces in microservices
Use of API gateways in microservices
Use of ESB and iPaaS with microservices
Service versioning considerations
Design for cross origin
Handling shared reference data
Microservices and bulk operations
Microservices challenges
Data islands
Logging and monitoring
Dependency management
Organization culture
Governance challenges
Operation overheads
Testing microservices
Infrastructure provisioning
The microservices capability model
Core capabilities
Infrastructure capabilities
Supporting capabilities
Process and governance capabilities
Summary
4. Microservices Evolution – A Case Study
Reviewing the microservices capability model
Understanding the PSS application
Business process view
Functional view
Architectural view
Design view
Implementation view
Deployment view
Death of the monolith
Pain points
Stop gap fix
Retrospection
Shared data
Single database
Native queries
Stored procedures
Domain boundaries
Microservices to the rescue
The business case
Plan the evolution
Evolutionary approach
Identification of microservices boundaries
Analyze dependencies
Events as opposed to query
Events as opposed to synchronous updates
Challenge requirements
Challenge service boundaries
Final dependency graph
Prioritizing microservices for migration
Data synchronization during migration
Managing reference data
User interfaces and web applications
Session handling and security
Test strategy
Building ecosystem capabilities
Migrate modules only if required
Target architecture
Internal layering of microservices
Orchestrating microservices
Integration with other systems
Managing shared libraries
Handling exceptions
Target implementation view
Implementation projects
Running and testing the project
Summary
5. Scaling Microservices with Spring Cloud
Reviewing microservices capabilities
Reviewing BrownField's PSS implementation
What is Spring Cloud?
Spring Cloud releases
Components of Spring Cloud
Spring Cloud and Netflix OSS
Setting up the environment for BrownField PSS
Spring Cloud Config
What's next?
Setting up the Config server
Understanding the Config server URL
Accessing the Config Server from clients
Handling configuration changes
Spring Cloud Bus for propagating configuration changes
Setting up high availability for the Config server
Monitoring the Config server health
Config server for configuration files
Completing changes to use the Config server
Feign as a declarative REST client
Ribbon for load balancing
Eureka for registration and discovery
Understanding dynamic service registration and discovery
Understanding Eureka
Setting up the Eureka server
High availability for Eureka
Zuul proxy as the API gateway
Setting up Zuul
High availability of Zuul
High availability of Zuul when the client is also a Eureka client
High availability when the client is not a Eureka client
Completing Zuul for all other services
Streams for reactive microservices
Summarizing the BrownField PSS architecture
Summary
6. Autoscaling Microservices
Reviewing the microservice capability model
Scaling microservices with Spring Cloud
Understanding the concept of autoscaling
The benefits of autoscaling
Different autoscaling models
Autoscaling an application
Autoscaling the infrastructure
Autoscaling in the cloud
Autoscaling approaches
Scaling with resource constraints
Scaling during specific time periods
Scaling based on the message queue length
Scaling based on business parameters
Predictive autoscaling
Autoscaling BrownField PSS microservices
The capabilities required for an autoscaling system
Implementing a custom life cycle manager using Spring Boot
Understanding the deployment topology
Understanding the execution flow
A walkthrough of the life cycle manager code
Running the life cycle manager
Summary
7. Logging and Monitoring Microservices
Reviewing the microservice capability model
Understanding log management challenges
A centralized logging solution
The selection of logging solutions
Cloud services
Off-the-shelf solutions
Best-of-breed integration
Log shippers
Log stream processors
Log storage
Dashboards
A custom logging implementation
Distributed tracing with Spring Cloud Sleuth
Monitoring microservices
Monitoring challenges
Monitoring tools
Monitoring microservice dependencies
Spring Cloud Hystrix for fault-tolerant microservices
Aggregating Hystrix streams with Turbine
Data analysis using data lakes
Summary
8. Containerizing Microservices with Docker
Reviewing the microservice capability model
Understanding the gaps in BrownField PSS microservices
What are containers?
The difference between VMs and containers
The benefits of containers
Microservices and containers
Introduction to Docker
The key components of Docker
The Docker daemon
The Docker client
Docker concepts
Docker images
Docker containers
The Docker registry
Dockerfile
Deploying microservices in Docker
Running RabbitMQ on Docker
Using the Docker registry
Setting up the Docker Hub
Publishing microservices to the Docker Hub
Microservices on the cloud
Installing Docker on AWS EC2
Running BrownField services on EC2
Updating the life cycle manager
The future of containerization – unikernels and hardened security
Summary
9. Managing Dockerized Microservices with Mesos and Marathon
Reviewing the microservice capability model
The missing pieces
Why cluster management is important
What does cluster management do?
Relationship with microservices
Relationship with virtualization
Cluster management solutions
Docker Swarm
Kubernetes
Apache Mesos
Nomad
Fleet
Cluster management with Mesos and Marathon
Diving deep into Mesos
The Mesos architecture
Marathon
Implementing Mesos and Marathon for BrownField microservices
Setting up AWS
Installing ZooKeeper, Mesos, and Marathon
Configuring ZooKeeper
Configuring Mesos
Running Mesos, Marathon, and ZooKeeper as services
Running the Mesos slave in the command line
Preparing BrownField PSS services
Deploying BrownField PSS services
Reviewing the deployment
A place for the life cycle manager
Rewriting the life cycle manager with Mesos and Marathon
The technology metamodel
Summary
10. The Microservices Development Life Cycle
Reviewing the microservice capability model
The new mantra of lean IT – DevOps
Reducing wastage
Automating every possible step
Value-driven delivery
Bridging development and operations
Meeting the trio – microservices, DevOps, and cloud
Cloud as the self-service infrastructure for Microservices
DevOps as the practice and process for microservices
Practice points for microservices development
Understanding business motivation and value
Changing the mindset from project to product development
Choosing a development philosophy
Design thinking
The start-up model
The Agile practice
Using the concept of Minimum Viable Product
Overcoming the legacy hotspot
Addressing challenges around databases
Establishing self-organizing teams
Building a self-service cloud
Building a microservices ecosystem
Defining a DevOps-style microservice life cycle process
Value-driven planning
Agile development
Continuous integration
Continuous testing
Continuous release
Continuous monitoring and feedback
Automating the continuous delivery pipeline
Development
Continuous integration
Automated testing
Different candidate tests for automation
Automated sanity tests
Regression testing
Automated functional testing
Automated acceptance testing
Performance testing
Real user flow simulation or journey testing
Automated security testing
Exploratory testing
A/B testing, canary testing, and blue-green deployments
Other nonfunctional tests
Testing in production
Antifragility testing
Target test environments
Continuous deployment
Monitoring and feedback
Automated configuration management
Microservices development governance, reference architectures, and libraries
Summary
Bibliography
Index
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Prev
Previous Chapter
Cover
Next
Next Chapter
Spring: Developing Java Applications for the Enterprise
Table of Contents
Spring: Developing Java Applications for the Enterprise
Spring: Developing Java Applications for the Enterprise
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Introducing the Spring Framework
Introducing Spring
Features of Spring
Other features of Spring
Evolution of the Spring Framework
Spring Framework Architecture
Spring Core Container
The AOP module
Data access/integration
The Web module
The Test module
Benefits of the Spring Framework
Creating an application in Spring
Obtaining Spring JAR files
Understanding Spring packaging
SpringSource Tool Suite
The Spring application
Creating a Spring project
Adding required libraries
Creating source files
Creating the Spring bean configuration file
Running the program
Exercise
Summary
2. Inversion of Control in Spring
Understanding Inversion of Control
What is a container
Spring Container
Beans
XML-based bean configuration
BeanFactory
What is a factory pattern?
Spring BeanFactory
Implementation of BeanFactory
ApplicationContext
Implementation of ApplicationContext
Dependency Injection
Dependency Injection in Spring
The Has-A relationship
Constructor-based Dependency Injection
The <constructor-arg> element
Constructor Injection – injecting simple Java types
Constructor Injection – resolving ambiguity
No ambiguity
Solution – use index attribute
Parameter ambiguity
Solution – use type attribute
The setter-based Dependency Injection
The <property> element
Setter Injection – injecting a simple Java type
Setter Injection – injecting collections
Injecting inner beans
Injecting null and empty string values in Spring
Case 1 – injecting an empty string
Case 2 – injecting a null value
Bean definition inheritance
Inheritance with abstract
Autowiring in Spring
Autowiring modes
Autowiring using the no option
Autowiring using the byname option
Case 1 – if id=" employeeDao"
Case 2 – if id=" employeeDaoBean"
Autowiring using the byType option
Autowiring using the constructor
The bean's scope
Singleton
Prototype
Request
Session
Global session
The Spring bean life cycle
Initialization
Activation
Destruction
Initialization callbacks
Implementing the org.springframework.beans.factory.InitializingBean interface
Using init-method in the XML configuration
Destruction callbacks
Implementing the org.springframework.beans.factory.DisposableBean interface
Using destroy-method in the XML configuration
Exercise
Summary
3. DAO and JDBC in Spring
Overview of database
The DAO design pattern
The DAO layer
JDBC without Spring
Sample code
ADD drivers specific to database into the project
Directory structure of the application
The Employee.java file
The EmployeeDao.java file
The EmployeeDaoImpl.java file
The HrPayrollSystem.java file
Spring JDBC packages
JDBC with Spring
DataSource
DataSource in the DAO class
Directory structure of the application
The EmployeeDaoImpl.java file
The HrPayrollSystem.java file
What is JdbcTemplate
Configuring the JdbcTemplate object as Spring bean
The Spring.xml file
Functionality exposed by the JdbcTemplate class
Querying (select)
Updating (Insert-Update-Delete)
Other JdbcTemplate operations
Directory structure of the application
The Employee.java file
The EmployeeDao.java file
The EmployeeDaoImpl.java file
JDBC batch operation in Spring
Directory structure of the application
The EmployeeDaoImpl.java file
The HrPayrollBatchUpdate.java file
Calling a stored procedure
Using the SimpleJdbcCall class
Calling a stored procedure
The EmployeeDaoImpl.java file
Exercise
Summary
4. Hibernate with Spring
Why Object/Relational Mapping?
Introducing ORM, O/RM, and O/R mapping
Introducing Hibernate
Hibernate architecture
Configuration
SessionFactory
Session
Transaction
Query
Criteria
The Persistent object
Integrating Hibernate with the Spring Framework
Sample data model for example code
Integrating Hibernate
Required JARs for the Spring-Hibernate project
Configuring Hibernate SessionFactory in Spring
XML Spring configuration for Hibernate
hibernate.properties
Annotated domain model class
The Hibernate sessions
The Session interface methods
Persistence layer – implement DAOs
The EmployeeDao interface
The EmployeeDaoImpl class
Service layer – implement services
The EmployeeService interface
The EmployeeServiceImpl class
Directory structure of the application
Running the application
The DBUtils class
The SpringHibernateMain class
Output to console
Populated data in the Employee table
Hibernate Query Language
The Query interface
Database operation using HQL
The FROM clause
The AS clause
The SELECT clause
The WHERE clause
The ORDER BY clause
The GROUP BY clause
Using the named parameter
The UPDATE clause
The DELETE clause
Pagination using Query
Hibernate Criteria Query Language
The Criteria interface
Restrictions with Criteria
The eq method
The gt method
The lt method
The like method
The ilike method
The between method
The isNull method
The isNotNull method
The And or OR condition
Restrictions.and
Restrictions.or
Pagination using Criteria
Sorting the results
Exercise
Summary
5. Spring Security
What is Spring Security?
Major operations
Servlet filters review
Security use case
Spring Security configuration
Spring Security setup
Adding JARs to the classpath
Spring Security dependencies – pom.xml
Namespace configuration
Securing web application's URL access
The first step – web.xml
Separating security configurations
Logging into web application
HTTP basic authentication
Form-based login service
Logout service
Anonymous login
Remember Me support
Users authentication
Users authentication with in-memory definitions
Users authentication against database
Encrypting passwords
Method-level security
Let's get down to business
Project structure
Adding filters to web.xml
Resolving your view
Let's add a custom login
Mapping your login requests
Obtaining the employee list
Let's see some credentials
Time to log out
Running the application
Exercise
Summary
6. Spring Testing
Testing using JUnit 4
JUnit 4 annotations
Assert methods
An example of JUnit 4
Testing using TestNG
TestNG annotations
Example of TestNG
Agile software testing
Unit testing
Unit testing for isolated classes
Unit testing for dependent class using mock objects
The Mockito framework
Integration testing
Create unit tests of the Spring MVC controller
Spring MVC test framework
Required dependencies
Annotations in Spring testing
The @ContextConfiguration annotation
The @WebAppConfiguration annotation
MockMvc
Assertion
@RunWith(SpringJUnit4ClassRunner.class)
Exercise
Summary
7. Integrating JavaMail and JMS with Spring
E-mail support in Spring
Introducing the JavaMail API
Using the JavaMail API
The Spring API for JavaMail
Developing a Spring Mail Application
Configuration file – Spring.xml
Spring's e-mail sender
The MailerTest class
Spring Java Messaging Service
What is a message and messaging?
What is JMS?
The JMS application
JMS components
MOM Service Provider
Configuring ActiveMQ – message queue
The Spring bean configuration (Spring.xml)
MessageSender.java – Spring JMS Template
App.java
Start ActiveMQ
Output
Monitoring the broker
Exception on running App.java
Exercise
Summary
A. Solutions to Exercises
Chapter 1, Introducing the Spring Framework
Chapter 2, Inversion of Control in Spring
Chapter 3, DAO and JDBC in Spring
Chapter 4, Hibernate with Spring
Chapter 5, Spring Security
Chapter 6, Spring Testing
Chapter 7, Integrating JavaMail and JMS with Spring
B. Setting up the Application Database – Apache Derby
2. Module 2
1. Configuring a Spring Development Environment
Setting up Java
Time for action - installing JDK
Time for action - setting up environment variables
Configuring a build tool
Time for action - installing the Maven build tool
Installing a web server
Time for action - installing the Tomcat web server
Configuring a development environment
Time for action - installing Spring Tool Suite
Time for action - configuring Maven on STS
Time for action - configuring Tomcat on STS
Creating our first Spring MVC project
Time for action - creating a Spring MVC project in STS
Time for action - adding Java version properties in pom.xml
What just happened?
Spring MVC dependencies
Time for action - adding Spring jars to the project
What just happened?
A jump-start to MVC
Time for action - adding a welcome page
What just happened?
The Dispatcher servlet
Time for action - configuring the Dispatcher servlet
What just happened?
Deploying our project
Time for action - running the project
Summary
2. Spring MVC Architecture – Architecting Your Web Store
Dispatcher servlet
Time for action - examining request mapping
What just happened?
Pop quiz – request mapping
Understanding the Dispatcher servlet configuration
Time for action - examining the servlet mapping
What just happened?
Servlet mapping versus request mapping
Pop quiz - servlet mapping
Web application context
View resolvers
Time for action - understanding web application context
What just happened?
Understanding the web application context configuration
Pop quiz - web application context configuration
Model View Controller
Overview of the Spring MVC request flow
The web application architecture
The Domain layer
Time for action - creating a domain object
What just happened?
The Persistence layer
Time for action - creating a repository object
What just happened?
The Service layer
Time for action - creating a service object
What just happened?
Have a go hero - accessing the product domain object via a service
An overview of the web application architecture
Have a go hero - listing all our customers
Summary
3. Control Your Store with Controllers
The role of a Controller in Spring MVC
Defining a Controller
Time for action - adding class-level request mapping
What just happened?
Default request mapping method
Pop quiz - class level request mapping
Handler mapping
Using URI template patterns
Time for action - showing products based on category
What just happened?
Pop quiz - request path variable
Using matrix variables
Time for action - showing products based on filters
What just happened?
Understanding request parameters
Time for action - adding a product detail page
What just happened?
Pop quiz - the request parameter
Time for action - implementing a master detail View
What just happened?
Have a go hero - adding multiple filters to list products
Summary
4. Working with Spring Tag Libraries
The JavaServer Pages Standard Tag Library
Serving and processing forms
Time for action - serving and processing forms
What just happened?
Have a go hero - customer registration form
Customizing data binding
Time for action - whitelisting form fields for binding
What just happened?
Pop quiz - data binding
Externalizing text messages
Time for action - externalizing messages
What just happened?
Have a go hero - externalizing all the labels from all the pages
Summary
5. Working with View Resolver
Resolving Views
RedirectView
Time for action - examining RedirectView
What just happened?
Pop quiz - RedirectView
Flash attribute
Serving static resources
Time for action - serving static resources
What just happened?
Pop quiz - static view
Time for action - adding images to the product detail page
What just happened?
Multipart requests in action
Time for action - adding images to a product
What just happened?
Have a go hero - uploading product user manuals to the server
Using ContentNegotiatingViewResolver
Time for action - configuring ContentNegotiatingViewResolver
What just happened?
Working with HandlerExceptionResolver
Time for action - adding a ResponseStatus exception
What just happened?
Time for action - adding an exception handler
What just happened?
Summary
6. Internalize Your Store with Interceptor
Working with interceptors
Time for action - configuring an interceptor
What just happened?
Pop quiz - interceptors
LocaleChangeInterceptor - internationalization
Time for action - adding internationalization
What just happened?
Have a go hero - fully internationalize the product details page
Mapped interceptors
Time for action - mapped intercepting offer page requests
What just happened?
Summary
7. Incorporating Spring Security
Using Spring Security
Time for action - authenticating users based on roles
What just happened?
Pop quiz - Spring Security
Have a go hero - play with Spring Security
Summary
8. Validate Your Products with a Validator
Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding more validation in the Add new product page
Custom validation with JSR-303/Bean Validation
Time for action - adding Bean Validation support
What just happened?
Have a go hero - adding custom validation to a category
Spring validation
Time for action - adding Spring validation
What just happened?
Time for action - combining Spring validation and Bean Validation
What just happened?
Have a go hero - adding Spring validation to a product image
Summary
9. Give REST to Your Application with Ajax
Introduction to REST
Time for action - implementing RESTful web services
What just happened?
Time for action - consuming REST web services
What just happened?
Handling web services in Ajax
Time for action - consuming REST web services via Ajax
What just happened?
Summary
10. Float Your Application with Web Flow
Working with Spring Web Flow
Time for action - implementing the order processing service
What just happened?
Time for action - implementing the checkout flow
What just happened?
Understanding flow definitions
Understanding checkout flow
Pop quiz - web flow
Time for action - creating Views for every view state
What just happened?
Have a go hero - adding a decision state
Summary
11. Template with Tiles
Enhancing reusability through Apache Tiles
Time for action - creating Views for every View state
What just happened?
Pop quiz - Apache Tiles
Summary
12. Testing Your Application
Unit testing
Time for action - unit testing domain objects
What just happened?
Have a go hero - adding tests for Cart
Integration testing with the Spring Test context framework
Time for action - testing product validator
What just happened?
Time for action - testing product Controllers
What just happened?
Time for action - testing REST Controllers
What just happened?
Have a go hero - adding tests for the remaining REST methods
Summary
Thank you readers!
A. Using the Gradle Build Tool
Installing Gradle
The Gradle build script for your project
Understanding the Gradle script
B. Pop Quiz Answers
Chapter 2, Spring MVC Architecture - Architecting Your Web Store
Chapter 3, Control Your Store with Controllers
Chapter 4, Working with Spring Tag Libraries
Chapter 5, Working with View Resolver
Chapter 6, Internalize Your Store with Interceptor
Chapter 7, Incorporating Spring Security
Chapter 10, Float Your Application with Web Flow
Chapter 11, Template with Tiles
3. Module 3
1. Demystifying Microservices
The evolution of microservices
Business demand as a catalyst for microservices evolution
Technology as a catalyst for the microservices evolution
Imperative architecture evolution
What are microservices?
Microservices – the honeycomb analogy
Principles of microservices
Single responsibility per service
Microservices are autonomous
Characteristics of microservices
Services are first-class citizens
Characteristics of services in a microservice
Microservices are lightweight
Microservices with polyglot architecture
Automation in a microservices environment
Microservices with a supporting ecosystem
Microservices are distributed and dynamic
Antifragility, fail fast, and self-healing
Microservices examples
An example of a holiday portal
A microservice-based order management system
An example of a travel agent portal
Microservices benefits
Supports polyglot architecture
Enabling experimentation and innovation
Elastically and selectively scalable
Allowing substitution
Enabling to build organic systems
Helping reducing technology debt
Allowing the coexistence of different versions
Supporting the building of self-organizing systems
Supporting event-driven architecture
Enabling DevOps
Relationship with other architecture styles
Relations with SOA
Service-oriented integration
Legacy modernization
Service-oriented application
Monolithic migration using SOA
Relations with Twelve-Factor apps
A single code base
Bundling dependencies
Externalizing configurations
Backing services are addressable
Isolation between build, release, and run
Stateless, shared nothing processes
Exposing services through port bindings
Concurrency to scale out
Disposability with minimal overhead
Development and production parity
Externalizing logs
Package admin processes
Microservice use cases
Microservices early adopters
The common theme is monolithic migrations
Summary
2. Building Microservices with Spring Boot
Setting up a development environment
Developing a RESTful service – the legacy approach
Moving from traditional web applications to microservices
Using Spring Boot to build RESTful microservices
Getting started with Spring Boot
Developing the Spring Boot microservice using the CLI
Developing the Spring Boot Java microservice using STS
Examining the POM file
Examining Application.java
Examining application.properties
Examining ApplicationTests.java
Testing the Spring Boot microservice
Developing the Spring Boot microservice using Spring Initializr – the HATEOAS example
What's next?
The Spring Boot configuration
Understanding the Spring Boot autoconfiguration
Overriding default configuration values
Changing the location of the configuration file
Reading custom properties
Using a .yaml file for configuration
Using multiple configuration profiles
Other options to read properties
Changing the default embedded web server
Implementing Spring Boot security
Securing microservices with basic security
Securing a microservice with OAuth2
Enabling cross-origin access for microservices
Implementing Spring Boot messaging
Developing a comprehensive microservice example
Spring Boot actuators
Monitoring using JConsole
Monitoring using SSH
Configuring application information
Adding a custom health module
Building custom metrics
Documenting microservices
Summary
3. Applying Microservices Concepts
Patterns and common design decisions
Establishing appropriate microservice boundaries
Autonomous functions
Size of a deployable unit
Most appropriate function or subdomain
Polyglot architecture
Selective scaling
Small, agile teams
Single responsibility
Replicability or changeability
Coupling and cohesion
Think microservice as a product
Designing communication styles
Synchronous style communication
Asynchronous style communication
How to decide which style to choose?
Orchestration of microservices
How many endpoints in a microservice?
One microservice per VM or multiple?
Rules engine – shared or embedded?
Role of BPM and workflows
Can microservices share data stores?
Setting up transaction boundaries
Altering use cases to simplify transactional requirements
Distributed transaction scenarios
Service endpoint design consideration
Contract design
Protocol selection
Message-oriented services
HTTP and REST endpoints
Optimized communication protocols
API documentations
Handling shared libraries
User interfaces in microservices
Use of API gateways in microservices
Use of ESB and iPaaS with microservices
Service versioning considerations
Design for cross origin
Handling shared reference data
Microservices and bulk operations
Microservices challenges
Data islands
Logging and monitoring
Dependency management
Organization culture
Governance challenges
Operation overheads
Testing microservices
Infrastructure provisioning
The microservices capability model
Core capabilities
Infrastructure capabilities
Supporting capabilities
Process and governance capabilities
Summary
4. Microservices Evolution – A Case Study
Reviewing the microservices capability model
Understanding the PSS application
Business process view
Functional view
Architectural view
Design view
Implementation view
Deployment view
Death of the monolith
Pain points
Stop gap fix
Retrospection
Shared data
Single database
Native queries
Stored procedures
Domain boundaries
Microservices to the rescue
The business case
Plan the evolution
Evolutionary approach
Identification of microservices boundaries
Analyze dependencies
Events as opposed to query
Events as opposed to synchronous updates
Challenge requirements
Challenge service boundaries
Final dependency graph
Prioritizing microservices for migration
Data synchronization during migration
Managing reference data
User interfaces and web applications
Session handling and security
Test strategy
Building ecosystem capabilities
Migrate modules only if required
Target architecture
Internal layering of microservices
Orchestrating microservices
Integration with other systems
Managing shared libraries
Handling exceptions
Target implementation view
Implementation projects
Running and testing the project
Summary
5. Scaling Microservices with Spring Cloud
Reviewing microservices capabilities
Reviewing BrownField's PSS implementation
What is Spring Cloud?
Spring Cloud releases
Components of Spring Cloud
Spring Cloud and Netflix OSS
Setting up the environment for BrownField PSS
Spring Cloud Config
What's next?
Setting up the Config server
Understanding the Config server URL
Accessing the Config Server from clients
Handling configuration changes
Spring Cloud Bus for propagating configuration changes
Setting up high availability for the Config server
Monitoring the Config server health
Config server for configuration files
Completing changes to use the Config server
Feign as a declarative REST client
Ribbon for load balancing
Eureka for registration and discovery
Understanding dynamic service registration and discovery
Understanding Eureka
Setting up the Eureka server
High availability for Eureka
Zuul proxy as the API gateway
Setting up Zuul
High availability of Zuul
High availability of Zuul when the client is also a Eureka client
High availability when the client is not a Eureka client
Completing Zuul for all other services
Streams for reactive microservices
Summarizing the BrownField PSS architecture
Summary
6. Autoscaling Microservices
Reviewing the microservice capability model
Scaling microservices with Spring Cloud
Understanding the concept of autoscaling
The benefits of autoscaling
Different autoscaling models
Autoscaling an application
Autoscaling the infrastructure
Autoscaling in the cloud
Autoscaling approaches
Scaling with resource constraints
Scaling during specific time periods
Scaling based on the message queue length
Scaling based on business parameters
Predictive autoscaling
Autoscaling BrownField PSS microservices
The capabilities required for an autoscaling system
Implementing a custom life cycle manager using Spring Boot
Understanding the deployment topology
Understanding the execution flow
A walkthrough of the life cycle manager code
Running the life cycle manager
Summary
7. Logging and Monitoring Microservices
Reviewing the microservice capability model
Understanding log management challenges
A centralized logging solution
The selection of logging solutions
Cloud services
Off-the-shelf solutions
Best-of-breed integration
Log shippers
Log stream processors
Log storage
Dashboards
A custom logging implementation
Distributed tracing with Spring Cloud Sleuth
Monitoring microservices
Monitoring challenges
Monitoring tools
Monitoring microservice dependencies
Spring Cloud Hystrix for fault-tolerant microservices
Aggregating Hystrix streams with Turbine
Data analysis using data lakes
Summary
8. Containerizing Microservices with Docker
Reviewing the microservice capability model
Understanding the gaps in BrownField PSS microservices
What are containers?
The difference between VMs and containers
The benefits of containers
Microservices and containers
Introduction to Docker
The key components of Docker
The Docker daemon
The Docker client
Docker concepts
Docker images
Docker containers
The Docker registry
Dockerfile
Deploying microservices in Docker
Running RabbitMQ on Docker
Using the Docker registry
Setting up the Docker Hub
Publishing microservices to the Docker Hub
Microservices on the cloud
Installing Docker on AWS EC2
Running BrownField services on EC2
Updating the life cycle manager
The future of containerization – unikernels and hardened security
Summary
9. Managing Dockerized Microservices with Mesos and Marathon
Reviewing the microservice capability model
The missing pieces
Why cluster management is important
What does cluster management do?
Relationship with microservices
Relationship with virtualization
Cluster management solutions
Docker Swarm
Kubernetes
Apache Mesos
Nomad
Fleet
Cluster management with Mesos and Marathon
Diving deep into Mesos
The Mesos architecture
Marathon
Implementing Mesos and Marathon for BrownField microservices
Setting up AWS
Installing ZooKeeper, Mesos, and Marathon
Configuring ZooKeeper
Configuring Mesos
Running Mesos, Marathon, and ZooKeeper as services
Running the Mesos slave in the command line
Preparing BrownField PSS services
Deploying BrownField PSS services
Reviewing the deployment
A place for the life cycle manager
Rewriting the life cycle manager with Mesos and Marathon
The technology metamodel
Summary
10. The Microservices Development Life Cycle
Reviewing the microservice capability model
The new mantra of lean IT – DevOps
Reducing wastage
Automating every possible step
Value-driven delivery
Bridging development and operations
Meeting the trio – microservices, DevOps, and cloud
Cloud as the self-service infrastructure for Microservices
DevOps as the practice and process for microservices
Practice points for microservices development
Understanding business motivation and value
Changing the mindset from project to product development
Choosing a development philosophy
Design thinking
The start-up model
The Agile practice
Using the concept of Minimum Viable Product
Overcoming the legacy hotspot
Addressing challenges around databases
Establishing self-organizing teams
Building a self-service cloud
Building a microservices ecosystem
Defining a DevOps-style microservice life cycle process
Value-driven planning
Agile development
Continuous integration
Continuous testing
Continuous release
Continuous monitoring and feedback
Automating the continuous delivery pipeline
Development
Continuous integration
Automated testing
Different candidate tests for automation
Automated sanity tests
Regression testing
Automated functional testing
Automated acceptance testing
Performance testing
Real user flow simulation or journey testing
Automated security testing
Exploratory testing
A/B testing, canary testing, and blue-green deployments
Other nonfunctional tests
Testing in production
Antifragility testing
Target test environments
Continuous deployment
Monitoring and feedback
Automated configuration management
Microservices development governance, reference architectures, and libraries
Summary
Bibliography
Index
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset