spring5-mvc-rest sessions 20180521-b · spring 5 and spring mvc/rest evaluation copy unauthorized...

83
Introduction to Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied

Upload: others

Post on 11-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Introduction to Spring 5 and

Spring MVC/REST

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 2: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright © LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. [email protected] | www.learningpatterns.com Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA 212.487.9064 voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in 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.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 3: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved i

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 Workshop Agenda_________________________________________________________________ 1 Typographic Conventions ___________________________________________________________ 1 Labs ____________________________________________________________________________ 1

Session 1: Introduction to Spring __________________________________________ 1 Lesson Objectives _________________________________________________________________ 1

Overview __________________________________________________________________ 1 Spring and Enterprise Applications____________________________________________________ 1 The Spring Modules _______________________________________________________________ 1 The Spring Distribution_____________________________________________________________ 1 The Spring jars ___________________________________________________________________ 1 A Word About JUnit _______________________________________________________________ 1 JUnit Example ____________________________________________________________________ 1

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

Managing Beans: Core Spring Capability _______________________________________________ 1 A Basic Spring Application__________________________________________________________ 1 The JavaTunes Online Store _________________________________________________________ 1 Some JavaTunes Types _____________________________________________________________ 1 XML Configuration Example ________________________________________________________ 1 The Spring Container ______________________________________________________________ 1 Instantiating and Using the Container __________________________________________________ 1 Why Bother - What do we Gain? _____________________________________________________ 1 Summary: Working With Spring______________________________________________________ 1 More on ApplicationContext_________________________________________________________ 1 Some BeanFactory/ApplicationContext API_____________________________________________ 1

Mini-Lab: Review Javadoc_______________________________________________________ 1 Lab 1.2: Hello Spring World _____________________________________________________ 1

Annotation-Based Configuration Example ______________________________________________ 1 A Brief Note on Annotations_________________________________________________________ 1 Enabling Annotations / Detecting Beans________________________________________________ 1 Spring's XML Schemas _____________________________________________________________ 1

Lab 1.3: Spring Annotations______________________________________________________ 1 Dependency Injection ________________________________________________________ 1

Dependencies Between Objects_______________________________________________________ 1 Example of a Direct Dependency _____________________________________________________ 1 Dependency Inversion ______________________________________________________________ 1 Dependency Injection (DI) in Spring __________________________________________________ 1 Injection with Autowired____________________________________________________________ 1 @Named/@Inject (JSR-330) Example _________________________________________________ 1 Dependency Injection Reduces Coupling _______________________________________________ 1 Advantages of Dependency Injection __________________________________________________ 1 Constructor Injection _______________________________________________________________ 1 Setter Injection vs. Constructor Injection _______________________________________________ 1 Qualifying Injection by Name ________________________________________________________ 1

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 4: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved ii

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 Using Java-based Configuration ______________________________________________________ 1 Dependency Injection ______________________________________________________________ 2 How Does it Work ? _______________________________________________________________ 2 Dependencies in Configuration Classes ________________________________________________ 2 Injecting Configuration Classes_______________________________________________________ 2 Other @Bean Capabiliites ___________________________________________________________ 2

Mini-Lab: Review Javadoc_______________________________________________________ 2 Integrating Configuration Types_______________________________________________ 2

XML and @Component Pro / Con ____________________________________________________ 2 Java-based Configuration: Pro / Con___________________________________________________ 2 Choosing a Configuration Style ______________________________________________________ 2 Integrating Configuration Metadata ___________________________________________________ 2 @Import: @Configuration by @Configuration___________________________________________ 2 <import>: XML by XML ___________________________________________________________ 2 Importing Between XML/@Configuration ______________________________________________ 2 Scanning for @Configuration Classes__________________________________________________ 2 Lab Options ______________________________________________________________________ 2

Lab 2.1: Java-based Configuration ________________________________________________ 2 Bean Scope and Lifecycle_____________________________________________________ 2

Bean Scope ______________________________________________________________________ 2 Specifying Bean Scope - XML _______________________________________________________ 2 Using @Scope to Specify Bean Scope _________________________________________________ 2 Bean Creation/Destruction Lifecycle __________________________________________________ 2 [Optional] Bean Creation Lifecycle Details _____________________________________________ 2 [Optional] BeanPostProcessor________________________________________________________ 2 [Optional] Event Handling __________________________________________________________ 2

Lab 2.2: Bean Lifecycle__________________________________________________________ 2 Externalizing Properties______________________________________________________ 2

Externalizing Values in Properties Files ________________________________________________ 2 Accessing Externalized Properties ____________________________________________________ 2 The Spring Environment ____________________________________________________________ 2 SpEL: Spring Expression Language Overview ___________________________________________ 2 Additional SpEL Examples __________________________________________________________ 2

Mini-Lab: Review SpEL Reference ________________________________________________ 2 Profiles ____________________________________________________________________ 2

Profile Overview __________________________________________________________________ 2 The First Configuration _____________________________________________________________ 2 Defining Second Configuration_______________________________________________________ 2 Using the Configurations____________________________________________________________ 2 Declaring Profiles - @Profile ________________________________________________________ 2 Enabling Profiles __________________________________________________________________ 2 Profiles - XML Configuration ________________________________________________________ 2 Profiles in JUnit tests_______________________________________________________________ 2

Lab 2.3: Profiles________________________________________________________________ 2

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 5: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved iii

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 Core Maven Concepts ______________________________________________________________ 2 The POM (Project Object Model) _____________________________________________________ 2 POM - Required Elements___________________________________________________________ 2 POM - External Dependencies _______________________________________________________ 2 Common Maven Artifacts for Spring __________________________________________________ 2 Repositories ______________________________________________________________________ 3 Maven Project Structure ____________________________________________________________ 3 Executing maven Goals_____________________________________________________________ 3

Spring Boot Overview _______________________________________________________ 3 Motivation for Spring Boot __________________________________________________________ 3 Spring Boot Project ________________________________________________________________ 3 Goals for Spring Boot Project ________________________________________________________ 3 How is Spring Boot Structured? ______________________________________________________ 3 Dependency Management with Spring Boot_____________________________________________ 3 Equivalent POM without Spring Boot__________________________________________________ 3 Configuration with Spring Boot ______________________________________________________ 3 Programming with Spring Boot_______________________________________________________ 3 Getting Started____________________________________________________________________ 3

Mini-Lab: Review Boot Reference _________________________________________________ 3 Mini-Lab: Spring Boot - Starter Projects ___________________________________________ 3

Spring Boot Hello World _____________________________________________________ 3 Our Goals for Hello World __________________________________________________________ 3 POM for Hello World ______________________________________________________________ 3 spring-boot-starter-parent ___________________________________________________________ 3 spring-boot-starter-parent POM Excerpt ________________________________________________ 3 spring-boot-dependencies POM Excerpt________________________________________________ 3 spring-boot-starter _________________________________________________________________ 3 spring-boot-starter POM Excerpt _____________________________________________________ 3 Summary ________________________________________________________________________ 3

Mini-Lab: Spring Boot - Brief Review of POMs______________________________________ 3 Hello World Overview _____________________________________________________________ 3 Hello World Code _________________________________________________________________ 3 Output of HelloBootWorld __________________________________________________________ 3 How it Works ____________________________________________________________________ 3 Easy Configuration with Properties____________________________________________________ 3 Executable Jar Packaging ___________________________________________________________ 3

Lab 1.1: Hello Boot World _______________________________________________________ 3 Recap of what we've seen ___________________________________________________________ 3

Session 4: Spring Testing ________________________________________________ 3 Lesson Objectives _________________________________________________________________ 3

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 6: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved iv

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 Order of Execution ________________________________________________________________ 3

[Optional] Lab 4.1: Using JUnit___________________________________________________ 3 Spring TestContext Framework _______________________________________________ 3

Spring TestContext Overview ________________________________________________________ 3 Common TestContext Types_________________________________________________________ 3 Using Spring's TestContext __________________________________________________________ 3 Context Management / Caching ______________________________________________________ 3 Using Spring Boot Test _____________________________________________________________ 3 Under the Hood ___________________________________________________________________ 4

Lab 4.2: Using Spring Testing ____________________________________________________ 4 Session 5: Database Access With Spring ____________________________________ 4

Lesson Objectives _________________________________________________________________ 4 Overview __________________________________________________________________ 4

Data Access Support _______________________________________________________________ 4 Datasources ______________________________________________________________________ 4 Example: Configuring a DataSource___________________________________________________ 4 Example: JNDI Lookup of a DataSource _______________________________________________ 4 Properties Files ___________________________________________________________________ 4 XML vs Java Config vs Properties Files ________________________________________________ 4

[Optional] Using Spring with Hibernate_________________________________________ 4 Hibernate Overview________________________________________________________________ 4 Hibernate Configuration File Illustration _______________________________________________ 4 Using Hibernate Directly____________________________________________________________ 4 Spring Support for Hibernate ________________________________________________________ 4 LocalSessionFactoryBean ___________________________________________________________ 4 Configuring a Hibernate Session Factory _______________________________________________ 4 Contextual Sessions________________________________________________________________ 4 Spring Free Repository Class ________________________________________________________ 4 Injecting the SessionFactory _________________________________________________________ 4

[Optional] Using Spring with JPA _____________________________________________ 4 JPA Overview and Architecture ______________________________________________________ 4 JPA Architecture – Key Types _______________________________________________________ 4 JPA: Entity Class__________________________________________________________________ 4 JPA: Persistence Unit Configuration___________________________________________________ 4 JPA: EntityManager _______________________________________________________________ 4 Spring Support for JPA _____________________________________________________________ 4 Managing the EntityManager[Factory] _________________________________________________ 4 1. JEE: Obtaining an EMF From JNDI _________________________________________________ 4 2. LocalContainerEntityManagerFactoryBean ___________________________________________ 4 Spring/JPA Integration Configuration__________________________________________________ 4 Example: XML Configuration________________________________________________________ 4 Example: @Configuration___________________________________________________________ 4 3. LocalEntityManagerFactoryBean ___________________________________________________ 4 JPA Repository / DAO _____________________________________________________________ 4

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 7: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved v

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

Using Spring Data___________________________________________________________ 4 How is Spring Data (JPA) Structured? _________________________________________________ 4 CrudRepository/JpaRepository Methods________________________________________________ 4 A Simple Event Entity______________________________________________________________ 4 The Event Repository Type__________________________________________________________ 4 Structure of our Repository __________________________________________________________ 4 Using the Repository _______________________________________________________________ 4 Using Other CrudRepository Methods _________________________________________________ 4

Lab 5.2: Using Spring Data ______________________________________________________ 4 Defining Queries Using Naming Conventions ___________________________________________ 4 More About Generated Queries_______________________________________________________ 4 More Complex Queries _____________________________________________________________ 4 Configuring Results________________________________________________________________ 5 Defining Queries with JPQL _________________________________________________________ 5

Lab 5.3: Writing Query Methods__________________________________________________ 5 Review Questions _________________________________________________________________ 5 Lesson Summary __________________________________________________________________ 5 Lesson Summary __________________________________________________________________ 5

Session 6: Transactions __________________________________________________ 5 Lesson Objectives _________________________________________________________________ 5

Spring Transaction Management ______________________________________________ 5 General Transaction (TX) Overview ___________________________________________________ 5 General Transaction Lifecycle________________________________________________________ 5 Spring's Transaction Managers _______________________________________________________ 5 Configuring Transaction Managers ____________________________________________________ 5 Spring's JTA Transaction Manager ____________________________________________________ 5 Spring Declarative TX Management ___________________________________________________ 5 Spring Transactional Scope__________________________________________________________ 5 Transaction Propagation ____________________________________________________________ 5 Transaction Attributes for Propagation _________________________________________________ 5 MANDATORY ___________________________________________________________________ 5 NESTED ________________________________________________________________________ 5 NEVER _________________________________________________________________________ 5 NOT_SUPPORTED _______________________________________________________________ 5 REQUIRED______________________________________________________________________ 5 REQUIRES_NEW ________________________________________________________________ 5 SUPPORTS ______________________________________________________________________ 5

Mini-Lab: Transaction Example __________________________________________________ 5 Transaction Attributes - Some Choices _____________________________________________ 5 Transaction Attributes - Some Choices _____________________________________________ 5

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 8: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved vi

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 [Optional] Pointcut-based Configuration________________________________________ 5

Spring Transactions and AOP ________________________________________________________ 5 Defining a Pointcut ________________________________________________________________ 5 Defining a Pointcut - XML __________________________________________________________ 5 Specifying Transactions Using XML __________________________________________________ 5 Specifying Transactions Using XML __________________________________________________ 5 Linking Advice With Pointcuts _______________________________________________________ 5 Resulting Behavioc ________________________________________________________________ 5 <tx:method> Attributes _____________________________________________________________ 5 Using Markers for Pointcuts _________________________________________________________ 5 Using a Marker Interface____________________________________________________________ 5 Using Marker Annotations __________________________________________________________ 5 Why Use Pointcut-based Configuration ________________________________________________ 5 More About Pointcut Expressions_____________________________________________________ 5 Sample execution Designator Patterns _________________________________________________ 6 Sample execution Designator Patterns _________________________________________________ 6 Other Spring AOP Designators _______________________________________________________ 6 Sample Designator Patterns__________________________________________________________ 6

[Demo] Lab 6.2: Pointcut-Based TX _______________________________________________ 6 Review Questions _________________________________________________________________ 6 Lesson Summary __________________________________________________________________ 6

Session 7: Web Applications and Spring MVC _______________________________ 6 Lesson Objectives _________________________________________________________________ 6

Integration with Java EE _____________________________________________________ 6 Spring and Java Enterprise Edition (JEE) _______________________________________________ 6 Overview of JEE Web Applications ___________________________________________________ 6 Web Application Structure __________________________________________________________ 6 Web Application Components________________________________________________________ 6 ApplicationContext and Java Web Apps________________________________________________ 6 Configuring ContextLoaderListener - XML _____________________________________________ 6 ContextLoaderListener - @Configuration_______________________________________________ 6 Using the Application Context _______________________________________________________ 6

Lab 7.1: Spring and the Web _____________________________________________________ 6 Spring MVC Basics__________________________________________________________ 6

What is Spring MVC? ______________________________________________________________ 6 General MVC Architecture __________________________________________________________ 6 MVC Pattern flow _________________________________________________________________ 6 Spring MVC Architecture ___________________________________________________________ 6 Plain Servlets/JSP Request Flow______________________________________________________ 6 Spring MVC Request Flow __________________________________________________________ 6 DispatcherServlet Initialization _______________________________________________________ 6 DispatcherServlet - Java Config ______________________________________________________ 6 Spring MVC Configuration - Java Config_______________________________________________ 6 DispatcherServlet - web.xml Config ___________________________________________________ 6

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 9: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved vii

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

View Resolvers _____________________________________________________________ 6 View Resolvers ___________________________________________________________________ 6 View Resolvers - Java Config ________________________________________________________ 6 Example: View Resolvers - Java Config ________________________________________________ 6 Java Config Simplified Configuration__________________________________________________ 6 Controller Using Logical Names______________________________________________________ 6 New Control Flow _________________________________________________________________ 6 Other View Resolvers ______________________________________________________________ 6 Configuring ResourceBundleViewResolver _____________________________________________ 6 Properties File - ResourceBundleViewResolver __________________________________________ 6 Mapping DispatcherServlet to /_______________________________________________________ 6 Controller Handling /_______________________________________________________________ 6

Lab 7.3: View Resolvers _________________________________________________________ 6 Controller Details ___________________________________________________________ 6

Request Parameters and Model Data___________________________________________________ 6 Sample Input Pages ________________________________________________________________ 6 @RequestParam – Parameter Binding _________________________________________________ 6 Returning Model Data ______________________________________________________________ 7 Class ModelAndView ______________________________________________________________ 7 Returning ModelAndView Example ___________________________________________________ 7 Model Argument Example __________________________________________________________ 7 Other Handler Method Capabilities____________________________________________________ 7 Example – Other Handler Capabilities _________________________________________________ 7

Lab 7.4: Client Input / Model Data ________________________________________________ 7 Review Questions _________________________________________________________________ 7 Lesson Summary __________________________________________________________________ 7 Lesson Summary __________________________________________________________________ 7

Session 8: More Spring MVC Capabilities ___________________________________ 7 Lesson Objectives _________________________________________________________________ 7

Forms and Model Objects ____________________________________________________ 7 Model Classes ____________________________________________________________________ 7 @ModelAttribute__________________________________________________________________ 7 Spring MVC Form Tags <form:form> _________________________________________________ 7 Spring MVC Form Tags <form:input> _________________________________________________ 7 Controller Data Binding - @ModelAttribute_____________________________________________ 7 Request Handling Flow _____________________________________________________________ 7 @ModelAttribute on Methods________________________________________________________ 7 Using Reference Data ______________________________________________________________ 7

Lab 8.1: Forms and Model Objects ________________________________________________ 7 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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 10: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved viii

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 Lesson Summary __________________________________________________________________ 7

Session 9: RESTful Services with Spring ____________________________________ 7 Lesson Objectives _________________________________________________________________ 7

REST Overview and Principles ________________________________________________ 7 Our Domain Model ________________________________________________________________ 7 REST – Representational State Transfer ________________________________________________ 7 REST Characteristics_______________________________________________________________ 7 REST Resources and Operations______________________________________________________ 7 REST in the Real World ____________________________________________________________ 7 REST Principles __________________________________________________________________ 7 REST Principles __________________________________________________________________ 7

Requests and Responses ______________________________________________________ 7 REST APIs ______________________________________________________________________ 7 URI Templates____________________________________________________________________ 7 REST API with URI Template _______________________________________________________ 7 GET – Retrieve All Items ____________________________________________________________ 7 GET – Retrieve Specific Item_________________________________________________________ 7 POST – Create New Item ____________________________________________________________ 7 PUT – Update Existing Item _________________________________________________________ 7 DELETE – Delete Existing Item _______________________________________________________ 7 Some Additional Points_____________________________________________________________ 7 Summary of REST Characteristics ____________________________________________________ 8

REST in Action – Mini-Lab ______________________________________________________ 8 REST with Spring MVC _____________________________________________________ 8

Spring Support for REST ___________________________________________________________ 8 A Simple Resource Class Example ____________________________________________________ 8 URI Templates and @PathVariable ___________________________________________________ 8 Generating a Response - @ResponseBody ______________________________________________ 8 @ResponseBody Example __________________________________________________________ 8 Other URI Path Mapping Capabilities__________________________________________________ 8 @RestController __________________________________________________________________ 8 But How Does It Work? ____________________________________________________________ 8 Accessing REST Resources__________________________________________________________ 8

Lab 9.1: A Simple REST Resource ________________________________________________ 8 Ajax Overview______________________________________________________________ 8

Ajax-JavaScript and REST Resources__________________________________________________ 8 Classic User Interaction – Synchronous ________________________________________________ 8 Ajax User Interaction – Asynchronous _________________________________________________ 8 Working with Ajax-JavaScript _______________________________________________________ 8 Ajax and REST Resources __________________________________________________________ 8

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 11: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved ix

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

Lab 10.1: A JSON Resource ______________________________________________________ 8 Generating XML____________________________________________________________ 8

XML Review_____________________________________________________________________ 8 Introducing JAXB _________________________________________________________________ 8 @XmlRootElement and Default Mapping ______________________________________________ 8 Default JAXB Mapping – Example____________________________________________________ 8 Serializing Data to XML ____________________________________________________________ 8 Using @XmlRootElement___________________________________________________________ 8 Serializing Collections to XML_______________________________________________________ 8 Summary: XML Serialization Requirements ____________________________________________ 8

Content Negotiation _________________________________________________________ 8 Content Negotiation Overview _______________________________________________________ 8 Accept Headers: What the Client Asks For______________________________________________ 8 Determining Client's Data Format_____________________________________________________ 8 Configuring Controller's Data Types___________________________________________________ 8

Lab 10.2: An XML Resource _____________________________________________________ 8 Review Questions _________________________________________________________________ 8 Lesson Summary __________________________________________________________________ 8

Session 11: Java Clients for RESTful Services _______________________________ 8 REST Client Requirements __________________________________________________________ 8 RestTemplate Example _____________________________________________________________ 8 Common RestTemplate Methods _____________________________________________________ 8 getForObject() in Detail_____________________________________________________________ 8 RestTemplate Method Variations _____________________________________________________ 8 getForObject() Using Map___________________________________________________________ 8 Other RestTemplate Method Details ___________________________________________________ 8

Lab 11.1: A Client Using RestTemplate ____________________________________________ 9 RestTemplate.getForEntity() _________________________________________________________ 9 Using HttpEntity and ResponseEntity __________________________________________________ 9 Accessing Headers_________________________________________________________________ 9 RestTemplate.exchange() ___________________________________________________________ 9 Setting Headers on a Request ________________________________________________________ 9 Error Handling____________________________________________________________________ 9 Summary of RestTemplate Usage _____________________________________________________ 9

Lab 11.2: [Optional] Setting / Accessing Headers_____________________________________ 9 Lesson Summary __________________________________________________________________ 9

Session 12: Common REST Patterns _______________________________________ 9 The REST Methods ________________________________________________________________ 9 GET: Retrieve Information __________________________________________________________ 9 POST: Add New Information ________________________________________________________ 9 Server: POST Controller - Details_____________________________________________________ 9 Server: Setting Location Header for POST ______________________________________________ 9 Client: RestTemplate for POST_______________________________________________________ 9 PUT: Update Information ___________________________________________________________ 9

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 12: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Copyright © LearningPatterns Inc. All rights reserved x

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 Default Interface Methods___________________________________________________________ 9 Candidate Component Index _________________________________________________________ 9 @Nullable and @NonNull __________________________________________________________ 9

WebFlux (Reactive Systems) __________________________________________________ 9 Reactive Programming Overview _____________________________________________________ 9 Iterator (Pull) - Synchronous _________________________________________________________ 9 Observer (Push) - Asynchronous______________________________________________________ 9 Reactive Programming - Observer+ ___________________________________________________ 9 Spring Reactor / WebFlux Frameworks ________________________________________________ 9 Note: Java 8 Lambda/Stream Usage ___________________________________________________ 9 WebFLux API and REST Example____________________________________________________ 9 Example: Reactive Resource_________________________________________________________ 9 Example: Reactive Client (Flux) ______________________________________________________ 9 Example: Reactive Client (Mono)_____________________________________________________ 9 Recap___________________________________________________________________________ 9

[Optional] Lab 13.1: WebFlux Demo_______________________________________________ 9 [Optional] Session 14: XML Specific Configuration ___________________________ 9

Lesson Objectives _________________________________________________________________ 9 Collection Valued Properties_________________________________________________________ 9 Working with Collections ___________________________________________________________ 9 Collection Property Example_________________________________________________________ 9 Configuring <list> and <set> Properties ________________________________________________ 9 Configuring Collection of Bean References _____________________________________________ 9 Map Valued Properties _____________________________________________________________ 9 Other Capabililties_________________________________________________________________ 9 Bean Definition Inheritance__________________________________________________________ 9 Inheritance Example _______________________________________________________________ 9 Factory Classes ___________________________________________________________________ 9 Instance Factory Methods ___________________________________________________________ 9 Autowiring with XML______________________________________________________________ 9 Inner Beans _____________________________________________________________________ 10 Compound Names ________________________________________________________________ 10

Recap _______________________________________________________________ 10 Recap of what we've done __________________________________________________________ 10 What Else is There________________________________________________________________ 10 Resources_______________________________________________________________________ 10

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 13: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

1

Introduction to Spring 5 and Spring MVC/REST

Introduction to Spring 5 and Spring MVC/REST

Version: 20180521-b

Version: 20180521-b

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 14: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

2

Introduction to Spring 5 and Spring MVC/REST

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

The course covers the following areas of Spring technology

– Core features of Spring– Spring Boot– Data Access Features Including Spring Data– Transaction Support– Web Application Support including Spring MVC– Building RESTful Resources with Spring MVC

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 15: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

3

Introduction to Spring 5 and Spring MVC/REST

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– XML, Java-based, and annotation-based config

Spring Boot: For easier dependency management and configurationData Access: Data access via Spring's data support– DataSource support– Hibernate and JPA-based Repositories/DAOs– Spring Data based repositories

Transactions: Controlling transactions declaratively with Spring– Via both Spring annotations and XML configuration

Web: Integrating Spring with Web applications. Understand and use Spring MVC/REST

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 16: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

4

Introduction to Spring 5 and Spring MVC/REST

Workshop Agenda

Session 1: Introduction to Spring

Session 2: Configuration in Depth

Session 3: Intro to Spring Boot

Session 4: Spring Testing

Session 5: Database Access With Spring

Session 6: Transactions

Session 7: Web Applications and Spring MVC

Session 8: More Spring MVC Capabilities

Session 9: RESTful Services with Spring

Session 10: Working with JSON and XML

Session 11: Java Clients for RESTful Services

Session 12: Common REST Patterns

[Optional] Session 13: Additional New Features

[Optional] Session 14: XML Specific Configuration

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 17: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

5

Introduction to Spring 5 and Spring MVC/REST

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()

–We bold/color text for emphasis

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

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

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

package com.javatunes.teach;

public class CatalogImpl implements Catalog {public void speakTruth() {

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

}

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

We might also put related information that generally pertains to the material covered in the slide.

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 18: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

6

Introduction to Spring 5 and Spring MVC/REST

Labs

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– The lab details are separate from the main manual pages

Setup zip files are provided with skeleton code for the labs– Students add code focused on the topic they're working with– There is a solution zip with completed lab code

Lab slides have an icon like in the upper right corner of this slide– The end of a lab is marked with a stop like this one:

Lab

STOP

Introduction

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 19: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

7

Introduction to Spring 5 and Spring MVC/REST

Session 1: Introduction to Spring

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 20: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

8

Introduction to Spring 5 and Spring MVC/REST

Lesson Objectives

Understand why we need the Spring Framework

Understand what Spring does, and how it simplifies enterprise application development

Learn how Spring uses configuration information and Dependency Injection (DI)– To manage the beans (objects) in an application– To manage bean dependencies

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 21: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

9

Introduction to Spring 5 and Spring MVC/REST

Overview

OverviewSpring Introduction

The Spring ContainerDependency Injection

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 22: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

10

Introduction to Spring 5 and Spring MVC/REST

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)

Spring: Lightweight framework to build enterprise apps– Non-intrusive, use only what you need, supports advanced capabilities

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

dependencies– DAO/Repository/Transaction support for persistent data– ORM support (Object-relational mapping, e.g. JPA)– AOP: Aspect-oriented programming– Web: Integration with standard JEE Web apps– Spring MVC: Model-View-Controller Web framework– Security: Authentication and authorization

There really is no formal definition of an enterprise application.Typically though, some of the characteristics they have are:

– Used in a business environment, often in business-critical domains.– Have some form of persistent storage.– Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc).– Require some measure of scalability and fault tolerance.

The definition of enterprise application is not important.– Many Java applications share some of the requirements that we are outlining here.

DAO: Data Access Object.

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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 23: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

11

Introduction to Spring 5 and Spring MVC/REST

The Spring Modules

Module diagram from the Spring Reference Documentation

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 24: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

12

Introduction to Spring 5 and Spring MVC/REST

The Spring Distribution

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

Distributed as modules in separate jars– e.g. spring-beans-5.0.5.RELEASE.jar– Has external dependencies - e.g. logging, JUnit, etc. (1)

– Generally use a tool like maven for dependencies• We supply jars the jars for some labs, and use maven in others

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

– JEE similarly supports enterprise apps• e.g. CDI for lifecycle / dependency injection

– Which to use? What works best• Based on your current and future system needs

– You might use both - e.g. a JEE Web container• With Spring for lifecycle management and DI• Or Spring MVC layered on top of JEE Servlets/JSP

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

– These are no longer provided.– It is assumed that you'll use a build tool like maven to get the Spring libraries and its

dependencies.

(1) The external dependencies for the core modules for dependency injection are (purposely) minimal.– Basically you just have a logging framework.– For other capabilities (e.g. AOP) there are more dependencies, but they're still rather small.– If you use other technologies however, e.g. Hibernate/JPA, then there are more external

dependencies .

(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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 25: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

13

Introduction to Spring 5 and Spring MVC/REST

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,

use maven for dependencies

These are external dependencies (2)

– Again, just a subset of what we'll need in later labs

(1) We supply the Spring project jars needed for the early labs in the lab setup.– We downloaded these using maven and a pom.xml specifying the different modules available in

Spring (e.g. spring-context) then gathered the jars together for the lab setup.– The dependencies were done in the same way.– Note that the actual jars in the lab setup may vary from this illustration - look at the setup to see

what is actually used.– Note that the junit and hamcrest jars are not needed by Spring, but needed because we use JUnit

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

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

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 26: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

14

Introduction to Spring 5 and Spring MVC/REST

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)

JUnit capabilities include:– Annotations for declaring test methods (e.g. @Test)– Assertions for testing expected results– Test fixtures for sharing common data– Test runners for running tests

See next slide for an example– We'll review in more depth in the Testing session

Most development environments have JUnit support– We'll use them to run tests which drive the lab code– The tests are the @Test annotated methods (see next slide)

We are using JUnit to drive our slide examples and lab code because it's convenient.– And also because it gives an easy way to test lab results.– However, since this is a class for learning new things, we often want some console indication of

what's going on, so we'll produce some console output in our test classes.– That's not usually done in test classes written explicitly for testing, but it's good for our purposes.– We don't need to adhere to any particular testing practices - our test cases are lab-oriented, not

for system testing.– Where appropriate, we do adhere to standard conventions - e.g. in naming our test classes and

test methods.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 27: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

15

Introduction to Spring 5 and Spring MVC/REST

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)

Note the @Test on testContextNotNullPositive()– The test creates the application context, and checks that it's non-null– We use org.junit.Assert.assertNotNull to perform the test– See notes about import static and assertTrue usage

// JUnit relevant code shown - some imports / code omitted import static org.junit.Assert.*;import org.junit.Test;

public class SpringTests {@Testpublic void testContextNotNullPositive() {

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

}}

The assertXXX methods are all static method of Assert.– The familiar way to use these methods would be to import org.junit.Assert, and then call

the static methods through the Assert class.Assert.assertTrue(collection.isEmpty());

– This is a little cumbersome, so the static import feature of Java is used - which imports static members from a class.

– The following import statement imports all the static members (including methods) from the Assert class.

import static org.junit.Assert.*;

– This allows us to use the static members without qualifying them by the classname, as seen in our earlier code.

assertTrue(collection.isEmpty());

There is much more capability in JUnit.– 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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 28: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

16

Introduction to Spring 5 and Spring MVC/REST

Lab 1.1: Setting Up the Environment

In this lab you'll set up the lab environment, boot the Spring container, and test it with a unit test

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 29: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

17

Introduction to Spring 5 and Spring MVC/REST

Spring Introduction

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 30: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

18

Introduction to Spring 5 and Spring MVC/REST

Managing Beans: Core Spring Capability

Beans: Fancy name for application objects– They're POJOs (Plain Old Java Objects)

The Spring container is the "manager"– Uses configuration information (metadata) to define,

instantiate, configure, and assemble beans• Metadata: Information about your beans (e.g. bean definitions)

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

Configuration choices include XML and annotations– XML: The "classic" configuration from early Spring– Two annotation choices (@Component, @Configuration)– We'll cover all of these

The term bean doesn't mean that much - it's a common name (e.g. JavaBeans and EJB).– Here, we use it to mean an object managed by the Spring container.

Spring Container: Software environment to manage beans and other capabilities.– Also called the Dependency Injection (DI) or Inversion of Control (IoC) container.– Programming to Spring basically means interacting with this software environment.

(1) Spring will create and initialize bean instances based on your configuration data.– You can then request those instances from the Spring container by type or name.– We'll see how this works soon.

Configuration metadata can also be provided in the Java properties format, or even provided programmatically (using Spring's public API).

– 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.– 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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 31: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

19

Introduction to Spring 5 and Spring MVC/REST

A Basic Spring Application

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 32: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

20

Introduction to Spring 5 and Spring MVC/REST

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:

– com.javatunes.domain.MusicItem : JavaBean-style value class representing a music item (e.g. an mp3)

– com.javatunes.service.Catalog : Interface defining JavaTunes catalog functionality (including search)

– com.javatunes.service.CatalogImpl : Concrete Catalogimplementation (uses ItemRepository)

– com.javatunes.persistence.ItemRepository : Interface defining data access API for items

– com.javatunes.persistence.InMemoryItemRepository : Concrete ItemRepository implementation (simple in-memory storage)

(1) We use a simple online music store as our domain for examples in the slides and for the labs.– We've tried to give it enough detail to provide good material to work with while keeping it

simple enough so you don't have to spend too much time in figuring it out.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 33: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

21

Introduction to Spring 5 and Spring MVC/REST

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

package com.javatunes.service;

public interface Catalog {public MusicItem findById (long id);public Collection<MusicItem> findByKeyword(String keyword);public long size();

}

package com.javatunes.service;

public class CatalogImpl implements Catalog { // Detail omitted

public MusicItem findById (long id) { /* */ }public Collection<MusicItem> findByKeyword(String keyword){ /* */ }

public long size() { /* */ }}

These two types are part of JavaTunes.– We'll use them to motivate our discussion on how Spring works.

(1) Programming to interfaces provides many advantages by decoupling your code from concrete implementation classes.

– This is not a concept unique to Spring.– Many design patterns are based on the decoupling gained by programming to an interface.– We'll soon see how the Spring framework makes these advantages even more usable and

powerful by helping manage the dependencies that have been abstracted using interfaces.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 34: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

22

Introduction to Spring 5 and Spring MVC/REST

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• Generally specify id (a name) and class (fully qualified class name) (2)

– Supports other configuration also - we'll cover it as we encounter itAt bottom, we define one bean with XML (the metadata)Many existing applications use XML– But annotation-based approaches now recommended

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

<!-- The beans namespace is the default one for the document --><beans xmlns="http://www.springframework.org/schema/beans"

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

http://www.springframework.org/schema/beans/spring-beans.xsd">

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

</beans>

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

– In fact, as we'll see, you can have multiple config files.(2) There are more sophisticated ways to create beans, for example with a factory class (shown later), in

which case the class name may not be the actual implementation class.Spring provides an XML Schema for this configuration file, and the examples and lab setup files have the necessary XML namespace information in them to refer to this schema.

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

– Refer to an XML reference if you need more detail on this.The xsi:schemaLocation property in the slide doesn't specify a version number for the schema.

– The latest version will automatically be picked up.– 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).

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 35: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

23

Introduction to Spring 5 and Spring MVC/REST

The Spring Container

The Spring container– Reads your configuration, and based on it:

• Instantiates/initializes application objects• Resolves object dependencies

org.springframework.context.ApplicationContext– Core API to access the Spring container in your code– Several implementations with different capabilities, e.g.– ClassPathXmlApplicationContext: Loads XML resources

from the class path

Interface ApplicationContext extends BeanFactory– BeanFactory has many core methods - usually not used directly

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

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 36: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

24

Introduction to Spring 5 and Spring MVC/REST

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

Next, we look up our configured bean via the context– Looked up by type (Catalog.class) - can look up by name also (1)

– We do any needed work, then close the context

import org.springframework.context.support.ClassPathXmlApplicationContext;

// Code fragment - other imports and much detail omitted ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");

// Note that getBean uses Java generics (no casting needed)Catalog cat = ctx.getBean(Catalog.class);// Or lookup by name: ctx.getBean("musicCatalog", Catalog.class);

MusicItem item = cat.findById(1L); // Use our beanctx.close(); // Close the context

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

– When the instance is created, it reads the configuration.– Based on the configuration, it does whatever work it needs to get ready to supply you with beans.– We then use that context instance to interact with the container.– It contains the API that you have access to.

(1) It's generally easier and more reliable to look up beans by their type.– However, sometimes that's not practical or possible - for example when there is more than one

concrete implementation of an interface.– We'll see bean lookup by name later.

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" );

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 37: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

25

Introduction to Spring 5 and Spring MVC/REST

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

Can use any implementation in our configuration– Client code will not change– That's why we code to interfaces, not concrete types

Bean lifecycle is managed by container– We don't instantiate our beans directly

Very useful for more complex systems– We'll see more useful capabilities soon

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

– What is the benefit?

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

– We'll see how useful it can be when we explore more of the capabilities.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 38: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

26

Introduction to Spring 5 and Spring MVC/REST

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

Initialize the Spring container– e.g. create an application context instance to read config data – It will initialize the beans in the config file(s)

Retrieve beans via the context instance and use them– e.g. use getBean() to look up a bean by type or name– Lookup by type is preferred, unless you can't do it

• For instance, if you have two beans implementing the same type

There are many, many usage scenarios for Spring.– And many, many different alternatives for each scenario– Spring is very large, and has a lot of flexibility and capability

In this initial introduction we show you one straightforward way of using Spring.– We will gradually introduce more capabilities throughout the course.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 39: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

27

Introduction to Spring 5 and Spring MVC/REST

More on ApplicationContext

Access point for many Spring capabilities, including:– Bean access– Resource Access: Config files, URLs, other files– Message resources with I18N capability– Publishing events to managed beans that are listeners– Multiple, hierarchical contexts

ClassPathXmlApplicationContext– Loads XML config files from the classpathFileSystemXmlApplicationContext– Loads XML config files from the file system or URLs– Both in org.springframework.context.support

AnnotationConfigApplicationContext– Accepts annotated classes as input (more on this later)– In org.springframework.context.annotation

The ApplicationContext is the full-fledged representation of the Spring container.– It is often regarded as the type that supplies the "framework" capabilities of Spring, rather than

simple bean management.If you are writing applications for a very resource-restricted environment, such as a mobile device, you might consider using BeanFactory over ApplicationContext.

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

There are also Web-based application contexts we'll cover later.We'll cover the ApplicationContext API in various parts of the course.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 40: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

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– Class<?> getType(String name): Get type of named bean– boolean isSingleton(String): Is bean a singleton– String[] getAliases(String): Get any aliases for this bean– Many more methods - see the javadoc

Can specify config files in multiple ways– ant-style wildcards: e.g. conf/**/ctx.xml - All ctx.xml files under conf– file: and classpath: prefixes - forces use of specified location, e.g.

• The following loads from the classpath:• new FileSystemXmlApplicationContext("classpath:ctx.xml");

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

The methods shown are a part of the BeanFactory API inherited by ApplicationContext.getBean returns either a singleton (shared) instance, or a newly created bean.– NoSuchBeanDefinitionException thrown if the bean can't be found– BeansException thrown if an exception occurred while instantiating/preparing the bean– BeanNotOfRequiredTypeException thrown if the bean is not of the required type

Object getBean(String) returns an object – which is then cast to the required type.– The newer getBean(String,Class<T> requiredType) method is generally preferred.

getType(String) throws NoSuchBeanDefinitionException if the bean can't be found.isSingleton(String) throws NoSuchBeanDefinitionException if bean can't be found.The method <T> T getBean(String, Class<T> requiredType) may look strange.

– 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>.

– 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.

28

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

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 41: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

29

Introduction to Spring 5 and Spring MVC/REST

Mini-Lab: Review Javadoc

Mini-LabWe provide the Spring Javadoc– Under StudentWork/Spring/Resources/SpringDocs/javadoc

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

Review the javadoc for the following types– BeanFactory

– ApplicationContext

– ClassPathXmlApplicationContext (especially the constructors)– FileSystemXmlApplicationContext (especially the constructors)

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 42: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

30

Introduction to Spring 5 and Spring MVC/REST

Lab 1.2: Hello Spring World

In this lab, we will create and use a Spring context to access a bean instance

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 43: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

31

Introduction to Spring 5 and Spring MVC/REST

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– We'll use Spring style annotations in this course (1)

Below, @Component declares CatalogImpl as a bean– Specifies id as musicCatalog (Default id: catalogImpl)

• Same bean as previous XML example– Could also have used @Named("musicCatalog")

import org.springframework.stereotype.Component;

package com.javatunes.service;

@Component("musicCatalog") // Declares bean with id musicCatalogpublic class CatalogImpl implements Catalog { /* Most detail omitted … */}

(1) Common usage in Spring projects is to use the Spring-based annotations.– Some advocate the usage of JSR-330 annotations since they are a Java standard.– This would (theoretically) allow you to port to another container that uses JSR-330 annotations -

for example JEE and its CDI capabilities.• However, this would entail a lot more work than just the annotations on the beans, so we

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

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

– All these considerations lead us to choose the Spring-standard annotations over the JSR-330 annotations when working with Spring.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 44: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

32

Introduction to Spring 5 and Spring MVC/REST

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)

– e.g. @Component

Annotations don't directly affect program semantics– They are not executable code

Tools work with the annotated code– And may affect the semantics of a running program– @Named/@Component annotated beans are recognized as bean

defs by the Spring container

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

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

Annotations can replace many "side files" – e.g. XML deployment descriptors.– It's easier for tools to read the metadata and source if they're all in one place.– They're often used for specifying details of high-level technologies (e.g. AOP, EJB, Web

Services …).– These often result in code generation.

Annotations are present in the class file, and can be read by tools.– The JDK also comes with a command line utility, called apt (Annotation Processing Tool), that

can be used to process annotations.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 45: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

33

Introduction to Spring 5 and Spring MVC/REST

Enabling Annotations / Detecting Beans

Spring can automatically scan for annotated beans on the classpath– This registers them as normal beans

Enable auto scanning via <context:component-scan/>– A standard element from Spring's context namespace (see next slide)– Includes the capabilities of <context:annotation-config/> (1)

– basePackage attribute configures the packages to scan<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd">

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

</beans>

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

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

– It only affects beans that are already registered.– component-scan element in the slide example will scan for all components in the

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

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

There are other attributes to component-scan, including– 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

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 46: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

34

Introduction to Spring 5 and Spring MVC/REST

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

Spring namespaces include:– aop: Configures AOP support– beans: The standard bean tags we've seen already– context: Configures ApplicationContext related things– jee: JEE related configuration such as looking up a JNDI object– jms: Configures JMS related beans– lang: Exposing objects written in language like JRuby as beans– tool: Adds tooling-specific metadata– tx: Configures transaction support– util: Common, utility configuration issues

(1) We've seen the usage of <context:component-scan> previously.– It is is a shorthand to introduce a number of bean definitions into the configuration.– The tags in these schemas typically have capabilities beyond simple bean definitions and

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

easier.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 47: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

35

Introduction to Spring 5 and Spring MVC/REST

Lab 1.3: Spring Annotations

In this lab, we'll work with Spring Annotations

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 48: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

36

Introduction to Spring 5 and Spring MVC/REST

Dependency Injection

OverviewSpring Introduction

Dependency Injection

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 49: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

37

Introduction to Spring 5 and Spring MVC/REST

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

Direct dependencies have several issues– Rigid: Changes affect other areas, so are hard to make– Fragile: Changes cause unexpected failures in other areas– Immobile: Hard to reuse functionality

• Modules can't be disentangled

We'll illustrate a direct dependency – Then show an alternative approach

(1) In straightforward applications, Object A will often just create an instance of Object B and use it.– Object A is highly coupled to, and directly dependent on, Object B.– This is initially an easy way to structure a system, but often not the best way.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 50: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

38

Introduction to Spring 5 and Spring MVC/REST

Example of a Direct Dependency

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

public class CatalogImpl implements Catalog {InMemoryItemRepository rep = new InMemoryItemRepository();public MusicItem findById(long ID) {

return rep.get(id);}

}

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

}

Assume we want to get our information from a class called FileRepository.– Assume it also has a get(Long id) method.

In that case, CatalogImpl might need to be changed to something like that below.

public class CatalogImpl implements Catalog {

FileRepository rep = new FileRepository();

public MusicItem findById(long id) {

return rep.get(id);

}

}

– This is not such a big deal if you have to change it in one place.– 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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 51: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

39

Introduction to Spring 5 and Spring MVC/REST

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)• CatalogImpl need not change - the modules are decoupled

public class CatalogImpl implements Catalog {private ItemRepository itemRepository; // get/set methods not shownpublic MusicItem findById(Long id) { return itemRepository.get(id); }

}

// Much detail omitted …public class InMemoryItemRepository implements ItemRepository { /*…*/ }

public interface ItemRepository {public MusicItem get(Long id);

}

// Code fragment - most detail omittedInMemoryItemRepository rep=new InMemoryItemRepository();CatalogImpl catalogImpl=new CatalogImpl();catalogImpl.setItemRepository(rep);MusicItem found = catalogImpl.findById(1);

Dependency Inversion is not a new idea.– The idea of "Programming to Interfaces" has been around since long before Java.– It has been used in non-OO languages also, for example the stdio module in the C programming

language abstracted away the details of the actual devices doing the output.We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use.We talk of modules here, which in this example result in dependencies between different classes.In the example, we see that CatalogImpl knows nothing about InMemoryItemRepository.

– It only depends on the ItemRepository interface (the abstraction).– When CatalogImpl is created, you initialize it with an instance of an ItemRepository

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

InMemoryItemRepository also depends on the abstraction (it implements ItemRepository ).– 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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 52: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

40

Introduction to Spring 5 and Spring MVC/REST

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– Spring initializes the dependencies ("injects" them) based on the config– No need to explicitly initialize dependencies in your code

We illustrate XML config of this below (injecting via a set method)– <property …> injects into the catalog's itemRepository property– Automatically done when the container creates the bean

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

<bean id="inMemoryRepository"class="com.javatunes.persistence.InMemoryItemRepository"/>

<bean id="musicCatalog" class="com.javatunes.service.CatalogImpl"><property name="itemRepository" ref="inMemoryRepository"/>

</bean>

</beans>

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 53: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

41

Introduction to Spring 5 and Spring MVC/REST

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)– We're ready to work !

import org.springframework.stereotype.Component;import org.springframework.beans.factory.annotation.Autowired;

@Component("musicCatalog") // Declares bean - most detail omittedpublic class CatalogImpl implements Catalog { @Autowired // can also apply to setter method or constructorprivate ItemRepository itemRepository;

}

public class CatalogTests { // imports, other detail omitted@Test testCatalogFindById() {ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Catalog cat = ctx.getBean(Catalog.class); // See note (1)

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

(1) The bean lookup with the code shown directly below works because there is only one bean that implements Catalog, so the container can find this bean by type.ctx.getBean( Catalog.class );

–We'll see ways to refine this type of lookup later.Note that CatalogImpl and InMemoryItemRepository didn't need anything special to support Spring's DI.

–They just need to be written according to the design principles of Dependency Inversion (i.e. coding to an interface, not a concrete type) which is good practice anyway.–Once this was done, we didn't need any special capabilities to support DI.

Note also that there is nothing in your CatalogTests code which shows that CatalogImpldepends on InMemoryRepository.

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

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 54: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

42

Introduction to Spring 5 and Spring MVC/REST

@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– And the test client would look exactly the same

We'll use @Component style going forward, as mentioned earlier– It's the more common choice

import javax.inject.Inject;import javax.inject.Named;

@Named("musicCatalog") // Declares bean - most detail omittedpublic class CatalogImpl implements Catalog { @Inject private ItemRepository itemRepository;

}

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 55: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

43

Introduction to Spring 5 and Spring MVC/REST

Dependency Injection Reduces Coupling

The simplest case, CatalogImpl coupled to InMemoryItemRepository

CatalogImpl coupled to ItemRepository only (Dependency Inversion)– CatalogTests coupled to CatalogImpl and InMemoryItemRepository

Using DI – CatalogTestsonly coupled to Catalog– CatalogImpl only coupled

to ItemRepository

CatalogImpl InMemoryItemRepository

ItemRepository<<interface>>

creates

CatalogImpl

InMemoryItemRepositoryCatalogTestsimplements

creates

ItemRepository<<interface>>

CatalogTests

Catalog<<interface>> CatalogImpl

implements

looks up

ApplicationContext

injects

In the slide, we show diagrams of the three different ways we structured our code in the earlier slides.– In the first, CatalogImpl is directly coupled to InMemoryItemRepository.– In the second, CatalogTests is doing the dependency injection of the

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

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

to abstract interfaces.

In the Spring DI version, all the dependencies in the code are ONLY to interfaces.– This is much better than being coupled to actual implementation classes.– It increases flexibility, testability, and ease of maintenance.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 56: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

44

Introduction to Spring 5 and Spring MVC/REST

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:– CatalogImpl is not coupled to InMemoryItemRepository– CatalogTests is not coupled to CatalogImpl or InMemoryItemRepository

The dependencies are still there but not in the code– Dependencies are moved to the spring configuration– They're injected into beans without you coding it– Commonly referred to as wiring beans together

This leads to more flexible code that is easier to maintain– At a cost – using Spring, and maintaining the spring configuration

Coupling is the measure of how much a module of code relies on other modules.– Loosely coupled code is generally considered better code.

Consider some of the following scenarios, and how DI makes them easier.– Testing your code with a testing framework such as JUnit can be much easier with DI – you can

configure the application to use mock objects wherever you want – without changing your code at all.

– Testing different versions of classes can be done just by changing the configuration metadata.– In fact, any implementation class that implements the particular interfaces being used can be

swapped into your program simply by changing the configuration information.There is debate about how worthwhile DI and frameworks like Spring are.

– However, the principles that it is based on that lead to loose coupling are widely accepted.– Spring simply makes it easier to apply these principles.– 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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 57: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

45

Introduction to Spring 5 and Spring MVC/REST

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 constructorSee notes for some additional detail/capabilities

public class CatalogImpl implements Catalog { // Most detail omittedpublic CatalogImpl(ItemRepository repository) { /* … */ }

}

<!-- XML config - Other detail omitted --><bean id="musicCatalog"

class="com.javatunes.service.CatalogImpl"><constructor-arg ref="itemRepository"/> <!-- inject via ctor -->

</bean>

public class CatalogImpl implements Catalog { // Most detail omitted@Autowired // Inject into ctor belowpublic CatalogImpl(ItemRepository repository) { /* … */

}

For @Autowired, if there is only one constructor, you can even leave out @Autowired.– It will be inferred - but we believe it's better practice to include it explicitly.

If a constructor has multiple arguments, they will all be injected with @Autowired.– For example, assuming that a CatalogImpl needs an ItemChecker to do some sanity

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

public CatalogImpl(ItemRepository rep, ItemChecker checker)

In XML, multiple arguments would be handled with multiple <constructor-arg>s.<bean id="musicCatalog" <!-- inject two ctor arguments -->

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

<constructor-arg ref="itemRepository"/>

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

</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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 58: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

46

Introduction to Spring 5 and Spring MVC/REST

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

Setter Injection Cons– Doesn't guarantee property initialization (Forget to do it - BUG!)– Setter methods are required

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

– Good for required properties (can be immutable if setter omitted)Constructor Injection Cons– Unwieldy and Brittle: Multiple constructors with multiple args unwieldy

• Refactor if you have this– Less flexible: Need ctors for each scenario, and can't reset properties

(1) If you leave out a constructor argument while configuring a bean, you'll have an error.– If using XML configuration or @Autowired, you'll get a runtime exception as soon as the code

is run.

You can mix constructor and setter injection.– For example, using constructor injection on required properties, and setter injection on other

properties.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 59: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

47

Introduction to Spring 5 and Spring MVC/REST

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– It injects based on the bean name

@Component // Declare as bean - default id inMemoryItemRepositorypublic class InMemoryItemRepository implements ItemRepository {…}

@Component // Declare as bean - default id cloudItemRepositorypublic class CloudItemRepository implements ItemRepository {…}

@Component public class CatalogImpl implements Catalog { // Autowire@Autowired private ItemRepository itemRepository; // FAILS!

}

import org.springframework.beans.factory.annotation.Qualifier;

@Component public class CatalogImpl implements Catalog { // Autowire@Autowired @Qualifier("cloudItemRepository")private ItemRepository itemRepository; // Injects the Cloud-based

}

In the first example of injection, where the autowiring is done by type, it fails at runtime.@Autowired private ItemRepository itemRepository; // FAILS!

–The container doesn't know which of the two possible types to use.In the second example of injection we use @Qualifier to supply a bean name.

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

@Qualifier("cloudItemRepository")

private ItemRepository itemRepository; // Injects the Cloud-based

There are other, more sophisticated, ways to qualify an injection.–This involves defining your own qualifiers, for example @CloudBased instead of using names.–This is compile-time safe, as it is not a string-based approach, so useful for program correctness.–However, it's fairly complex, and arguably the complexity is often not worth the benefit.–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.

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 60: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

48

Introduction to Spring 5 and Spring MVC/REST

Lab 1.4: Dependency Injection

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

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 61: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

49

Introduction to Spring 5 and Spring MVC/REST

Review Questions

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

What is Dependency Inversion?

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

What is an ApplicationContext?

How does Spring use annotations on your bean classes for defining and wiring beans?– What are the pros/cons of using them?

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 62: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

50

Introduction to Spring 5 and Spring MVC/REST

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

Manages complex dependencies - non-intrusive and lightweight– Supports loose coupling between components– Encourages coding to interfaces (good design)

• Also called Dependency Inversion

Uses configuration metadata to initialize beans and dependencies– Via XML configuration files or annotations

Dependency Injection: Injects dependencies based on config– Complete decoupling from concrete implementation types

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 63: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

51

Introduction to Spring 5 and Spring MVC/REST

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:

ClassPathXmlApplicationContext,

FileSystemXmlApplicationContext, and

AnnotationConfigApplicationContext

Provides resource access in a flexible and powerful way– From file system, the classpath, URL access, and more– Supports ant-style wildcards like conf/**/ctx.xml– Uses its own resource classes to accomplish resource access

Session 1: Introduction to Spring

Copyright © LearningPatterns Inc. All rights reserved.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 64: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Introduction to Spring 5 and

Spring MVC/REST

Lab Manual

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 65: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc. Copyright © LearningPatterns Inc. For more information about Java Enterprise Java, or related courseware, please contact us. Our courses are available globally for license, customization and/or purchase. LearningPatterns. Inc. [email protected] | www.learningpatterns.com Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA 212.487.9064 voice and fax Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in 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.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 66: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 1

Labs: Introduction to Spring 5 and Spring MVC/REST (Eclipse/Tomcat)

Version: 20180521-b

Version 20180521-b

IntroductionLabs: Introduction to Spring 5 and Spring MVC/REST

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 67: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 2

Release Level

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)– Spring 5 (tested with 5.0.4.RELEASE)

• Release used by Spring Boot– Java (tested with and requires Java 8 )– Eclipse Java EE Edition (tested with Oxygen 4.7.2))– Tomcat for the Spring/Web material (tested with Tomcat 8.5)

Recent similar versions of the software will likely work except for potentially small configuration changes

Lab

Any 5.x version of Spring should work.– The course materials are compatible with all 5.x versions.– However, we include some Spring jars and their dependencies with the labs.– If you want to use a different version, then it's up to you to make sure you have all the correct

Spring jars and the correct dependency jars.– We will also introduce Maven and Spring Boot to manage all dependencies later in the course.

Spring Boot 2 is needed to support Spring 5.– At the time of this writing the latest release version was Spring Boot 2.0.0.RELEASE.

All labs have been tested on Microsoft Windows using the software listed above.– Many have been tested on Mac OS also.– 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.

IntroductionLabs: Introduction to Spring 5 and Spring MVC/REST

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 68: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 3

Lab 1.1: Setting Up the Environment

In this lab you'll set up the lab environment, boot the Spring container, and test it with a unit test

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 69: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 4

Lab Synopsis

Overview: In this lab, we will:– Become familiar with the lab structure– Set up our environment, including the Spring container– Write, compile and run a simple unit test that requires Spring and

validates our setup

Builds on previous labs: None

Approximate Time: 30-45 minutes

Lab

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 70: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 5

Information Content and Task Content

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– An example appears below

Tasks to PerformNote the different look of this instruction box compared to the above– Future labs will also use this format

OK – Now locate your setup files; we're ready to start working (1)

Lab

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

– Present on the training machines as a zip file– Already unzipped on the training machine– Given to you by the instructor– Available as a network share or web download

Your instructor will let you know how to access them.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 71: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 6

Set Up Environment

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– Assuming you extracted the zip to C:\ - otherwise adjust accordingly– It includes a directory structure and files needed for the labs

Tasks to PerformMake sure Java is installedMake sure Eclipse is installedUnzip the lab setup file to C:\– This will create the directory structure, described in the next slide,

containing files that you will need for doing the labs– You can unzip it elsewhere - just adjust all locations consistently (1)

Lab

To make sure Java is installed, you can do one of the following.– Open a command prompt, and type the below - it should execute and give version information.java -version

– Look in C:\Program Files\Java for an installed JDK.If Java is not installed, then download it from one of the following, and execute the installer.

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

To make sure Eclipse is installed, check for the install folder (usually C:\Eclipse).– If Eclipse is not installed, then first download it from http://www.eclipse.org/downloads.– Select the download packages link, then click on the link for the Eclipse IDE for Java EE

Developers, and select the appropriate zip file 32/64 bit, Windows vs. Linux, etc.– If you need to install Eclipse, unzip the zip file - easiest location to unzip it to is C:\, but another

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.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 72: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 7

Lab Directory Structure

StudentWork\Spring contains– Derby/DerbyLib: Database files– mavenRepository: pre-populated

repo for labs– SpringDependencies: Dependency

jars– SpringLibraries: Spring jars– workspace: Eclipse workspace

StudentWork\Spring\workspacewill contain the following folders:– LabNN : Folder for Lab NN– LabNN/src : Java source– LabNN/test : Java unit tests– LabNN/bin/ : compiled code

(Eclipse's standard location)

Lab

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 73: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 8

General Lab Structure

Root lab folder for this lab, already in your workspace is:workspace\Lab01.1

–It contains starter files• All labs either have starter files or build on a previous lab

–You'll create an Eclipse project in this folder–Lab files and instructions are relative to the Lab01.1 folder

Two source folders–src: Contains regular Java source–test: Contains JUnit test classes

• To test our code• You'll run these using Eclipse's JUnit support• test may sometimes contain a regular Java app (with a main())

Lab

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 74: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 9

Eclipse Overview

Eclipse: Open source platform for building integrated development environments (IDEs)– Used mainly for Java development– Can be flexibly extended via plugins to add capabilities– http://www.eclipse.org is the main website

This lab includes detailed instructions on using Eclipse– Starting it, creating and configuring projects, etc.

Other labs include fewer Eclipse details - they may just say build/run as previously– Just use the same procedures to build/run as in this lab– Refer back to these lab instructions as needed

Lab

The Eclipse source base was originally developed by IBM.– It was released by IBM into open source.– IBM's RAD (and it's predecessor WSAD) are built on top of Eclipse.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 75: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 10

Launch Eclipse

Tasks to PerformLaunch 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– Click OK– Close the Welcome screen: Click the X on its tab (below right)

Lab

If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly.– You can put a shortcut to this executable on your desktop.

You can also have your lab workspace in a different location.– Again, just adjust the lab instructions as required.

If a different default workspace location is set when you start Eclipse, then change it.– Sometimes Eclipse is set up to automatically open to a different workspace location.– If this is the case, you can switch workspaces after Eclipse starts by going to File | Switch

Workspace.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 76: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 11

Workbench and Java Perspective

Tasks to PerformOpen 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– Close the Java EE perspective by right clicking its icon, and

selecting close (bottom right)Unclutter the Java Perspective by closing some views– Close the Task List and Outline views (click on the X)– Open the Navigator View (Window | Show View | Navigator)

Lab

The Eclipse Java EE version opens in the Java EE perspective by default.– Other versions may open in a different perspective. If you're already in a Java perspective, you

don't need to switch perspectives, and there is nothing for you to do.To save a our "uncluttered" perspective as the default Java perspective go to:

– Window | Save Perspective As | JavaYou can reset the perspective to its defaults via: Window | Reset Perspective.In Eclipse Neon (4.6) and later, the perspective switcher does not show the perspective text by default.

– To change this, right click on the perspective icons, select Show Text - see examples below.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 77: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 12

Java Perspective: Where's the Projects?

Relax! The projects will reveal themselves as we proceed– Do not import anything

Lab

financial info

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 78: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Create User Libraries

Tasks to PerformGo to Window | Preferences | Java | Build Path | User Libraries– Click New… , in the dialog, call the library Spring, and press OK– Click the Add External JARs… button, browse to StudentWork\Spring\SpringLibraries– Select all the jars in that folder, Click Open– Select the Spring library again, click Add External JARs…, browse to StudentWork\Spring\SpringDependencies– Select all jars in that folder, Click Open– Click OK to finish creating the library

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– Later labs use maven for dependencies

Lab

We include all the Spring jars from the Spring distribution in our setup– This is for ease of use– Otherwise you would need to download them somehow - which is no longer a trivial job since

there is no archive available from the Spring project with all the jar files that make up the Spring distribution

We supply all needed dependencies in the SpringDependencies folder– These were figured out by using Maven and seeing what dependencies were added to the project– In this folder, we supply all the external dependencies for all the labs– This is quite a bit more than is needed for this lab

Copyright © LearningPatterns Inc. All rights reserved. 13

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 79: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 14

Create a Project for our Application

Tasks to PerformCreate a Java Project (1)

– Call the project Lab01.1• You MUST call it this to pick up

starter files– Eclipse will then automatically set

the project folder to Lab01.1• It already exists in the workspace• Contains Java project for Eclipse

– Click Next

This will bring you to the Java Settings dialog– It should show the src and test

folders as source folders (2)

– It will also let us add a library

Lab

(1) To create a Java Project, use the menu item:– File| New | Java Project

There are many other ways to create a project.– You can use the new icon on the left hand side of the toolbar, as shown above.

You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a new Lab directory - this happens several times in the course.

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

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 80: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 15

Add the Spring Library to the ClassPath

Tasks to PerformIn Java Settingsdialog, click the Libraries tab (1)

–Click Add Librarybutton, and in the dialog that comes up, select User Library then click Next–Check off Spring, then click Finish out of all dialogs

Lab

(1) If you forget to add the library in this step, you can always add it later as follows.– Right click on the project in Package Explorer, and select Build Path | Add Libraries.– That should bring you to the Libraries tab, so add in the Spring library as described above.

Note that we include the JUnit library with the SpringDependencies.– Eclipse also provides a JUnit library, but we prefer not to have an Eclipse dependency in the lab

classpath.

When the project is created, Eclipse will attempt to compile all the Java source.– This may lead to warnings about unused imports, variables, etc. depending on our setup files.– You can just ignore these – most of them are because the files we give you are just skeletons, and

not complete..– 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".

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 81: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Running the Lab

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

– It just bootstraps Spring to test the environment

After a clean build (error-free, not necessarily warning-free), do the following– In Package Explorer , right click

on SpringTest.java• In com.javatunes.spring

package under the test folder– Select: Run As -> JUnit Test– This automatically finds and runs

SpringTest's test method

Lab

(1) Don't worry about the Spring code at this point…we'll cover all of it the next section.– This lab is designed to ensure that the project is set up and runs properly.

Copyright © LearningPatterns Inc. All rights reserved. 16

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 82: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

Notes:

Copyright © LearningPatterns Inc. All rights reserved. 17

Program Output

You should see JUnit output in a JUnit view, as shown below, andoutput 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 test to run in the labs (2)

Lab

STOP

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

(2) When running tests in other labs, the only thing that may change is the test class that you'll need to right click on to run.–The procedure will remain the same though.

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied

Page 83: Spring5-MVC-REST Sessions 20180521-b · Spring 5 and Spring MVC/REST EVALUATION COPY Unauthorized reproduction or distribution is prohibitied. This material is copyrighted by LearningPatterns

7400 E. Orchard Road, Suite 1450 NGreenwood Village, Colorado 80111

Ph: 303-302-5280www.ITCourseware.com

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

EVALUATION COPY

Unauthorized reproduction or distribution is prohibitied