You are on page 1of 83

Spring MVC/REST

PY
Introduction to
Spring 5 and
d
tie
O
i
ib
oh
C is
pr
N
n
tio
bu
IO di
s tri
AT
or
n
tio
U uc
AL
od
pr
re
ed
EV
riz
ho
ut
na
U
EV
U
na
ut
AL
ho
riz
ed
re
U
pr
od
uc AT tio
n
IO

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or
or

distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc.
Copyright © LearningPatterns Inc.
di
s
N

For more information about Java Enterprise Java, or related courseware, please contact us. Our courses
tri

are available globally for license, customization and/or purchase.


bu

C
LearningPatterns. Inc. Services@learningpatterns.com | www.learningpatterns.com
t io

Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA
n
O
212.487.9064 voice and fax
is
pr
PY
Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in
oh

the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns
Inc. All other products referenced herein are trademarks of their respective holders.
ib
itie
d
Table of Contents – Introduction to Spring 5
and Spring MVC/REST
Introduction to Spring 5 and Spring MVC/REST _____________________________ 1
Workshop Overview _______________________________________________________________ 1
Workshop Objectives ______________________________________________________________ 1
EV
Workshop Agenda _________________________________________________________________ 1
Typographic Conventions ___________________________________________________________ 1
U

Labs ____________________________________________________________________________ 1
na

Session 1: Introduction to Spring __________________________________________ 1


ut

Lesson Objectives _________________________________________________________________ 1


AL
ho

Overview __________________________________________________________________ 1
Spring and Enterprise Applications ____________________________________________________ 1
riz

The Spring Modules _______________________________________________________________ 1


The Spring Distribution _____________________________________________________________ 1
ed

The Spring jars ___________________________________________________________________ 1


U
A Word About JUnit _______________________________________________________________ 1
re

JUnit Example ____________________________________________________________________ 1


Lab 1.1: Setting Up the Environment ______________________________________________ 1
pr
AT
Spring Introduction _________________________________________________________ 1
od

Managing Beans: Core Spring Capability _______________________________________________ 1


A Basic Spring Application__________________________________________________________ 1
uc

The JavaTunes Online Store _________________________________________________________ 1


tio

Some JavaTunes Types _____________________________________________________________ 1


IO
XML Configuration Example ________________________________________________________ 1
n

The Spring Container ______________________________________________________________ 1


Instantiating and Using the Container __________________________________________________ 1
or

Why Bother - What do we Gain? _____________________________________________________ 1


Summary: Working With Spring______________________________________________________ 1
di
N
More on ApplicationContext _________________________________________________________ 1
s

Some BeanFactory/ApplicationContext API_____________________________________________ 1


tri

Mini-Lab: Review Javadoc _______________________________________________________ 1


bu

Lab 1.2: Hello Spring World _____________________________________________________ 1


C
Annotation-Based Configuration Example ______________________________________________ 1
t

A Brief Note on Annotations_________________________________________________________ 1


io

Enabling Annotations / Detecting Beans ________________________________________________ 1


n
O
Spring's XML Schemas _____________________________________________________________ 1
Lab 1.3: Spring Annotations______________________________________________________ 1
is

Dependency Injection ________________________________________________________ 1


pr
PY
Dependencies Between Objects_______________________________________________________ 1
oh

Example of a Direct Dependency _____________________________________________________ 1


Dependency Inversion ______________________________________________________________ 1
ib

Dependency Injection (DI) in Spring __________________________________________________ 1


i

Injection with Autowired____________________________________________________________ 1


tie

@Named/@Inject (JSR-330) Example _________________________________________________ 1


Dependency Injection Reduces Coupling _______________________________________________ 1
d

Advantages of Dependency Injection __________________________________________________ 1


Constructor Injection _______________________________________________________________ 1
Setter Injection vs. Constructor Injection _______________________________________________ 1
Qualifying Injection by Name ________________________________________________________ 1

Copyright © LearningPatterns Inc. All rights reserved i


Lab 1.4: Dependency Injection____________________________________________________ 1
Review Questions _________________________________________________________________ 1
Lesson Summary __________________________________________________________________ 1
Lesson Summary __________________________________________________________________ 1
Session 2: Configuration in Depth _________________________________________ 1
Lesson Objectives _________________________________________________________________ 1
Java-based Configuration ____________________________________________________ 1
Java Configuration Overview ________________________________________________________ 1
EV
Using Java-based Configuration ______________________________________________________ 1
Dependency Injection ______________________________________________________________ 2
U

How Does it Work ? _______________________________________________________________ 2


na

Dependencies in Configuration Classes ________________________________________________ 2


Injecting Configuration Classes_______________________________________________________ 2
ut

Other @Bean Capabiliites ___________________________________________________________ 2


AL
ho

Mini-Lab: Review Javadoc _______________________________________________________ 2


Integrating Configuration Types_______________________________________________ 2
riz

XML and @Component Pro / Con ____________________________________________________ 2


ed

Java-based Configuration: Pro / Con___________________________________________________ 2


U
Choosing a Configuration Style ______________________________________________________ 2
Integrating Configuration Metadata ___________________________________________________ 2
re

@Import: @Configuration by @Configuration___________________________________________ 2


pr

<import>: XML by XML ___________________________________________________________ 2


AT
Importing Between XML/@Configuration ______________________________________________ 2
od

Scanning for @Configuration Classes__________________________________________________ 2


Lab Options ______________________________________________________________________ 2
uc

Lab 2.1: Java-based Configuration ________________________________________________ 2


tio

Bean Scope and Lifecycle _____________________________________________________ 2


IO
Bean Scope ______________________________________________________________________ 2
n

Specifying Bean Scope - XML _______________________________________________________ 2


or

Using @Scope to Specify Bean Scope _________________________________________________ 2


Bean Creation/Destruction Lifecycle __________________________________________________ 2
di
N
[Optional] Bean Creation Lifecycle Details _____________________________________________ 2
[Optional] BeanPostProcessor________________________________________________________ 2
s tri

[Optional] Event Handling __________________________________________________________ 2


Lab 2.2: Bean Lifecycle __________________________________________________________ 2
bu

C
Externalizing Properties______________________________________________________ 2
t

Externalizing Values in Properties Files ________________________________________________ 2


io

Accessing Externalized Properties ____________________________________________________ 2


n
O
The Spring Environment ____________________________________________________________ 2
is

SpEL: Spring Expression Language Overview ___________________________________________ 2


Additional SpEL Examples __________________________________________________________ 2
pr

Mini-Lab: Review SpEL Reference ________________________________________________ 2


PY
oh

Profiles ____________________________________________________________________ 2
Profile Overview __________________________________________________________________ 2
ib

The First Configuration _____________________________________________________________ 2


i

Defining Second Configuration_______________________________________________________ 2


tie

Using the Configurations____________________________________________________________ 2


d

Declaring Profiles - @Profile ________________________________________________________ 2


Enabling Profiles __________________________________________________________________ 2
Profiles - XML Configuration ________________________________________________________ 2
Profiles in JUnit tests_______________________________________________________________ 2
Lab 2.3: Profiles________________________________________________________________ 2

Copyright © LearningPatterns Inc. All rights reserved ii


Review Questions _________________________________________________________________ 2
Lesson Summary __________________________________________________________________ 2
Lesson Summary __________________________________________________________________ 2
Session 3: Introduction to Spring Boot______________________________________ 2
Lesson Objectives _________________________________________________________________ 2
maven Overview ____________________________________________________________ 2
About Maven _____________________________________________________________________ 2
How We'll Work With Maven________________________________________________________ 2
EV
Core Maven Concepts ______________________________________________________________ 2
The POM (Project Object Model) _____________________________________________________ 2
U

POM - Required Elements___________________________________________________________ 2


na

POM - External Dependencies _______________________________________________________ 2


Common Maven Artifacts for Spring __________________________________________________ 2
ut

Repositories ______________________________________________________________________ 3
AL
ho

Maven Project Structure ____________________________________________________________ 3


Executing maven Goals _____________________________________________________________ 3
riz

Spring Boot Overview _______________________________________________________ 3


ed

Motivation for Spring Boot __________________________________________________________ 3


U
Spring Boot Project ________________________________________________________________ 3
Goals for Spring Boot Project ________________________________________________________ 3
re

How is Spring Boot Structured? ______________________________________________________ 3


pr

Dependency Management with Spring Boot _____________________________________________ 3


AT
Equivalent POM without Spring Boot__________________________________________________ 3
od

Configuration with Spring Boot ______________________________________________________ 3


Programming with Spring Boot_______________________________________________________ 3
uc

Getting Started____________________________________________________________________ 3
Mini-Lab: Review Boot Reference _________________________________________________ 3
tio
IO
Mini-Lab: Spring Boot - Starter Projects ___________________________________________ 3
n

Spring Boot Hello World _____________________________________________________ 3


or

Our Goals for Hello World __________________________________________________________ 3


POM for Hello World ______________________________________________________________ 3
di
N
spring-boot-starter-parent ___________________________________________________________ 3
spring-boot-starter-parent POM Excerpt ________________________________________________ 3
s tri

spring-boot-dependencies POM Excerpt ________________________________________________ 3


spring-boot-starter _________________________________________________________________ 3
bu

spring-boot-starter POM Excerpt _____________________________________________________ 3


C
Summary ________________________________________________________________________ 3
t io

Mini-Lab: Spring Boot - Brief Review of POMs______________________________________ 3


Hello World Overview _____________________________________________________________ 3
n
O
Hello World Code _________________________________________________________________ 3
is

Output of HelloBootWorld __________________________________________________________ 3


How it Works ____________________________________________________________________ 3
pr
PY
Easy Configuration with Properties____________________________________________________ 3
oh

Executable Jar Packaging ___________________________________________________________ 3


Lab 1.1: Hello Boot World _______________________________________________________ 3
ib

Recap of what we've seen ___________________________________________________________ 3


itie

Session 4: Spring Testing ________________________________________________ 3


Lesson Objectives _________________________________________________________________ 3
d

Testing and JUnit Overview __________________________________________________ 3


Testing Overview _________________________________________________________________ 3
JUnit Overview ___________________________________________________________________ 3
Writing a Test – First Example _______________________________________________________ 3

Copyright © LearningPatterns Inc. All rights reserved iii


Running Tests in the IDE ___________________________________________________________ 3
Running Tests in Other Environments _________________________________________________ 3
Naming Conventions and Organizing Tests _____________________________________________ 3
Positive and Negative Tests__________________________________________________________ 3
Writing Test Methods ______________________________________________________________ 3
Assertions _______________________________________________________________________ 3
Test Fixtures – @Before and @After ________________________________________________ 3
Test Fixtures – Example ____________________________________________________________ 3
Test Fixtures – @BeforeClass and @AfterClass ____________________________________ 3
EV
Order of Execution ________________________________________________________________ 3
[Optional] Lab 4.1: Using JUnit ___________________________________________________ 3
U

Spring TestContext Framework _______________________________________________ 3


na

Spring TestContext Overview ________________________________________________________ 3


Common TestContext Types _________________________________________________________ 3
ut
AL
Using Spring's TestContext __________________________________________________________ 3
ho

Context Management / Caching ______________________________________________________ 3


Using Spring Boot Test _____________________________________________________________ 3
riz

Under the Hood ___________________________________________________________________ 4


Lab 4.2: Using Spring Testing ____________________________________________________ 4
ed

U
Session 5: Database Access With Spring ____________________________________ 4
re

Lesson Objectives _________________________________________________________________ 4


pr

Overview __________________________________________________________________ 4
AT
Data Access Support _______________________________________________________________ 4
od

Datasources ______________________________________________________________________ 4
Example: Configuring a DataSource ___________________________________________________ 4
uc

Example: JNDI Lookup of a DataSource _______________________________________________ 4


Properties Files ___________________________________________________________________ 4
tio
IO
XML vs Java Config vs Properties Files ________________________________________________ 4
n

[Optional] Using Spring with Hibernate_________________________________________ 4


or

Hibernate Overview________________________________________________________________ 4
Hibernate Configuration File Illustration _______________________________________________ 4
di
N
Using Hibernate Directly____________________________________________________________ 4
Spring Support for Hibernate ________________________________________________________ 4
s tri

LocalSessionFactoryBean ___________________________________________________________ 4
Configuring a Hibernate Session Factory _______________________________________________ 4
bu

Contextual Sessions________________________________________________________________ 4
C
Spring Free Repository Class ________________________________________________________ 4
t io

Injecting the SessionFactory _________________________________________________________ 4


n
O
[Optional] Using Spring with JPA _____________________________________________ 4
is

JPA Overview and Architecture ______________________________________________________ 4


JPA Architecture – Key Types _______________________________________________________ 4
pr

JPA: Entity Class__________________________________________________________________ 4


PY
JPA: Persistence Unit Configuration ___________________________________________________ 4
oh

JPA: EntityManager _______________________________________________________________ 4


Spring Support for JPA _____________________________________________________________ 4
ib

Managing the EntityManager[Factory] _________________________________________________ 4


itie

1. JEE: Obtaining an EMF From JNDI _________________________________________________ 4


2. LocalContainerEntityManagerFactoryBean ___________________________________________ 4
d

Spring/JPA Integration Configuration __________________________________________________ 4


Example: XML Configuration________________________________________________________ 4
Example: @Configuration___________________________________________________________ 4
3. LocalEntityManagerFactoryBean ___________________________________________________ 4
JPA Repository / DAO _____________________________________________________________ 4

Copyright © LearningPatterns Inc. All rights reserved iv


Extended Persistence Context ________________________________________________________ 4
[Optional] Lab 5.1: Integrating Spring and JPA _____________________________________ 4
Spring Data Overview _______________________________________________________ 4
Why do We Need Spring Data _______________________________________________________ 4
Spring Data Goals _________________________________________________________________ 4
Spring Data Project ________________________________________________________________ 4
Spring Data Modules_______________________________________________________________ 4
POM for Using Spring Data JPA______________________________________________________ 4
EV
Using Spring Data___________________________________________________________ 4
How is Spring Data (JPA) Structured? _________________________________________________ 4
U

CrudRepository/JpaRepository Methods________________________________________________ 4
na

A Simple Event Entity______________________________________________________________ 4


The Event Repository Type__________________________________________________________ 4
ut

Structure of our Repository __________________________________________________________ 4


AL
ho

Using the Repository _______________________________________________________________ 4


Using Other CrudRepository Methods _________________________________________________ 4
riz

Lab 5.2: Using Spring Data ______________________________________________________ 4


Defining Queries Using Naming Conventions ___________________________________________ 4
ed

More About Generated Queries_______________________________________________________ 4


U
More Complex Queries _____________________________________________________________ 4
Configuring Results________________________________________________________________ 5
re

Defining Queries with JPQL _________________________________________________________ 5


pr
AT
Lab 5.3: Writing Query Methods__________________________________________________ 5
Review Questions _________________________________________________________________ 5
od

Lesson Summary __________________________________________________________________ 5


uc

Lesson Summary __________________________________________________________________ 5


Session 6: Transactions __________________________________________________ 5
tio
IO
Lesson Objectives _________________________________________________________________ 5
n

Spring Transaction Management ______________________________________________ 5


or

General Transaction (TX) Overview ___________________________________________________ 5


General Transaction Lifecycle________________________________________________________ 5
di
N
Spring's Transaction Managers _______________________________________________________ 5
Configuring Transaction Managers ____________________________________________________ 5
s tri

Spring's JTA Transaction Manager ____________________________________________________ 5


Spring Declarative TX Management ___________________________________________________ 5
bu

Spring Transactional Scope __________________________________________________________ 5


C
Transaction Propagation ____________________________________________________________ 5
t io

Transaction Attributes for Propagation _________________________________________________ 5


MANDATORY ___________________________________________________________________ 5
n
O
NESTED ________________________________________________________________________ 5
is

NEVER _________________________________________________________________________ 5
NOT_SUPPORTED _______________________________________________________________ 5
pr
PY
REQUIRED______________________________________________________________________ 5
oh

REQUIRES_NEW ________________________________________________________________ 5
SUPPORTS ______________________________________________________________________ 5
ib

Mini-Lab: Transaction Example __________________________________________________ 5


Transaction Attributes - Some Choices _____________________________________________ 5
itie

Transaction Attributes - Some Choices _____________________________________________ 5


d

@Transactional Configuration ________________________________________________ 5


@Transactional Declarative Transactions _______________________________________________ 5
Additional Transactional Attributes ___________________________________________________ 5
Example: Specifying Transaction Attributes_____________________________________________ 5
Transactional Attributes Guidelines ___________________________________________________ 5

Copyright © LearningPatterns Inc. All rights reserved v


Rolling Back and Exceptions ________________________________________________________ 5
Spring Data JPA and Transactions ____________________________________________________ 5
Aspect Oriented Programming (AOP) Defined___________________________________________ 5
Aspect Oriented Programming Illustrated _______________________________________________ 5
Spring TX and AOP _______________________________________________________________ 5
Example – Invoking Directly ________________________________________________________ 5
Example – Invoking Directly ________________________________________________________ 5
@Transactional Pros and Cons _______________________________________________________ 5
Lab 6.1: Spring Transactions _____________________________________________________ 5
EV
[Optional] Pointcut-based Configuration ________________________________________ 5
U

Spring Transactions and AOP ________________________________________________________ 5


Defining a Pointcut ________________________________________________________________ 5
na

Defining a Pointcut - XML __________________________________________________________ 5


Specifying Transactions Using XML __________________________________________________ 5
ut
AL
Specifying Transactions Using XML __________________________________________________ 5
ho

Linking Advice With Pointcuts _______________________________________________________ 5


Resulting Behavioc ________________________________________________________________ 5
riz

<tx:method> Attributes _____________________________________________________________ 5


Using Markers for Pointcuts _________________________________________________________ 5
ed

Using a Marker Interface____________________________________________________________ 5


U
Using Marker Annotations __________________________________________________________ 5
re

Why Use Pointcut-based Configuration ________________________________________________ 5


More About Pointcut Expressions _____________________________________________________ 5
pr
AT
Sample execution Designator Patterns _________________________________________________ 6
od

Sample execution Designator Patterns _________________________________________________ 6


Other Spring AOP Designators _______________________________________________________ 6
uc

Sample Designator Patterns__________________________________________________________ 6


[Demo] Lab 6.2: Pointcut-Based TX _______________________________________________ 6
tio

Review Questions _________________________________________________________________ 6


IO
Lesson Summary __________________________________________________________________ 6
n

Session 7: Web Applications and Spring MVC _______________________________ 6


or

Lesson Objectives _________________________________________________________________ 6


di
N
Integration with Java EE _____________________________________________________ 6
s

Spring and Java Enterprise Edition (JEE) _______________________________________________ 6


tri

Overview of JEE Web Applications ___________________________________________________ 6


bu

Web Application Structure __________________________________________________________ 6


C
Web Application Components________________________________________________________ 6
t

ApplicationContext and Java Web Apps ________________________________________________ 6


io

Configuring ContextLoaderListener - XML _____________________________________________ 6


n

ContextLoaderListener - @Configuration_______________________________________________ 6
O
Using the Application Context _______________________________________________________ 6
is

Lab 7.1: Spring and the Web _____________________________________________________ 6


pr
PY
Spring MVC Basics__________________________________________________________ 6
oh

What is Spring MVC? ______________________________________________________________ 6


General MVC Architecture __________________________________________________________ 6
ib

MVC Pattern flow _________________________________________________________________ 6


Spring MVC Architecture ___________________________________________________________ 6
itie

Plain Servlets/JSP Request Flow ______________________________________________________ 6


Spring MVC Request Flow __________________________________________________________ 6
d

DispatcherServlet Initialization _______________________________________________________ 6


DispatcherServlet - Java Config ______________________________________________________ 6
Spring MVC Configuration - Java Config_______________________________________________ 6
DispatcherServlet - web.xml Config ___________________________________________________ 6

Copyright © LearningPatterns Inc. All rights reserved vi


Spring MVC Configuration - XML Config______________________________________________ 6
Mini-Lab: DispatcherServlet Reference ____________________________________________ 6
Controllers _______________________________________________________________________ 6
A Very Simple Controller ___________________________________________________________ 6
Logon Control Flow _______________________________________________________________ 6
@RequestMapping Defines Controllers ________________________________________________ 6
Handler Methods __________________________________________________________________ 6
Mini-Lab: Controller Reference __________________________________________________ 6
Lab 7.2: Spring MVC Basics _____________________________________________________ 6
EV
View Resolvers _____________________________________________________________ 6
U

View Resolvers ___________________________________________________________________ 6


View Resolvers - Java Config ________________________________________________________ 6
na

Example: View Resolvers - Java Config ________________________________________________ 6


Java Config Simplified Configuration__________________________________________________ 6
ut
AL
Controller Using Logical Names ______________________________________________________ 6
ho

New Control Flow _________________________________________________________________ 6


Other View Resolvers ______________________________________________________________ 6
riz

Configuring ResourceBundleViewResolver _____________________________________________ 6


Properties File - ResourceBundleViewResolver __________________________________________ 6
ed

Mapping DispatcherServlet to / _______________________________________________________ 6


U
Controller Handling /_______________________________________________________________ 6
re

Lab 7.3: View Resolvers _________________________________________________________ 6


pr
AT
Controller Details ___________________________________________________________ 6
Request Parameters and Model Data ___________________________________________________ 6
od

Sample Input Pages ________________________________________________________________ 6


uc

@RequestParam – Parameter Binding _________________________________________________ 6


Returning Model Data ______________________________________________________________ 7
tio

Class ModelAndView ______________________________________________________________ 7


IO
Returning ModelAndView Example ___________________________________________________ 7
n

Model Argument Example __________________________________________________________ 7


Other Handler Method Capabilities____________________________________________________ 7
or

Example – Other Handler Capabilities _________________________________________________ 7


Lab 7.4: Client Input / Model Data ________________________________________________ 7
di
N
Review Questions _________________________________________________________________ 7
s

Lesson Summary __________________________________________________________________ 7


tri

Lesson Summary __________________________________________________________________ 7


bu

Session 8: More Spring MVC Capabilities ___________________________________ 7


t
C
Lesson Objectives _________________________________________________________________ 7
io

Forms and Model Objects ____________________________________________________ 7


n
O
Model Classes ____________________________________________________________________ 7
is

@ModelAttribute__________________________________________________________________ 7
Spring MVC Form Tags <form:form> _________________________________________________ 7
pr
PY
Spring MVC Form Tags <form:input> _________________________________________________ 7
oh

Controller Data Binding - @ModelAttribute_____________________________________________ 7


Request Handling Flow _____________________________________________________________ 7
ib

@ModelAttribute on Methods________________________________________________________ 7
Using Reference Data ______________________________________________________________ 7
itie

Lab 8.1: Forms and Model Objects ________________________________________________ 7


d

Working with Sessions _______________________________________________________ 7


Storing Model Objects in the Session __________________________________________________ 7
Using Model Objects in the Session ___________________________________________________ 7
SessionStatus - Clearing the Session ___________________________________________________ 7
Obtaining a Session Object __________________________________________________________ 7

Copyright © LearningPatterns Inc. All rights reserved vii


Lab 8.2: Working with Sessions ___________________________________________________ 7
Validation _________________________________________________________________ 7
Validation Overview _______________________________________________________________ 7
Validation Constraints ______________________________________________________________ 7
Validation Usage __________________________________________________________________ 7
Manual Validation Configuration _____________________________________________________ 7
Programmatic Validation____________________________________________________________ 7
Review Questions _________________________________________________________________ 7
EV
Lesson Summary __________________________________________________________________ 7
Session 9: RESTful Services with Spring ____________________________________ 7
U

Lesson Objectives _________________________________________________________________ 7


na

REST Overview and Principles ________________________________________________ 7


ut

Our Domain Model ________________________________________________________________ 7


AL
REST – Representational State Transfer ________________________________________________ 7
ho

REST Characteristics_______________________________________________________________ 7
REST Resources and Operations______________________________________________________ 7
riz

REST in the Real World ____________________________________________________________ 7


ed

REST Principles __________________________________________________________________ 7


U
REST Principles __________________________________________________________________ 7
re

Requests and Responses ______________________________________________________ 7


REST APIs ______________________________________________________________________ 7
pr
AT
URI Templates____________________________________________________________________ 7
od

REST API with URI Template _______________________________________________________ 7


GET – Retrieve All Items ____________________________________________________________ 7
uc

GET – Retrieve Specific Item_________________________________________________________ 7


POST – Create New Item ____________________________________________________________ 7
tio
IO
PUT – Update Existing Item _________________________________________________________ 7
DELETE – Delete Existing Item _______________________________________________________ 7
n

Some Additional Points _____________________________________________________________ 7


or

Summary of REST Characteristics ____________________________________________________ 8


REST in Action – Mini-Lab ______________________________________________________ 8
di
N
REST with Spring MVC _____________________________________________________ 8
s tri

Spring Support for REST ___________________________________________________________ 8


A Simple Resource Class Example ____________________________________________________ 8
bu

URI Templates and @PathVariable ___________________________________________________ 8


C
Generating a Response - @ResponseBody ______________________________________________ 8
t io

@ResponseBody Example __________________________________________________________ 8


Other URI Path Mapping Capabilities__________________________________________________ 8
n
O
@RestController __________________________________________________________________ 8
is

But How Does It Work? ____________________________________________________________ 8


Accessing REST Resources__________________________________________________________ 8
pr
PY
Lab 9.1: A Simple REST Resource ________________________________________________ 8
oh

Ajax Overview______________________________________________________________ 8
Ajax-JavaScript and REST Resources__________________________________________________ 8
ib

Classic User Interaction – Synchronous ________________________________________________ 8


itie

Ajax User Interaction – Asynchronous _________________________________________________ 8


Working with Ajax-JavaScript _______________________________________________________ 8
d

Ajax and REST Resources __________________________________________________________ 8


Lab 9.2: Use Ajax in a Client _____________________________________________________ 8
Review Questions _________________________________________________________________ 8
Lesson Summary __________________________________________________________________ 8

Copyright © LearningPatterns Inc. All rights reserved viii


Session 10: Working with JSON and XML __________________________________ 8
Generating JSON ___________________________________________________________ 8
JSON Overview___________________________________________________________________ 8
JSON Details _____________________________________________________________________ 8
Arrays and More Complex Objects ____________________________________________________ 8
JSON Representations for REST Resources _____________________________________________ 8
Http Message Converters / JSON _____________________________________________________ 8
Summary: JSON Serialization Requirements ____________________________________________ 8
EV
Lab 10.1: A JSON Resource ______________________________________________________ 8
Generating XML____________________________________________________________ 8
U

XML Review _____________________________________________________________________ 8


na

Introducing JAXB _________________________________________________________________ 8


@XmlRootElement and Default Mapping ______________________________________________ 8
ut
AL
Default JAXB Mapping – Example____________________________________________________ 8
ho

Serializing Data to XML ____________________________________________________________ 8


Using @XmlRootElement___________________________________________________________ 8
riz

Serializing Collections to XML_______________________________________________________ 8


Summary: XML Serialization Requirements ____________________________________________ 8
ed

U
Content Negotiation _________________________________________________________ 8
Content Negotiation Overview _______________________________________________________ 8
re

Accept Headers: What the Client Asks For ______________________________________________ 8


pr
AT
Determining Client's Data Format _____________________________________________________ 8
Configuring Controller's Data Types___________________________________________________ 8
od

Lab 10.2: An XML Resource _____________________________________________________ 8


Review Questions _________________________________________________________________ 8
uc

Lesson Summary __________________________________________________________________ 8


tio

Session 11: Java Clients for RESTful Services _______________________________ 8


IO
REST Client Requirements __________________________________________________________ 8
n

RestTemplate Example _____________________________________________________________ 8


or

Common RestTemplate Methods _____________________________________________________ 8


getForObject() in Detail_____________________________________________________________ 8
di
N
RestTemplate Method Variations _____________________________________________________ 8
s

getForObject() Using Map___________________________________________________________ 8


tri

Other RestTemplate Method Details ___________________________________________________ 8


Lab 11.1: A Client Using RestTemplate ____________________________________________ 9
bu

RestTemplate.getForEntity() _________________________________________________________ 9
C
Using HttpEntity and ResponseEntity __________________________________________________ 9
t io

Accessing Headers_________________________________________________________________ 9
n

RestTemplate.exchange() ___________________________________________________________ 9
O
Setting Headers on a Request ________________________________________________________ 9
is

Error Handling____________________________________________________________________ 9
Summary of RestTemplate Usage _____________________________________________________ 9
pr
PY
Lab 11.2: [Optional] Setting / Accessing Headers_____________________________________ 9
oh

Lesson Summary __________________________________________________________________ 9


ib

Session 12: Common REST Patterns _______________________________________ 9


The REST Methods ________________________________________________________________ 9
itie

GET: Retrieve Information __________________________________________________________ 9


POST: Add New Information ________________________________________________________ 9
d

Server: POST Controller - Details_____________________________________________________ 9


Server: Setting Location Header for POST ______________________________________________ 9
Client: RestTemplate for POST_______________________________________________________ 9
PUT: Update Information ___________________________________________________________ 9

Copyright © LearningPatterns Inc. All rights reserved ix


Client: RestTemplate for PUT ________________________________________________________ 9
DELETE: Remove an Entity _________________________________________________________ 9
Client: RestTemplate for DELETE ____________________________________________________ 9
[Optional] Lab 12.1: Additional REST Operations ___________________________________ 9
[Optional] Session 13: Additional New Features ______________________________ 9
Core Updates _______________________________________________________________ 9
Specification Baselines _____________________________________________________________ 9
Lambdas for Bean Registration _______________________________________________________ 9
EV
Default Interface Methods ___________________________________________________________ 9
Candidate Component Index _________________________________________________________ 9
U

@Nullable and @NonNull __________________________________________________________ 9


na

WebFlux (Reactive Systems) __________________________________________________ 9


ut

Reactive Programming Overview _____________________________________________________ 9


AL
Iterator (Pull) - Synchronous _________________________________________________________ 9
ho

Observer (Push) - Asynchronous______________________________________________________ 9


Reactive Programming - Observer+ ___________________________________________________ 9
riz

Spring Reactor / WebFlux Frameworks ________________________________________________ 9


ed

Note: Java 8 Lambda/Stream Usage ___________________________________________________ 9


U
WebFLux API and REST Example____________________________________________________ 9
Example: Reactive Resource _________________________________________________________ 9
re

Example: Reactive Client (Flux) ______________________________________________________ 9


pr

Example: Reactive Client (Mono) _____________________________________________________ 9


AT
Recap ___________________________________________________________________________ 9
od

[Optional] Lab 13.1: WebFlux Demo_______________________________________________ 9


uc

[Optional] Session 14: XML Specific Configuration ___________________________ 9


Lesson Objectives _________________________________________________________________ 9
tio

Collection Valued Properties_________________________________________________________ 9


IO
Working with Collections ___________________________________________________________ 9
n

Collection Property Example_________________________________________________________ 9


or

Configuring <list> and <set> Properties ________________________________________________ 9


Configuring Collection of Bean References _____________________________________________ 9
di
N
Map Valued Properties _____________________________________________________________ 9
s

Other Capabililties_________________________________________________________________ 9
tri

Bean Definition Inheritance__________________________________________________________ 9


Inheritance Example _______________________________________________________________ 9
bu

Factory Classes ___________________________________________________________________ 9


C
Instance Factory Methods ___________________________________________________________ 9
t io

Autowiring with XML______________________________________________________________ 9


n

Inner Beans _____________________________________________________________________ 10


O
Compound Names ________________________________________________________________ 10
is

Recap _______________________________________________________________ 10
pr

Recap of what we've done __________________________________________________________ 10


PY
oh

What Else is There________________________________________________________________ 10


Resources_______________________________________________________________________ 10
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved x


Introduction to Spring 5 and Spring MVC/REST Introduction
EV
U
na

Introduction to Spring 5 and


ut

Spring MVC/REST
AL
ho
riz
ed
re
prU
od
uc AT

Version: 20180521-b
tio
n
IO

Notes:
or

Version: 20180521-b
di
N
‹
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 1


Introduction to Spring 5 and Spring MVC/REST Introduction

Workshop Overview
‹ An in-depth course teaching the use of Spring 5 to build
enterprise applications using Java
– Including newer areas of Spring/Java technology
EV
‹ The course covers the following areas of Spring technology
U
na

– Core features of Spring


ut
AL
– Spring Boot
ho

– Data Access Features Including Spring Data


riz
ed

– Transaction Support
re
U

– Web Application Support including Spring MVC


pr
AT
– Building RESTful Resources with Spring MVC
od
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 2


Introduction to Spring 5 and Spring MVC/REST Introduction

Workshop Objectives
‹ Understand the Spring framework and use its capabilities, including:

‹ Spring Core: Dependency Injection (DI) and bean lifecycle management


– Spring configuration and API for writing Spring programs
EV
– XML, Java-based, and annotation-based config
U

‹ Spring Boot: For easier dependency management and configuration


na

‹ Data Access: Data access via Spring's data support


ut
AL
– DataSource support
ho

– Hibernate and JPA-based Repositories/DAOs


riz

– Spring Data based repositories


ed

U
‹ Transactions: Controlling transactions declaratively with Spring
re

– Via both Spring annotations and XML configuration


pr
AT
‹ Web: Integrating Spring with Web applications. Understand and use
od

Spring MVC/REST
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 3


Introduction to Spring 5 and Spring MVC/REST Introduction

Workshop Agenda
‹ Session 1: Introduction to Spring ‹ Session 9: RESTful Services with
Spring
‹ Session 2: Configuration in Depth
‹ Session 10: Working with JSON and
‹ Session 3: Intro to Spring Boot
EV
XML
‹ Session 4: Spring Testing
U

‹ Session 11: Java Clients for


na

‹ Session 5: Database Access With


RESTful Services
Spring
ut
AL
Session 12: Common REST Patterns
ho

‹
‹ Session 6: Transactions
riz

‹ [Optional] Session 13: Additional


‹ Session 7: Web Applications and
New Features
ed

Spring MVC
U
[Optional] Session 14: XML Specific
re

‹
‹ Session 8: More Spring MVC
Configuration
pr
AT
Capabilities
od
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 4


Introduction to Spring 5 and Spring MVC/REST Introduction

Typographic Conventions
‹ Code in the text uses a fixed-width code font, e.g.:
Catalog catalog = new CatalogImpl()

–Code fragments are the same, e.g. catalog.speakTruth()


EV
U

–We bold/color text for emphasis


na

–Filenames are in italics, e.g. Catalog.java


ut
AL
ho

–Notes are indicated with a superscript number (1) or a star *


riz

–Longer code examples appear in a separate code box - e.g.


ed

U
package com.javatunes.teach;
re
pr
AT
public class CatalogImpl implements Catalog {
od

public void speakTruth() {


System.out.println("BeanFactories are way cool");
uc

}
}
tio
n
IO

Notes:
or

(1)
If we had additional information about a particular item in the slide, it would appear here in the notes.
di
s
N
tri

‹We might also put related information that generally pertains to the material covered in the slide.
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 5


Introduction to Spring 5 and Spring MVC/REST Introduction

Labs Lab

‹ The workshop has numerous hands-on lab exercises,


structured as a series of brief labs
– Many follow a common fictional case study called JavaTunes
• An online music store
EV

– The lab details are separate from the main manual pages
U
na
ut

‹ Setup zip files are provided with skeleton code for the labs
AL
ho

– Students add code focused on the topic they're working with


riz

– There is a solution zip with completed lab code


ed
re
U

‹ Lab slides have an icon like in the upper right corner of this
pr
AT
slide
od

– The end of a lab is marked with a stop like this one: STOP
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 6


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Session 1: Introduction to Spring


ut
AL
ho
riz

Overview
ed

U
Spring Introduction
re

Dependency Injection
pr
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 7


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Lesson Objectives
‹ Understand why we need the Spring Framework

‹ Understand what Spring does, and how it simplifies enterprise


EV
application development
U
na

‹ Learn how Spring uses configuration information and


ut
AL
Dependency Injection (DI)
ho

– To manage the beans (objects) in an application


riz

– To manage bean dependencies


ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 8


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Overview
ut
AL
ho
riz

Overview
ed

U
Spring Introduction
re

The Spring Container


pr
AT
Dependency Injection
od
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 9


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Spring and Enterprise Applications


‹ Enterprise apps have complex requirements, including
– Many application types and dependencies
– Persistent data and transactions
– Remote clients (REST, Web Service, others)
EV

Spring: Lightweight framework to build enterprise apps


U

‹
na

– Non-intrusive, use only what you need, supports advanced capabilities


ut
AL
‹ Capabilities include:
ho

– Dependency Injection (Inversion of Control/IOC) to manage bean


riz

dependencies
ed

– DAO/Repository/Transaction support for persistent data


U

– ORM support (Object-relational mapping, e.g. JPA)


re
pr

– AOP: Aspect-oriented programming


od
AT

– Web: Integration with standard JEE Web apps


– Spring MVC: Model-View-Controller Web framework
uc

– Security: Authentication and authorization


tio
n
IO

Notes:
or

There really is no formal definition of an enterprise application.


di
N
‹
s

‹ Typically though, some of the characteristics they have are:


tri

– Used in a business environment, often in business-critical domains.


bu

C
– Have some form of persistent storage.
t io

– Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc).
n
O
– Require some measure of scalability and fault tolerance.
is

‹ The definition of enterprise application is not important.


pr
PY
– Many Java applications share some of the requirements that we are outlining here.
oh
ib

‹ DAO: Data Access Object.


i tie
d

‹ The Spring ecosystem is now very large.


– There are other capabilities that we don't list and won't cover in this course.
– We'll cover some of the more central technologies that many of the others rely on.

Copyright © LearningPatterns Inc. All rights reserved. 10


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

The Spring Modules


EV
U
na
ut
AL
ho
riz
ed
re
prU
od
uc AT tio
n
IO

Notes:
or

Module diagram from the Spring Reference Documentation


di
N
‹
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 11


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

The Spring Distribution


‹ Spring home page: http://spring.io/

‹ Distributed as modules in separate jars


– e.g. spring-beans-5.0.5.RELEASE.jar
EV
– Has external dependencies - e.g. logging, JUnit, etc. (1)
U

– Generally use a tool like maven for dependencies


na

• We supply jars the jars for some labs, and use maven in others
ut
AL
ho

‹ Spring vs. JEE (Java Enterprise Edition) (2)


riz

– JEE similarly supports enterprise apps


ed

• e.g. CDI for lifecycle / dependency injection


U

– Which to use? What works best


re

• Based on your current and future system needs


pr
AT

– You might use both - e.g. a JEE Web container


od

• With Spring for lifecycle management and DI


uc

• Or Spring MVC layered on top of JEE Servlets/JSP


tio
n
IO

Notes:
or

In earlier releases (up to Spring 3), both the Spring distribution and its dependencies were available as
di
N
‹
a separate download from the Spring download pages.
s tri

– These are no longer provided.


bu

– It is assumed that you'll use a build tool like maven to get the Spring libraries and its
C
dependencies.
t io
n
O
(1)
The external dependencies for the core modules for dependency injection are (purposely) minimal.
is

– Basically you just have a logging framework.


pr
PY
– For other capabilities (e.g. AOP) there are more dependencies, but they're still rather small.
oh

– If you use other technologies however, e.g. Hibernate/JPA, then there are more external
ib

dependencies .
i tie
d

(2)
Modern releases of Java/JEE offer many of the core capabilities of Spring.
– However, it is not productive to try to compare them in an absolute sense.
– Usually there are many constraints and requirements guiding your choice of technology.
– We'll present Spring's capabilities, strengths, and weaknesses, to support your decision making.

Copyright © LearningPatterns Inc. All rights reserved. 12


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

The Spring jars


‹ At right, are the Spring libraries we
supply for the early labs (1)
– They are a subset of Spring
– Later labs, which need more jars,
EV
use maven for dependencies
U
na
ut
AL
ho
riz
ed

U
‹ These are external dependencies (2)
re

– Again, just a subset of what we'll


pr
AT
need in later labs
od
uc
tio
n
IO

Notes:
or

(1)
We supply the Spring project jars needed for the early labs in the lab setup.
di
s
N

– We downloaded these using maven and a pom.xml specifying the different modules available in
tri

Spring (e.g. spring-context) then gathered the jars together for the lab setup.
bu

– The dependencies were done in the same way.


t
C

– Note that the actual jars in the lab setup may vary from this illustration - look at the setup to see
io

what is actually used.


n
O
– Note that the junit and hamcrest jars are not needed by Spring, but needed because we use JUnit
is

in our labs.
pr
PY
(2)
You can see that there are not a large number of external dependencies for the basic Spring
oh

functionality.
ib

– You'll see when we do later, more complex, labs, that maven will include/download quite a few
i tie

additional dependencies.
d

Copyright © LearningPatterns Inc. All rights reserved. 13


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

A Word About JUnit


‹ JUnit: Open source Java testing framework
– Often used in examples and labs to test our work
– Labs also create console output - that's not standard (see notes)
EV
‹ JUnit capabilities include:
U

– Annotations for declaring test methods (e.g. @Test)


na

– Assertions for testing expected results


ut
AL
– Test fixtures for sharing common data
ho

– Test runners for running tests


riz
ed

‹ See next slide for an example


re
U

– We'll review in more depth in the Testing session


pr
AT

Most development environments have JUnit support


od

– We'll use them to run tests which drive the lab code
uc

– The tests are the @Test annotated methods (see next slide)
tio
n
IO

Notes:
or

We are using JUnit to drive our slide examples and lab code because it's convenient.
di
N
‹
s

– And also because it gives an easy way to test lab results.


tri

– However, since this is a class for learning new things, we often want some console indication of
bu

what's going on, so we'll produce some console output in our test classes.
t
C

– That's not usually done in test classes written explicitly for testing, but it's good for our purposes.
io
n

– We don't need to adhere to any particular testing practices - our test cases are lab-oriented, not
O
for system testing.
is

– Where appropriate, we do adhere to standard conventions - e.g. in naming our test classes and
pr
PY
test methods.
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 14


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

JUnit Example
‹ To write a JUnit test, we:
– Create a class, one or more methods annotated with @Test
– Make assertions using static methods in org.junit.Assert (e.g.
assertTrue)
EV

‹ Note the @Test on testContextNotNullPositive()


U

– The test creates the application context, and checks that it's non-null
na

– We use org.junit.Assert.assertNotNull to perform the test


ut
AL
– See notes about import static and assertTrue usage
ho
riz

// JUnit relevant code shown - some imports / code omitted


import static org.junit.Assert.*;
ed

import org.junit.Test;
U
public class SpringTests {
re

@Test
pr
AT
public void testContextNotNullPositive() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
od

// Just an example - we'd probably never test that the new operator works
assertNotNull("spring container should not be null", ctx);
uc

}
tio

}
n
IO

Notes:
or

The assertXXX methods are all static method of Assert.


di
N
‹
s

– The familiar way to use these methods would be to import org.junit.Assert, and then call
tri

the static methods through the Assert class.


bu

Assert.assertTrue(collection.isEmpty());
t
C

– This is a little cumbersome, so the static import feature of Java is used - which imports static
io

members from a class.


n
O
– The following import statement imports all the static members (including methods) from the
is

Assert class.
pr
PY
import static org.junit.Assert.*;
oh

– This allows us to use the static members without qualifying them by the classname, as seen in
ib

our earlier code.


i tie

assertTrue(collection.isEmpty());
There is much more capability in JUnit.
d

– We won't go into that, since it's beyond the scope of the course.
– We only cover enough to show how the labs work.
– The course is also NOT meant to teach JUnit or JUnit best practices.

Copyright © LearningPatterns Inc. All rights reserved. 15


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Lab 1.1: Setting Up the Environment


ut
AL
ho
riz

In this lab you'll set up the lab environment, boot the


ed

Spring container, and test it with a unit test


re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 16


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Spring Introduction
ut
AL
ho
riz

Overview
ed

U
Spring Introduction
re

Dependency Injection
pr
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 17


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Managing Beans: Core Spring Capability


‹ Beans: Fancy name for application objects
– They're POJOs (Plain Old Java Objects)
EV
‹ The Spring container is the "manager"
U

– Uses configuration information (metadata) to define,


na

instantiate, configure, and assemble beans


ut

• Metadata: Information about your beans (e.g. bean definitions)


AL
ho

– Container uses the configuration to create and manage beans (1)


riz
ed

Configuration choices include XML and annotations


U
‹
re

– XML: The "classic" configuration from early Spring


pr
AT
– Two annotation choices (@Component, @Configuration)
od

– We'll cover all of these


uc
tio
n
IO

Notes:
or

The term bean doesn't mean that much - it's a common name (e.g. JavaBeans and EJB).
di
N
‹
s

– Here, we use it to mean an object managed by the Spring container.


tri

‹ Spring Container: Software environment to manage beans and other capabilities.


bu

C
– Also called the Dependency Injection (DI) or Inversion of Control (IoC) container.
t io

– Programming to Spring basically means interacting with this software environment.


n
O
(1)
Spring will create and initialize bean instances based on your configuration data.
is

– You can then request those instances from the Spring container by type or name.
pr
PY
– We'll see how this works soon.
oh

‹ Configuration metadata can also be provided in the Java properties format, or even provided
ib

programmatically (using Spring's public API).


i tie

– These are generally more cumbersome to use, and we won't cover them in this course.
– In fact, the Spring IoC container is totally decoupled from the external form of the metadata.
d

– It has its own internal format which it uses to store this information.
– The XML format was the original one, and is still in use today, but there are now other, more
sophisticated, ways to configure the container.

Copyright © LearningPatterns Inc. All rights reserved. 18


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

A Basic Spring Application


EV
U
na
ut
AL
ho
riz
ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 19


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

The JavaTunes Online Store


‹ The course uses JavaTunes as an example and lab domain
– A simple online music store (1)
‹ Some of the types you'll see include:
EV

– com.javatunes.domain.MusicItem : JavaBean-style value class


U
na

representing a music item (e.g. an mp3)


ut

– com.javatunes.service.Catalog : Interface defining JavaTunes


AL
ho

catalog functionality (including search)


riz

– com.javatunes.service.CatalogImpl : Concrete Catalog


ed

implementation (uses ItemRepository)


re
U

– com.javatunes.persistence.ItemRepository : Interface defining


pr
AT
data access API for items
od

– com.javatunes.persistence.InMemoryItemRepository :
uc

Concrete ItemRepository implementation (simple in-memory storage)


tio
n
IO

Notes:
or

(1)
We use a simple online music store as our domain for examples in the slides and for the labs.
di
s
N

– We've tried to give it enough detail to provide good material to work with while keeping it
tri

simple enough so you don't have to spend too much time in figuring it out.
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 20


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Some JavaTunes Types


‹ Catalog and CatalogImpl are shown below
– Note how CatalogImpl implements the Catalog interface (1)
‹ Let's look at how to configure some objects
EV
package com.javatunes.service;
U
na

public interface Catalog {


public MusicItem findById (long id);
ut

public Collection<MusicItem> findByKeyword(String keyword);


AL
ho

public long size();


}
riz

package com.javatunes.service;
ed

U
public class CatalogImpl implements Catalog { // Detail omitted
re
pr
AT
public MusicItem findById (long id) { /* */ }
od

public Collection<MusicItem> findByKeyword(String keyword)


{ /* */ }
uc

public long size() { /* */ }


}
tio
n
IO

Notes:
or

These two types are part of JavaTunes.


di
N
‹
s

– We'll use them to motivate our discussion on how Spring works.


tri
bu

C
(1)
Programming to interfaces provides many advantages by decoupling your code from concrete
t

implementation classes.
io
n

– This is not a concept unique to Spring.


is
O

– Many design patterns are based on the decoupling gained by programming to an interface.
pr

– We'll soon see how the Spring framework makes these advantages even more usable and
PY
powerful by helping manage the dependencies that have been abstracted using interfaces.
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 21


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

XML Configuration Example


‹ Spring can be configured in an XML file
– Default config file: applicationContext.xml, but can be anything (1)
– General structure: Top level <beans> containing <bean> elements
• Each <bean> defines a bean
EV
• Generally specify id (a name) and class (fully qualified class name) (2)
U

– Supports other configuration also - we'll cover it as we encounter it


na

‹ At bottom, we define one bean with XML (the metadata)


ut
AL
Many existing applications use XML
ho

– But annotation-based approaches now recommended


riz
ed

<?xml version="1.0" encoding="UTF-8"?>


re
U

<!-- The beans namespace is the default one for the document -->
<beans xmlns="http://www.springframework.org/schema/beans"
pr
AT
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
od

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
uc

<bean id="musicCatalog" class="com.javatunes.service.CatalogImpl"/>


tio

</beans>
n
IO

Notes:
or

(1)
applicationContext.xml is a standard (and default) name for the Spring config file, but you can name it
di
N
anything that you want.
s tri

– In fact, as we'll see, you can have multiple config files.


bu

(2)
There are more sophisticated ways to create beans, for example with a factory class (shown later), in
C
which case the class name may not be the actual implementation class.
t io

Spring provides an XML Schema for this configuration file, and the examples and lab setup files have
n

‹
O
the necessary XML namespace information in them to refer to this schema.
is

– This is standard XML usage, and we don't go into the details here of how to use an XML
pr
PY
Schema.
oh

– Refer to an XML reference if you need more detail on this.


ib

‹ The xsi:schemaLocation property in the slide doesn't specify a version number for the schema.
i tie

– The latest version will automatically be picked up.


d

– For example, spring-beans-4.3.xsd (latest current version in Spring 5 as of this writing).


• You read that correctly, the latest schema version is 4.3, even for Spring 5.
‹ Typically configure beans like service and repository objects, Hibernate sessions, JMS queues, etc.
‹ Some BeanFactory implementations also permit the registration of existing objects that have been
created outside the factory (by user code).

Copyright © LearningPatterns Inc. All rights reserved. 22


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

The Spring Container


‹ The Spring container
– Reads your configuration, and based on it:
• Instantiates/initializes application objects
• Resolves object dependencies
EV
U
na

‹ org.springframework.context.ApplicationContext
ut

– Core API to access the Spring container in your code


AL
ho

– Several implementations with different capabilities, e.g.


riz

– ClassPathXmlApplicationContext: Loads XML resources


ed

from the class path


re
prU
AT
‹ Interface ApplicationContext extends BeanFactory
od

– BeanFactory has many core methods - usually not used directly


uc
tio
n
IO

Notes:
or

Interface BeanFactory is in package org.springframework.beans.factory.


di
N
‹
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 23


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Instantiating and Using the Container


‹ Below, we create a ClassPathXmlApplicationContext
– Sometimes called "instantiating the container"
– We pass the name of our config file (or multiple file names)
– The container will create and manage the beans defined in the XML
EV

Next, we look up our configured bean via the context


U

‹
na

– Looked up by type (Catalog.class) - can look up by name also (1)


ut

– We do any needed work, then close the context


AL
ho

import org.springframework.context.support.ClassPathXmlApplicationContext;
riz
ed

// Code fragment - other imports and much detail omitted


U
ClassPathXmlApplicationContext ctx=
new ClassPathXmlApplicationContext("applicationContext.xml");
re
pr

// Note that getBean uses Java generics (no casting needed)


AT
Catalog cat = ctx.getBean(Catalog.class);
od

// Or lookup by name: ctx.getBean("musicCatalog", Catalog.class);


uc

MusicItem item = cat.findById(1L); // Use our bean


ctx.close(); // Close the context
tio
n
IO

Notes:
or

Creating an instance of an ApplicationContext is often called "instantiating" or "bootstrapping" the


di
N
‹
container.
s tri

– When the instance is created, it reads the configuration.


bu

– Based on the configuration, it does whatever work it needs to get ready to supply you with beans.
t
C

– We then use that context instance to interact with the container.


io
n

– It contains the API that you have access to.


is
O
pr

(1)
It's generally easier and more reliable to look up beans by their type.
PY
oh

– However, sometimes that's not practical or possible - for example when there is more than one
concrete implementation of an interface.
ib
i

– We'll see bean lookup by name later.


tie
d

‹ We can pass multiple config files when creating the context, for example as shown below.
ApplicationContext ctx =
new ClassPathXmlApplicationContext( "ctx-1.xml", "ctx-2.xml" );

Copyright © LearningPatterns Inc. All rights reserved. 24


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Why Bother - What do we Gain?


‹ Main benefit: Our code doesn't know about CatalogImpl
– It just knows about needed functionality (interface Catalog)
– We've decoupled our code from a dependency on the
implementation class
EV
U

Can use any implementation in our configuration


na

– Client code will not change


ut
AL
ho

– That's why we code to interfaces, not concrete types


riz

Bean lifecycle is managed by container


ed

‹
U
– We don't instantiate our beans directly
re
pr
AT
‹ Very useful for more complex systems
od

– We'll see more useful capabilities soon


uc
tio
n
IO

Notes:
or

In this simple example, it looks like we've done quite a bit of work to instantiate a single instance of a
di
N
‹
single class.
s tri

– What is the benefit?


bu
t
C

The decoupling we've achieved seems like a simple thing, but it has a lot of benefits, especially when
io

‹
maintaining large systems.
n
O
– We'll see how useful it can be when we explore more of the capabilities.
is
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 25


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Summary: Working With Spring


‹ Create Spring configuration data for your beans
– It's the "cookbook" telling Spring how to create objects
– Via an XML file like applicationContext.xml or via annotations
EV

Initialize the Spring container


U

‹
na

– e.g. create an application context instance to read config data


ut
AL
– It will initialize the beans in the config file(s)
ho
riz

‹ Retrieve beans via the context instance and use them


ed

U
– e.g. use getBean() to look up a bean by type or name
re

– Lookup by type is preferred, unless you can't do it


pr
AT

• For instance, if you have two beans implementing the same type
od
uc
tio
n
IO

Notes:
or

There are many, many usage scenarios for Spring.


di
N
‹
s

– And many, many different alternatives for each scenario


tri

– Spring is very large, and has a lot of flexibility and capability


bu
t io
C

‹ In this initial introduction we show you one straightforward way of using Spring.
n
O
– We will gradually introduce more capabilities throughout the course.
is
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 26


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

More on ApplicationContext
‹ Access point for many Spring capabilities, including:
– Bean access
– Resource Access: Config files, URLs, other files
– Message resources with I18N capability
EV

– Publishing events to managed beans that are listeners


U

– Multiple, hierarchical contexts


na
ut

ClassPathXmlApplicationContext
AL
‹
ho

– Loads XML config files from the classpath


riz

‹ FileSystemXmlApplicationContext
ed

– Loads XML config files from the file system or URLs


re
U

– Both in org.springframework.context.support
pr
od
AT

‹ AnnotationConfigApplicationContext
uc

– Accepts annotated classes as input (more on this later)


– In org.springframework.context.annotation
tio
n
IO

Notes:
or

The ApplicationContext is the full-fledged representation of the Spring container.


di
N
‹
s

– It is often regarded as the type that supplies the "framework" capabilities of Spring, rather than
tri

simple bean management.


bu

If you are writing applications for a very resource-restricted environment, such as a mobile device,
C
‹
you might consider using BeanFactory over ApplicationContext.
t io

– Then again, even mobile devices these days usually have enough capability to make the
n
O
additional resources used by ApplicationContext negligible.
is

‹ There are also Web-based application contexts we'll cover later.


pr
PY
‹ We'll cover the ApplicationContext API in various parts of the course.
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 27


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Some BeanFactory/ApplicationContext API


‹ Useful methods include:
– boolean containsBean(String): true if named bean exists
– <T> T getBean(Class<T> requiredType): Get by type
– <T> T getBean(String, Class<T> requiredType): Get by name
EV

– Class<?> getType(String name): Get type of named bean


U

– boolean isSingleton(String): Is bean a singleton


na

– String[] getAliases(String): Get any aliases for this bean


ut
AL
ho

– Many more methods - see the javadoc


riz

‹ Can specify config files in multiple ways


ed

U
– ant-style wildcards: e.g. conf/**/ctx.xml - All ctx.xml files under conf
re

– file: and classpath: prefixes - forces use of specified location, e.g.


pr
AT
• The following loads from the classpath:
od

• new FileSystemXmlApplicationContext("classpath:ctx.xml");
uc

– Spring uses its resource classes under the hood to do this


tio
n
IO

Notes:
or

The methods shown are a part of the BeanFactory API inherited by ApplicationContext.
di
N
‹
s

‹ getBean returns either a singleton (shared) instance, or a newly created bean.


tri

– NoSuchBeanDefinitionException thrown if the bean can't be found


bu

C
– BeansException thrown if an exception occurred while instantiating/preparing the bean
t io

– BeanNotOfRequiredTypeException thrown if the bean is not of the required type


n
O
‹ Object getBean(String) returns an object – which is then cast to the required type.
is

– The newer getBean(String,Class<T> requiredType) method is generally preferred.


pr
PY
‹ getType(String) throws NoSuchBeanDefinitionException if the bean can't be found.
oh

‹ isSingleton(String) throws NoSuchBeanDefinitionException if bean can't be found.


ib

‹ The method <T> T getBean(String, Class<T> requiredType) may look strange.


i tie

– This is standard Java generics syntax - The first <T> in the return type simply indicates that this
is a generic method, parameterized by the type parameter <T>.
d

– The T return value indicates that the return type is generic (that is, it will take on different types
based on the <T> parameter).
– The Class<T> argument indicates that when you call the method, you pass in the class which
specifies what type <T> actually is in that call.

Copyright © LearningPatterns Inc. All rights reserved. 28


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Mini-Lab: Review Javadoc


Mini-Lab
‹ We provide the Spring Javadoc
– Under StudentWork/Spring/Resources/SpringDocs/javadoc
EV

In a browser, open index.html in the folder above


U

‹
na
ut

‹ Review the javadoc for the following types


AL
ho

– BeanFactory
riz

– ApplicationContext
ed

– ClassPathXmlApplicationContext (especially the constructors)


U
– FileSystemXmlApplicationContext (especially the constructors)
re
pr
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 29


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Lab 1.2: Hello Spring World


ut
AL
ho
riz

In this lab, we will create and use a Spring context


ed

to access a bean instance


re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 30


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Annotation-Based Configuration Example


‹ Beans can be declared with annotations
– @Component (org.springframework.stereotype) - Spring specific
• @Component often called a "stereotype" annotation
– @Named (javax.inject) - Standard Java (JSR 330) annotation
EV

– We'll use Spring style annotations in this course (1)


U
na

‹ Below, @Component declares CatalogImpl as a bean


ut

– Specifies id as musicCatalog (Default id: catalogImpl)


AL
ho

• Same bean as previous XML example


riz

– Could also have used @Named("musicCatalog")


ed

U
import org.springframework.stereotype.Component;
re

package com.javatunes.service;
pr
od
AT

@Component("musicCatalog") // Declares bean with id musicCatalog


public class CatalogImpl implements Catalog {
uc

/* Most detail omitted … */


tio

}
n
IO

Notes:
or

(1)
Common usage in Spring projects is to use the Spring-based annotations.
di
s
N

– Some advocate the usage of JSR-330 annotations since they are a Java standard.
tri

– This would (theoretically) allow you to port to another container that uses JSR-330 annotations -
bu

for example JEE and its CDI capabilities.


t
C

• However, this would entail a lot more work than just the annotations on the beans, so we
io

don't consider this much of a benefit, especially since it's relatively rare to do this kind of
n
O
transition.
is

– In addition, the behavior of the JSR-330 annotations in the Spring container are not exactly the
pr
PY
same as in a JEE container, so using them is somewhat misleading.
oh

– All these considerations lead us to choose the Spring-standard annotations over the JSR-330
ib

annotations when working with Spring.


i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 31


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

A Brief Note on Annotations


‹ Standard Java mechanism to add metadata to source code
– Like comments that the compiler is aware of

@ is used for both declaration and use of annotations (1)


EV
‹

– e.g. @Component
U
na
ut

Annotations don't directly affect program semantics


AL
‹
ho

– They are not executable code


riz
ed

U
‹ Tools work with the annotated code
re

– And may affect the semantics of a running program


pr
AT
– @Named/@Component annotated beans are recognized as bean
od

defs by the Spring container


uc
tio
n
IO

Notes:
or

(1)
There is a syntax for declaring annotations, a syntax for using them in declarations, a class file
di
N
representation, and an API to read them.
s tri

– We'll only cover the capabilities that we'll be using for our Spring coding.
bu
t
C

Annotations can replace many "side files" – e.g. XML deployment descriptors.
io

‹
n

– It's easier for tools to read the metadata and source if they're all in one place.
is
O

– They're often used for specifying details of high-level technologies (e.g. AOP, EJB, Web
Services …).
pr
PY
– These often result in code generation.
oh
ib
i

‹ Annotations are present in the class file, and can be read by tools.
tie

– The JDK also comes with a command line utility, called apt (Annotation Processing Tool), that
d

can be used to process annotations.

Copyright © LearningPatterns Inc. All rights reserved. 32


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Enabling Annotations / Detecting Beans


‹ Spring can automatically scan for annotated beans on the
classpath
– This registers them as normal beans
EV
‹ Enable auto scanning via <context:component-scan/>
U

– A standard element from Spring's context namespace (see next slide)


na

– Includes the capabilities of <context:annotation-config/> (1)


ut

– basePackage attribute configures the packages to scan


AL
ho

<beans xmlns="http://www.springframework.org/schema/beans"
riz

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
ed

xsi:schemaLocation="http://www.springframework.org/schema/beans
U
http://www.springframework.org/schema/beans/spring-beans.xsd
re

http://www.springframework.org/schema/context
pr
AT
http://www.springframework.org/schema/context/spring-context.xsd">
od

<context:component-scan base-package="com.javatunes"/>
uc

</beans>
tio
n
IO

Notes:
or

(1)
In addition to enabling scanning, context:component-scan also enables the capabilities of
di
N
context:annotation-config.
s tri
bu

context:annotation-config activates the ability to detect annotations like @Autowired and


C
‹

@Required.
t io

– It only affects beans that are already registered.


n
O
– component-scan element in the slide example will scan for all components in the
is

com.javatunes package and all of its sub-packages, and register them as beans.
pr
PY
– Note that annotations are actually detected by bean postprocessors (not important to know, but
oh

interesting if you want to know a bit about Spring internals).


ib
i tie

‹ There are other attributes to component-scan, including


d

– annotation-config: (default true): should the implicit annotation post-processors


(AutowiredAnnotationPostProcessor, CommonAnnotationPostProcessor) be
registered
– resource-pattern: Controls the class files eligible for component scanning. Default is
**/*.class, the recommended value

Copyright © LearningPatterns Inc. All rights reserved. 33


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Overview - Spring's XML Schemas


‹ Spring provides XML Schemas for configuration
– With custom namespaces and tags with complex behavior (1)
– e.g. the context: namespace we just used
EV

Spring namespaces include:


U

‹
na

– aop: Configures AOP support


ut

– beans: The standard bean tags we've seen already


AL
ho

– context: Configures ApplicationContext related things


riz

– jee: JEE related configuration such as looking up a JNDI object


ed

U
– jms: Configures JMS related beans
re

– lang: Exposing objects written in language like JRuby as beans


pr
AT
– tool: Adds tooling-specific metadata
od

– tx: Configures transaction support


uc

– util: Common, utility configuration issues


tio
n
IO

Notes:
or

(1)
We've seen the usage of <context:component-scan> previously.
di
s
N

– It is is a shorthand to introduce a number of bean definitions into the configuration.


tri

– The tags in these schemas typically have capabilities beyond simple bean definitions and
bu

injection.
t
C

– This is one of the nice things about the custom namespaces - they can make configuration much
io

easier.
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 34


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Lab 1.3: Spring Annotations


ut
AL
ho
riz

In this lab, we'll work with Spring Annotations


ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 35


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Dependency Injection
ut
AL
ho
riz

Overview
ed

U
Spring Introduction
re

Dependency Injection
pr
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 36


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Dependencies Between Objects


‹ In OO systems, multiple objects work together
– e.g., Object A directly uses Object B to accomplish a goal (1)
– So Object A depends on Object B
EV

Direct dependencies have several issues


U

‹
na

– Rigid: Changes affect other areas, so are hard to make


ut
AL
– Fragile: Changes cause unexpected failures in other areas
ho

– Immobile: Hard to reuse functionality


riz

• Modules can't be disentangled


ed
re
U

‹ We'll illustrate a direct dependency


pr
AT

– Then show an alternative approach


od
uc
tio
n
IO

Notes:
or

(1)
In straightforward applications, Object A will often just create an instance of Object B and use it.
di
s
N

– Object A is highly coupled to, and directly dependent on, Object B.


tri

– This is initially an easy way to structure a system, but often not the best way.
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 37


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Example of a Direct Dependency


‹ CatalogImpl uses InMemoryRepository
– And creates an InMemoryRepository instance directly
– CatalogImpl depends on the lower level module details
EV
– To use a different data store - e.g. a FileRepository,
CatalogImpl must change (see notes)
U
na
ut
AL
ho

public class InMemoryItemRepository {


public MusicItem get(Long id) { /* Details not shown */ }
riz

}
ed
re
U

public class CatalogImpl implements Catalog {


InMemoryItemRepository rep = new InMemoryItemRepository();
pr
AT
public MusicItem findById(long ID) {
od

return rep.get(id);
}
uc

}
tio
n
IO

Notes:
or

Assume we want to get our information from a class called FileRepository.


di
N
‹
s

– Assume it also has a get(Long id) method.


tri

‹ In that case, CatalogImpl might need to be changed to something like that below.
bu
t io
C

public class CatalogImpl implements Catalog {


n
O
FileRepository rep = new FileRepository();
is

public MusicItem findById(long id) {


pr

return rep.get(id);
PY
oh

}
}
ib
i tie

– This is not such a big deal if you have to change it in one place.
d

– But imagine if you had to change it in 100 places, or 10,000 places.

‹ Assume that classes in the examples in this session are in the com.javatunes.service package.
– We'll be leaving out most package statements in the Java code examples for brevity.

Copyright © LearningPatterns Inc. All rights reserved. 38


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Dependency Inversion
‹ All modules depend on abstractions, not each other
– In other words - program to interfaces
– CatalogImpl only knows about the abstract ItemRepository
• Can be initialized with another type (e.g. FileItemRepository)
EV
• CatalogImpl need not change - the modules are decoupled
U
na

public interface ItemRepository {


public MusicItem get(Long id);
ut

}
AL
ho

// Much detail omitted …


riz

public class InMemoryItemRepository implements ItemRepository { /*…*/ }


ed

public class CatalogImpl implements Catalog {


U
private ItemRepository itemRepository; // get/set methods not shown
public MusicItem findById(Long id) { return itemRepository.get(id); }
re

}
pr
AT
// Code fragment - most detail omitted
od

InMemoryItemRepository rep=new InMemoryItemRepository();


CatalogImpl catalogImpl=new CatalogImpl();
uc

catalogImpl.setItemRepository(rep);
tio

MusicItem found = catalogImpl.findById(1);


n
IO

Notes:
or

Dependency Inversion is not a new idea.


di
N
‹
s

– The idea of "Programming to Interfaces" has been around since long before Java.
tri

– It has been used in non-OO languages also, for example the stdio module in the C programming
bu

language abstracted away the details of the actual devices doing the output.
t
C

We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use.
io

‹
n

We talk of modules here, which in this example result in dependencies between different classes.
O
‹
is

‹ In the example, we see that CatalogImpl knows nothing about InMemoryItemRepository.


pr

– It only depends on the ItemRepository interface (the abstraction).


PY
oh

– When CatalogImpl is created, you initialize it with an instance of an ItemRepository


implementation.
ib
i

– But it doesn't know any details of this implementation, and doesn't even know its exact type.
tie

‹ InMemoryItemRepository also depends on the abstraction (it implements ItemRepository ).


d

– The abstraction (the interface) is the common language that lets the different parts of the system
work together without depending directly on each other.
‹ We are still creating the InMemoryItemRepository directly in our code (in this example).
– We'll have Spring do this soon, which gives even more benefit.

Copyright © LearningPatterns Inc. All rights reserved. 39


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Dependency Injection (DI) in Spring


‹ The Spring container injects dependencies into a bean
– Into bean properties, constructors, or via factory method args

‹ Dependencies are defined in the Spring configuration


EV
– Spring initializes the dependencies ("injects" them) based on the config
U

– No need to explicitly initialize dependencies in your code


na

‹ We illustrate XML config of this below (injecting via a set method)


ut
AL
– <property …> injects into the catalog's itemRepository property
ho

– Automatically done when the container creates the bean


riz
ed

<beans … > <!-- Much detail / Namespace declarations omitted -->


U

<bean id="inMemoryRepository"
re

class="com.javatunes.persistence.InMemoryItemRepository"/>
pr
AT
<bean id="musicCatalog" class="com.javatunes.service.CatalogImpl">
od

<property name="itemRepository" ref="inMemoryRepository"/>


uc

</bean>
tio

</beans>
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 40


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Injection with Autowired


‹ Can also inject with @Autowired - shown below for the repository
– This injects a dependency by type - same result as previous XML
‹ At bottom, we get a catalog from Spring
– With an already initialized repository (by Spring's DI)
EV

– We're ready to work !


U
na

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
ut
AL
@Component("musicCatalog") // Declares bean - most detail omitted
ho

public class CatalogImpl implements Catalog {


riz

@Autowired // can also apply to setter method or constructor


private ItemRepository itemRepository;
ed

}
re
U

public class CatalogTests { // imports, other detail omitted


@Test testCatalogFindById() {
pr
AT
ClassPathXmlApplicationContext ctx =
od

new ClassPathXmlApplicationContext("applicationContext.xml");
Catalog cat = ctx.getBean(Catalog.class); // See note (1)
uc

assertNotNull("item shouldn't be null", cat.findById(1L)); // Use cat


tio

}
n
IO

Notes:
or

(1) The bean lookup with the code shown directly below works because there is only one bean that
di
N
implements Catalog, so the container can find this bean by type.
s tri

ctx.getBean( Catalog.class );
bu

–We'll see ways to refine this type of lookup later.


t
C

Note that CatalogImpl and InMemoryItemRepository didn't need anything special to support
io

‹
Spring's DI.
n
O
–They just need to be written according to the design principles of Dependency Inversion (i.e.
is

coding to an interface, not a concrete type) which is good practice anyway.


pr
PY
–Once this was done, we didn't need any special capabilities to support DI.
oh

‹ Note also that there is nothing in your CatalogTests code which shows that CatalogImpl
ib

depends on InMemoryRepository.
i tie

–This is defined in your configuration, and handled for you by the container.
d

Copyright © LearningPatterns Inc. All rights reserved. 41


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

@Named/@Inject (JSR-330) Example


‹ Below, @Named is used to declare a bean
– @Inject is used to inject the dependency

‹ Results are the same as with @Component style


EV
– And the test client would look exactly the same
U
na

‹ We'll use @Component style going forward, as mentioned earlier


ut
AL
– It's the more common choice
ho
riz
ed

import javax.inject.Inject;
U
import javax.inject.Named;
re

@Named("musicCatalog") // Declares bean - most detail omitted


pr
AT
public class CatalogImpl implements Catalog {
od

@Inject
private ItemRepository itemRepository;
uc

}
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 42


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Dependency Injection Reduces Coupling


‹ The simplest case,
CatalogImpl coupled to
CatalogImpl InMemoryItemRepository
InMemoryItemRepository
EV
‹ CatalogImpl coupled to
ItemRepository only <<interface>>
U

CatalogImpl ItemRepository
(Dependency Inversion)
na

– CatalogTests coupled to creates


ut

implements
CatalogImpl and
AL
ho

CatalogTests InMemoryItemRepository
InMemoryItemRepository creates
riz
ed

‹ Using DI – CatalogTests
U
<<interface>>
only coupled to Catalog CatalogImpl
Catalog
re

implements
– CatalogImpl only coupled
pr
AT
to ItemRepository injects
od

<<interface>>
looks up ItemRepository
uc

CatalogTests ApplicationContext
tio
n
IO

Notes:
or

In the slide, we show diagrams of the three different ways we structured our code in the earlier slides.
di
N
‹
s

– In the first, CatalogImpl is directly coupled to InMemoryItemRepository.


tri

– In the second, CatalogTests is doing the dependency injection of the


bu

InMemoryItemRepository into CatalogImpl.


t
C

• CatalogTests is coupled to both of these types, but CatalogImpl is only coupled to


io

ItemRepository.
n
O
– In the third, Spring is doing the DI, and so CatalogTests and CatalogImpl are only coupled
is

to abstract interfaces.
pr
PY
oh

‹ In the Spring DI version, all the dependencies in the code are ONLY to interfaces.
ib

– This is much better than being coupled to actual implementation classes.


itie

– It increases flexibility, testability, and ease of maintenance.


d

Copyright © LearningPatterns Inc. All rights reserved. 43


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Advantages of Dependency Injection


‹ Hides dependencies and reduces coupling in your code
– Coupling is basically a measure of the dependencies

‹ We see this in two ways:


EV

– CatalogImpl is not coupled to InMemoryItemRepository


U
na

– CatalogTests is not coupled to CatalogImpl or


InMemoryItemRepository
ut
AL
ho

‹ The dependencies are still there but not in the code


riz

– Dependencies are moved to the spring configuration


ed

U
– They're injected into beans without you coding it
re

– Commonly referred to as wiring beans together


pr
od
AT

‹ This leads to more flexible code that is easier to maintain


uc

– At a cost – using Spring, and maintaining the spring configuration


tio
n
IO

Notes:
or

Coupling is the measure of how much a module of code relies on other modules.
di
N
‹
s

– Loosely coupled code is generally considered better code.


tri

‹ Consider some of the following scenarios, and how DI makes them easier.
bu

C
– Testing your code with a testing framework such as JUnit can be much easier with DI – you can
t

configure the application to use mock objects wherever you want – without changing your code
io

at all.
n
O
– Testing different versions of classes can be done just by changing the configuration metadata.
is

– In fact, any implementation class that implements the particular interfaces being used can be
pr
PY
swapped into your program simply by changing the configuration information.
oh

‹ There is debate about how worthwhile DI and frameworks like Spring are.
ib

– However, the principles that it is based on that lead to loose coupling are widely accepted.
i tie

– Spring simply makes it easier to apply these principles.


d

– The effort required to learn, adopt, and use Spring is not trivial, but the initial cost of adopting
Spring can be well worth it in writing and maintaining any reasonably sized system.

Copyright © LearningPatterns Inc. All rights reserved. 44


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Constructor Injection
‹ Can easily inject into a constructor (ctor)
– Assume the CatalogImpl constructor shown below
‹ With XML, <constructor-arg> means "inject into constructor"
With @Autowired, apply it to the constructor
EV
‹

See notes for some additional detail/capabilities


U

‹
na

public class CatalogImpl implements Catalog { // Most detail omitted


ut
AL
public CatalogImpl(ItemRepository repository) { /* … */ }
ho

}
riz

<!-- XML config - Other detail omitted -->


ed

<bean id="musicCatalog"
U
class="com.javatunes.service.CatalogImpl">
re

<constructor-arg ref="itemRepository"/> <!-- inject via ctor -->


</bean>
pr
od
AT

public class CatalogImpl implements Catalog { // Most detail omitted


@Autowired // Inject into ctor below
uc

public CatalogImpl(ItemRepository repository) { /* … */


tio

}
n
IO

Notes:
or

For @Autowired, if there is only one constructor, you can even leave out @Autowired.
di
N
‹
s

– It will be inferred - but we believe it's better practice to include it explicitly.


tri

‹ If a constructor has multiple arguments, they will all be injected with @Autowired.
bu

C
– For example, assuming that a CatalogImpl needs an ItemChecker to do some sanity
t

checking on items, you might have the following ctor, which will have both arguments injected.
io
n

@Autowired
is
O

public CatalogImpl(ItemRepository rep, ItemChecker checker)


pr

‹ In XML, multiple arguments would be handled with multiple <constructor-arg>s.


PY
oh

<bean id="musicCatalog" <!-- inject two ctor arguments -->


class="com.javatunes.service.CatalogImpl">
ib

<constructor-arg ref="itemRepository"/>
i tie

<constructor-arg ref="itemCheck"/> <!-- itemCheck def not shown -->


d

</bean>
‹ There are a lot of ways to configure the ctor injection.
– For example, you can specify the type and/or index of args with XML configuration.
– These details are best explored as needed in the documentation, not during class time.

Copyright © LearningPatterns Inc. All rights reserved. 45


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Setter Injection vs. Constructor Injection


‹ Setter Injection Pros
– Easy, Flexible: Simple setters, easily choose properties to configure
– Good for optional properties (with defaults to reduce not-null checks)
– Supports reconfiguration after startup
EV

‹ Setter Injection Cons


U

– Doesn't guarantee property initialization (Forget to do it - BUG!)


na

– Setter methods are required


ut
AL
ho

‹ Constructor Injection Pros


riz

– Guaranteed Initialization: Immediate error if you leave it out (1)


ed

U
– Good for required properties (can be immutable if setter omitted)
re

‹ Constructor Injection Cons


pr
AT
– Unwieldy and Brittle: Multiple constructors with multiple args unwieldy
od

• Refactor if you have this


uc

– Less flexible: Need ctors for each scenario, and can't reset properties
tio
n
IO

Notes:
or

(1)
If you leave out a constructor argument while configuring a bean, you'll have an error.
di
s
N

– If using XML configuration or @Autowired, you'll get a runtime exception as soon as the code
tri

is run.
bu
t
C

You can mix constructor and setter injection.


io

‹
n

– For example, using constructor injection on required properties, and setter injection on other
O
properties.
is
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 46


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Qualifying Injection by Name


‹ Consider two repository implementations (first two examples below)
– What happens if we try to auto-wire one in?
– The first autowire below fails at runtime - which one to inject?
– The second try is "qualified" by the bean name using @Qualifier
EV

– It injects based on the bean name


U
na

@Component // Declare as bean - default id inMemoryItemRepository


public class InMemoryItemRepository implements ItemRepository {…}
ut
AL
ho

@Component // Declare as bean - default id cloudItemRepository


public class CloudItemRepository implements ItemRepository {…}
riz
ed

@Component public class CatalogImpl implements Catalog { // Autowire


U
@Autowired private ItemRepository itemRepository; // FAILS!
re

}
pr
AT
import org.springframework.beans.factory.annotation.Qualifier;
od

@Component public class CatalogImpl implements Catalog { // Autowire


uc

@Autowired @Qualifier("cloudItemRepository")
private ItemRepository itemRepository; // Injects the Cloud-based
tio

}
n
IO

Notes:
or

In the first example of injection, where the autowiring is done by type, it fails at runtime.
di
N
‹
s

@Autowired private ItemRepository itemRepository; // FAILS!


tri

–The container doesn't know which of the two possible types to use.
bu

C
‹ In the second example of injection we use @Qualifier to supply a bean name.
t io

–This pinpoints exactly which bean should be injected, and works as you'd expect.
n
O
@Autowired
is

@Qualifier("cloudItemRepository")
pr

private ItemRepository itemRepository; // Injects the Cloud-based


PY
oh

‹ There are other, more sophisticated, ways to qualify an injection.


ib

–This involves defining your own qualifiers, for example @CloudBased instead of using names.
i

–This is compile-time safe, as it is not a string-based approach, so useful for program correctness.
tie

–However, it's fairly complex, and arguably the complexity is often not worth the benefit.
d

–With adequate testing, name-based qualifying should work fine.


–In those instances (rare) when it's not suitable, then you can use the more sophisticated approach,
which is beyond the scope of this course.

Copyright © LearningPatterns Inc. All rights reserved. 47


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring
EV
U
na

Lab 1.4: Dependency Injection


ut
AL
ho
riz

In this lab, we'll work with Spring's DI capabilities


ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 48


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Review Questions
‹ What is Spring, and how does it help you build enterprise
apps?

What is Dependency Inversion?


EV
‹
U
na

‹ What is Dependency Injection, and how does it work in


ut

Spring
AL
ho
riz

‹ What is an ApplicationContext?
ed
re
U

‹ How does Spring use annotations on your bean classes for


pr
AT
defining and wiring beans?
od

– What are the pros/cons of using them?


uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 49


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Lesson Summary
‹ Spring: Lightweight enterprise framework that supports:
– Dependency Injection
– Persistence support (Repository/DAO and ORM)
– Integration with standard Web technologies, and MVC Web apps
EV
U

‹ Manages complex dependencies - non-intrusive and lightweight


na

– Supports loose coupling between components


ut
AL
– Encourages coding to interfaces (good design)
ho

• Also called Dependency Inversion


riz
ed

‹ Uses configuration metadata to initialize beans and


U

dependencies
re
pr

– Via XML configuration files or annotations


od
AT

Dependency Injection: Injects dependencies based on config


uc

– Complete decoupling from concrete implementation types


tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 50


Introduction to Spring 5 and Spring MVC/REST Session 1: Introduction to Spring

Lesson Summary
‹ ApplicationContext: API to the Spring container functionality
– Configure/wire beans, access program resources, work with resource
bundles, load multiple contexts, and publish events to beans
– Common implementations include:
EV

ClassPathXmlApplicationContext,
U
na

FileSystemXmlApplicationContext, and
ut

AnnotationConfigApplicationContext
AL
ho
riz

Provides resource access in a flexible and powerful way


ed

‹
U
– From file system, the classpath, URL access, and more
re

– Supports ant-style wildcards like conf/**/ctx.xml


pr
AT
– Uses its own resource classes to accomplish resource access
od
uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d

Copyright © LearningPatterns Inc. All rights reserved. 51


PY
Introduction to Spring 5

d
tie
O
i
Spring MVC/REST

ib
oh
C is
pr
N
n
tio

Lab Manual
bu
and
IO di
s tri
AT
or
n
tio
U uc
AL
od
pr
re
ed
EV
riz
ho
ut
na
U
EV
U
na
ut
AL
ho
riz
ed
re
U
pr
od
uc AT tio
n
IO

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or
or

distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc.
Copyright © LearningPatterns Inc.
di
s
N

For more information about Java Enterprise Java, or related courseware, please contact us. Our courses
tri

are available globally for license, customization and/or purchase.


bu

C
LearningPatterns. Inc. Services@learningpatterns.com | www.learningpatterns.com
t io

Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA
n
O
212.487.9064 voice and fax
is
pr
PY
Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in
oh

the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns
Inc. All other products referenced herein are trademarks of their respective holders.
ib
itie
d
Labs: Introduction to Spring 5 and Spring MVC/REST Introduction
EV
U
na

Labs: Introduction to Spring 5 and


ut

Spring MVC/REST (Eclipse/Tomcat)


AL
ho
riz
ed
re
prU
od
uc AT

Version: 20180521-b
tio
n
IO

Notes:
or

Version 20180521-b
di
N
‹
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

Copyright © LearningPatterns Inc. All rights reserved. 1


Labs: Introduction to Spring 5 and Spring MVC/REST Introduction

Release Level Lab

‹ This manual has been tested with, and contains instructions


for, running the labs using the following platforms:

– Spring Boot (tested with 2.0.0.RELEASE)


EV

– Spring 5 (tested with 5.0.4.RELEASE)


U

• Release used by Spring Boot


na

– Java (tested with and requires Java 8 )


ut
AL
ho

– Eclipse Java EE Edition (tested with Oxygen 4.7.2))


riz

– Tomcat for the Spring/Web material (tested with Tomcat 8.5)


ed

Recent similar versions of the software will likely work except


re

‹
pr

for potentially small configuration changes


od
uc AT tio
n
IO

Notes:
or

Any 5.x version of Spring should work.


di
N
‹
s

– The course materials are compatible with all 5.x versions.


tri

– However, we include some Spring jars and their dependencies with the labs.
bu

C
– If you want to use a different version, then it's up to you to make sure you have all the correct
t

Spring jars and the correct dependency jars.


io
n

– We will also introduce Maven and Spring Boot to manage all dependencies later in the course.
is
O
pr

‹ Spring Boot 2 is needed to support Spring 5.


PY
oh

– At the time of this writing the latest release version was Spring Boot 2.0.0.RELEASE.
ib
i
tie

‹ All labs have been tested on Microsoft Windows using the software listed above.
– Many have been tested on Mac OS also.
d

– The labs should work on unix variants with little modification, except for the database setup
scripts, which need to use unix shell scripts, which we also supply.

Copyright © LearningPatterns Inc. All rights reserved. 2


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment
EV
U
na

Lab 1.1: Setting Up the Environment


ut
AL
ho
riz

In this lab you'll set up the lab environment, boot the


ed

Spring container, and test it with a unit test


re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 3


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Lab Synopsis Lab

‹ Overview: In this lab, we will:


– Become familiar with the lab structure
– Set up our environment, including the Spring container
EV
– Write, compile and run a simple unit test that requires Spring and
validates our setup
U
na
ut

Builds on previous labs: None


AL
‹
ho
riz

‹ Approximate Time: 30-45 minutes


ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 4


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Information Content and Task Content Lab

‹ Within a lab, information only content appears the same as


in the student manual pages
– Like these bullets at the top of the page
Tasks to perform are in an easily identifiable box
EV
‹

– An example appears below


U
na
ut

Tasks to Perform
AL
ho

‹ Note the different look of this instruction box compared to the


riz

above
ed

– Future labs will also use this format


re
U

OK – Now locate your setup files; we're ready to start working (1)
pr
AT
‹
od
uc
tio
n
IO

Notes:
or

(1)
Depending on your training environment, the setup files may be given to you in different ways,
di
N
including the following.
s tri

– Present on the training machines as a zip file


bu

– Already unzipped on the training machine


t
C

– Given to you by the instructor


io
n

– Available as a network share or web download


is
O
pr

‹ Your instructor will let you know how to access them.


PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 5


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Set Up Environment Lab

‹ You'll need the lab setup file, with a name like


– LabSetup_Spring5-MVC-REST_2018050521.zip
‹ Our base working directory (created when we extract the setup) is:
C:\StudentWork\Spring
EV

– Assuming you extracted the zip to C:\ - otherwise adjust accordingly


U

– It includes a directory structure and files needed for the labs


na
ut
AL
ho

Tasks to Perform
riz

‹ Make sure Java is installed


ed

‹ Make sure Eclipse is installed


U

Unzip the lab setup file to C:\


re

‹
pr
AT
– This will create the directory structure, described in the next slide,
od

containing files that you will need for doing the labs
uc

– You can unzip it elsewhere - just adjust all locations consistently (1)
tio
n
IO

Notes:
or

To make sure Java is installed, you can do one of the following.


di
N
‹
s

– Open a command prompt, and type the below - it should execute and give version information.
tri

java -version
bu

C
– Look in C:\Program Files\Java for an installed JDK.
t io

‹ If Java is not installed, then download it from one of the following, and execute the installer.
n
O
– https://java.com/en/download/index.jsp
is

– https://java.com/en/download/manual.jsp
pr

To make sure Eclipse is installed, check for the install folder (usually C:\Eclipse).
PY
‹
oh

– If Eclipse is not installed, then first download it from http://www.eclipse.org/downloads.


ib

– Select the download packages link, then click on the link for the Eclipse IDE for Java EE
i

Developers, and select the appropriate zip file 32/64 bit, Windows vs. Linux, etc.
tie

– If you need to install Eclipse, unzip the zip file - easiest location to unzip it to is C:\, but another
d

location is fine as long as you can get to it to run the eclipse.exe executable.
(1)
You can install the software and unzip the lab setup anywhere that is convenient to you.
– We give instructions based on the locations above - just adjust accordingly to your locations.

Copyright © LearningPatterns Inc. All rights reserved. 6


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Lab Directory Structure Lab

‹ StudentWork\Spring contains
– Derby/DerbyLib: Database files
– mavenRepository: pre-populated
repo for labs
EV
– SpringDependencies: Dependency
U

jars
na

– SpringLibraries: Spring jars


ut

– workspace: Eclipse workspace


AL
ho
riz

‹ StudentWork\Spring\workspace
ed

will contain the following folders:


U
– LabNN : Folder for Lab NN
re

– LabNN/src : Java source


pr
AT

– LabNN/test : Java unit tests


od

– LabNN/bin/ : compiled code


uc

(Eclipse's standard location)


tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 7


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

General Lab Structure Lab

‹ Root lab folder for this lab, already in your workspace is:
workspace\Lab01.1
–It contains starter files
EV
• All labs either have starter files or build on a previous lab
–You'll create an Eclipse project in this folder
U
na

–Lab files and instructions are relative to the Lab01.1 folder


ut
AL
ho

‹ Two source folders


riz

–src: Contains regular Java source


ed

U
–test: Contains JUnit test classes
re

• To test our code


pr
AT
• You'll run these using Eclipse's JUnit support
od

• test may sometimes contain a regular Java app (with a main())


uc
tio
n
IO

Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 8


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Eclipse Overview Lab

‹ Eclipse: Open source platform for building integrated


development environments (IDEs)
– Used mainly for Java development
– Can be flexibly extended via plugins to add capabilities
EV

– http://www.eclipse.org is the main website


U
na
ut

This lab includes detailed instructions on using Eclipse


AL
‹
ho

– Starting it, creating and configuring projects, etc.


riz
ed

U
‹ Other labs include fewer Eclipse details - they may just say
re

build/run as previously
pr
AT
– Just use the same procedures to build/run as in this lab
od

– Refer back to these lab instructions as needed


uc
tio
n
IO

Notes:
or

The Eclipse source base was originally developed by IBM.


di
N
‹
s

– It was released by IBM into open source.


tri

– IBM's RAD (and it's predecessor WSAD) are built on top of Eclipse.
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 9


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Launch Eclipse Lab

Tasks to Perform
‹ Launch eclipse: Go to c:\eclipse and run eclipse.exe
– A dialog box appears prompting for workbench location (below left)
– Set the workbench location to C:\StudentWork\Spring\workspace
EV

– Click OK
U

– Close the Welcome screen: Click the X on its tab (below right)
na
ut
AL
ho
riz
ed
re
prU
od
uc AT tio
n
IO

Notes:
or

If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly.
di
N
‹
s

– You can put a shortcut to this executable on your desktop.


tri

‹ You can also have your lab workspace in a different location.


bu

C
– Again, just adjust the lab instructions as required.
t io

‹ If a different default workspace location is set when you start Eclipse, then change it.
n
O
– Sometimes Eclipse is set up to automatically open to a different workspace location.
is

– If this is the case, you can switch workspaces after Eclipse starts by going to File | Switch
pr

Workspace.
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 10


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Workbench and Java Perspective Lab

Tasks to Perform
‹ Open a Java Perspective: Click the Perspective icon at the top
right of the Workbench, and select Java (bottom left)
– See notes on Perspective Icons and text labels
EV

– Close the Java EE perspective by right clicking its icon, and


U

selecting close (bottom right)


na

Unclutter the Java Perspective by closing some views


ut

‹
AL
ho

– Close the Task List and Outline views (click on the X)


riz

– Open the Navigator View (Window | Show View | Navigator)


ed
re
U
pr
od
uc AT tio
n
IO

Notes:
or

The Eclipse Java EE version opens in the Java EE perspective by default.


di
N
‹
s

– Other versions may open in a different perspective. If you're already in a Java perspective, you
tri

don't need to switch perspectives, and there is nothing for you to do.
bu

To save a our "uncluttered" perspective as the default Java perspective go to:


C
‹
t

– Window | Save Perspective As | Java


io
n

You can reset the perspective to its defaults via: Window | Reset Perspective.
O
‹
is

‹ In Eclipse Neon (4.6) and later, the perspective switcher does not show the perspective text by
default.
pr
PY
– To change this, right click on the perspective icons, select Show Text - see examples below.
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 11


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Java Perspective: Where's the Projects? Lab

‹ Relax! The projects will reveal themselves as we proceed


– Do not import anything
EV
U
na
ut
AL
financial info
ho
riz
ed
re
prU
od
uc AT tio
n
IO

Notes:
or
di
s tri
N bu
tio
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 12


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Create User Libraries Lab

‹ Projects require Spring jars from the Spring distribution, plus


external dependencies (all supplied in the lab setup)
– We'll set up jars as an Eclipse user library for ease of use
– Labs before Spring Boot depend on these libraries being set up
EV

– Later labs use maven for dependencies


U
na

Tasks to Perform
ut

Go to Window | Preferences | Java | Build Path | User Libraries


AL
‹
ho

– Click New… , in the dialog, call the library Spring, and press OK
riz

– Click the Add External JARs… button, browse to


ed

StudentWork\Spring\SpringLibraries
U

– Select all the jars in that folder, Click Open


re
pr

– Select the Spring library again, click Add External JARs…, browse to
od
AT

StudentWork\Spring\SpringDependencies
uc

– Select all jars in that folder, Click Open


– Click OK to finish creating the library
tio
n
IO

Notes:
or

We include all the Spring jars from the Spring distribution in our setup
di
N
‹
s

– This is for ease of use


tri

– Otherwise you would need to download them somehow - which is no longer a trivial job since
bu

there is no archive available from the Spring project with all the jar files that make up the Spring
C
distribution
t io
n
O
We supply all needed dependencies in the SpringDependencies folder
is

– These were figured out by using Maven and seeing what dependencies were added to the project
pr
PY
– In this folder, we supply all the external dependencies for all the labs
oh

– This is quite a bit more than is needed for this lab


ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 13


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Create a Project for our Application Lab

Tasks to Perform
‹ Create a Java Project (1)
– Call the project Lab01.1
• You MUST call it this to pick up
EV
starter files
U

– Eclipse will then automatically set


na

the project folder to Lab01.1


ut

• It already exists in the workspace


AL
ho

• Contains Java project for Eclipse


riz

– Click Next
ed

This will bring you to the Java


U
‹
re

Settings dialog
pr
AT
– It should show the src and test
od

folders as source folders (2)


uc

– It will also let us add a library


tio
n
IO

Notes:
or

(1)
To create a Java Project, use the menu item:
di
s
N

– File| New | Java Project


tri
bu
t io
C

‹ There are many other ways to create a project.


n
O
– You can use the new icon on the left hand side of the toolbar, as shown above.
is

‹ You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a
pr

new Lab directory - this happens several times in the course.


PY
oh

(2)
You should see the following two folders picked up automatically by Eclipse as source folders.
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 14


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Add the Spring Library to the ClassPath Lab

Tasks to Perform
‹ In Java Settings
dialog, click the
Libraries tab (1)
EV
–Click Add Library
U

button, and in the


na

dialog that comes


ut

up, select User


AL
ho

Library then click


Next
riz

–Check off Spring,


ed

U
then click Finish out
re

of all dialogs
pr
od
uc AT tio
n
IO

Notes:
or

(1)
If you forget to add the library in this step, you can always add it later as follows.
di
s
N

– Right click on the project in Package Explorer, and select Build Path | Add Libraries.
tri

– That should bring you to the Libraries tab, so add in the Spring library as described above.
bu
t io
C

‹ Note that we include the JUnit library with the SpringDependencies.


n
O
– Eclipse also provides a JUnit library, but we prefer not to have an Eclipse dependency in the lab
is

classpath.
pr
PY
oh

‹ When the project is created, Eclipse will attempt to compile all the Java source.
ib

– This may lead to warnings about unused imports, variables, etc. depending on our setup files.
i

– You can just ignore these – most of them are because the files we give you are just skeletons, and
tie

not complete..
d

– If you want, you can shut these warnings off as follows:


Window | Preferences | Java | Compiler | Errors/Warnings
– Go to the "Unnecessary Code" section, and change the settings for "Unused import", "Unused
local or private member", and "Local variable is never read" to "Ignore".

Copyright © LearningPatterns Inc. All rights reserved. 15


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Running the Lab Lab

Tasks to Perform
‹ We use Eclipse to run a test case
in SpringTest.java
– No coding needed in this class (1)
EV

– It just bootstraps Spring to test the


U

environment
na

‹ After a clean build (error-free, not


ut
AL
necessarily warning-free), do the
ho

following
riz

– In Package Explorer , right click


ed

on SpringTest.java
re
U

• In com.javatunes.spring
package under the test folder
pr
AT

– Select: Run As -> JUnit Test


od

– This automatically finds and runs


uc

SpringTest's test method


tio
n
IO

Notes:
or

(1)
Don't worry about the Spring code at this point…we'll cover all of it the next section.
di
s
N

– This lab is designed to ensure that the project is set up and runs properly.
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 16


Labs: Introduction to Spring 5 and Spring MVC/REST Lab 1.1: Setting Up the Environment

Program Output Lab

‹ You should see JUnit output in a JUnit view, as shown below, and
output in the Eclipse Console view as shown at bottom
– These should all be error free (1)
Note: You'll follow similar procedures whenever you have a JUnit
EV
‹
test to run in the labs (2)
U
na
ut
AL
ho
riz
ed
re
prU
od
uc AT

STOP
tio
n
IO

Notes:
or

(1)
If you see any errors in the JUnit test, or exceptions in the Console output, then you've got something
di
N
configured incorrectly.
s tri
bu

(2)
When running tests in other labs, the only thing that may change is the test class that you'll need to
C
right click on to run.
t io

–The procedure will remain the same though.


n
is
O
pr
PY
oh
ib
itie
d

Copyright © LearningPatterns Inc. All rights reserved. 17


EV
U
na
ut
AL
ho
riz
ed
re
U
pr
od
AT
uc

7400 E. Orchard Road, Suite 1450 N


Greenwood Village, Colorado 80111
tio
IO
Ph: 303-302-5280
n

www.ITCourseware.com
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d

9-06-00087-000-09-10-18

You might also like