LABS:
INTRODUCTIO
N TO SPRING 5
AND SPRING
MVC/REST
(ECLIPSE/TOM
CAT)
RELEASE Lab
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
Introduction 2
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 Environment
Lab
Overview: In this lab, we
will:
• Become familiar with the lab
structure
LAB • Set up our environment, including
the Spring container
SYNOP • Write, compile and run a simple unit
test that requires Spring and
SIS validates our setup
Builds on previous labs:
None
Approximate Time: 30-45
minutes
Lab 1.1: Setting up Environment 4
INFORMATION CONTENT Lab
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 Perform
Note 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.1: Setting up Environment 5
SET UP
ENVIRONME Lab
NT
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 Perform
Make sure Java is installed
Make sure Eclipse is installed
Unzip 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 1.1: Setting up Environment 6
LAB DIRECTORY Lab
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\workspac
e
will 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 1.1: Setting up Environment 7
GENERAL LAB 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 1.1: Setting up Environment 8
Lab
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 1.1: Setting up Environment 9
LAUNCH
ECLIPSE Tasks to Perform
Launch eclipse: Go to c:\eclipse and run eclipse.exe
– A dialog box appears prompting for workbench location (below left)
– Set the workbench location to C:\StudentWork\Spring\workspace
– Click OK
– Close the Welcome screen: Click the X on its tab (below right)
Lab 1.1: Setting up Environment 10
WORKBENCH AND Lab
JAVA PERSPECTIVE
Tasks to Perform
Open a Java Perspective: Click the Perspective icon at the top
right of the Workbench, and select Java (bottom left)
– See notes on Perspective Icons and text labels
– 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 1.1: Setting up Environment 11
JAVA PERSPECTIVE: Lab
WHERE'S
Relax! THE
The projects PROJECTS?
will reveal themselves as we
proceed
– Do not import anything
Lab 1.1: Setting up Environment 12
CREATE USER Lab
LIBRARIES
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
Tasks to Perform
Go 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 Lab 1.1: Setting up Environment 13
CREATE A PROJECT FOR
OUR
TasksAPPLICATION
to Perform
Create 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.1: Setting up Environment 14
ADD THE SPRING LIBRARY
TO THE
Tasks to Perform
CLASSPATH
In Java Settings
dialog, click the
Libraries tab (1)
–Click Add Library
button, 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.1: Setting up Environment 15
RUNNING
THE LAB
Tasks to Perform
We 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.1: Setting up Environment 16
PROGRAM
OUTPUT
You should see JUnit output in a JUnit view, as shown below, and
output in the Eclipse Console view as shown at bottom
– These should all be error free (1)
Note: You'll follow similar procedures whenever you have a JUnit
test to run in the labs (2)
STOP
Lab 1.1: Setting up Environment 17
LAB 1.2: HELLO SPRING
WORLD
IN THIS LAB, WE WILL TO ACCESS A BEAN
CREATE AND USE A INSTANCE
SPRING CONTEXT
LAB
SYNOPSI Lab
S
Overview: In this lab, we will:
– Become familiar with the different parts of basic Spring
– Create and use a Spring context to access a bean instance
– Write and run a simple Spring test
Builds on previous labs: None
Approximate Time: 20-30 minutes
Lab 1.2: Hello Spring World 19
OBJECT Lab
MODEL
Object Model: Our focus will be on the following types
– We'll cover more types shortly
– Note: Search methods in the catalog won't work yet
Lab 1.2: Hello Spring World 20
LAB
PREPARATI Lab
ON
The new lab folder where you will do all your work is:
workspace\Lab01.2
Tasks to Perform
Close all open files and projects
Create a new Java project called Lab01.2 in the workspace
– See Lab 1.1 instructions on how to do this if you need to
– Remember to add the Spring user library
– You can expect to see compiler errors until the lab is
completed.
Lab 1.2: Hello Spring World 21
WRITING AND
CONFIGURING A BEAN IN Lab
SPRING Tasks to Perform
Open CatalogImpl for editing
– The class is in the com.javatunes.service package, under
src
– Make sure CatalogImpl implements the Catalog interface
– Remember - we code to interfaces to decouple from a specific
implementation
– Save your changes
Open applicationContext.xml in the src folder for editing
– Click the Source tab to edit
– Finish up the declaration of the <bean> element by
declaring:
• An id of musicCatalog
• A class of com.javatunes.service.CatalogImpl
– Save your changes
Lab 1.2: Hello Spring World 22
USING A BEAN IN Lab
A PROGRAMTasks to Perform
Open com.javatunes.service.CatalogTest (test folder)
and:
– In testCatalogLookupPositive(), modify the constructor for
ClassPathXmlApplicationContext
• Specify the applicationContext.xml file.
– Next, look up the musicCatalog bean (by type) from the context (1)
• Catalog catalog = ctx…
– Make sure the catalog bean is not null (use assertNotNull)
– Output the catalog bean (Just use System.out.println())
– Finally, call close() on the context and fix any compilation errors
Run CatalogTest as a unit test and make sure the test passes
– Right click | Run As …| JUnit Test as in previous labs
– Your tests should pass, and you should see some console output
You've successfully configured and used a bean with Spring
Lab 1.2: Hello Spring World 23
LOGGING AND ADDITIONAL THINGS Lab
(OPTIONAL)
Tasks to Perform
Open log4j2.xml in the src folder
– This configures some of the logging that Spring will do
– The root logger is configured at error level, spring at info
– You can decrease Spring logging by configuring it at warn
<Logger name="org.springframework" level="warn"/>
– debug level increases the logging - try some levels
[Optional] Other things to try
– Try looking up the bean by name, – what happens? What
about if you look it up by the wrong name?
– Try looking up a CatalogImpl instead of a Catalog
• Does this work? Is it a good idea? (see notes)
– Change your code back to your original solution STOP
before proceeding
Lab 1.2: Hello Spring World 24
LAB 1.3: SPRING
ANNOTATIONS
IN THIS LAB, WE WILL CONFIGURE BEANS
USE SPRING
ANNOTATIONS TO
LAB
SYNOPSI
S
Overview: In this lab, we will become familiar with Spring
annotations for declaring beans. We will:
– Configure Spring to scan packages for annotated Spring
beans
– Annotate CatalogImpl to be a Spring bean
• Using Spring annotations
– CatalogTest does not need to change at all
• It can simply look up the catalog as it did before
Builds on previous labs: 1.2
– Continue to work in your Lab01.2 project
Approximate Time: 20-30 minutes
Lab 1.3: Spring Annotations 26
CONFIGURING AN
ANNOTATED BEAN IN
SPRING Tasks to Perform
Continue to work in the Lab01.2 project
Open CatalogImpl
– Declare this as a Spring bean with
@Component (1)
• Use the same bean id you used
previously - "musicItem"
• Remember to import @Component
– Note the bean and context namespaces and schema locations at the
Open applicationContext.xml
top of this file (in the src
folder)
– Comment out the bean declaration from the previous lab
• Highlight the line, Right click, select Source | Toggle Comment
– Add a line to configure scanning for annotated classes
• The base package to start scanning from is "com.javatunes"
Lab 1.3: Spring Annotations 27
CHECK THAT YOUR
BEAN EXISTS
Tasks to Perform
Run CatalogTest (in the test folder) and make sure it still passes
– The output should be identical and all asserts should pass
[Optional] Uncomment the bean declaration in
applicationContext.xml
– Run Spring Test again…did you see any errors?
– Is this a good idea? Why or why not?
– What happens if you name the bean in the XML something different,
like "musicCatalog2"?
– Do you get two instances of Catalog, or two references to one
bean?
– How could you confirm your conclusion in SpringTest?
– Change your code back to your original solution before going on
STOP
Lab 1.3: Spring Annotations 28
Lab 1.4: Dependency Injection
In this lab, we'll work with Spring's DI capabilities
LAB
SYNOPSI
S
Overview: In this lab, we will become familiar with Spring DI
and work with its capabilities. We will:
– Configure Spring to inject dependencies based on the
following:
• CatalogImpl needs an ItemRepository
• InMemoryItemRepository is a concrete implementation of
ItemRepository
– CatalogTest can look up the catalog as it did before
• The catalog will now have complete functionality
• And we can add other testing for it if we want
Builds on previous labs: 1.3
– Continue to work in your Lab01.2 project
Approximate Time: 20-30 minutes
Lab 1.4: Dependency Injection 30
OBJECT
MODEL
Object Model: We'll focus on injecting an ItemRepository
into the CatalogImpl
– We don't cover ItemRepository details - it's given to you in full
Lab 1.4: Dependency Injection 31
WRITING AND
CONFIGURING A BEAN IN
SPRING Tasks to Perform
Continue to work in the Lab01.2 project
Open InMemoryItemRepository class
in com.javatunes.persistence for editing
– Annotate this as a Spring bean
– It requires no injection or other configuration
Open CatalogImpl in com.javatunes.service
– Notice it has an ItemRepository property
• A dependency on ItemRepository, which
will need to be wired
– Add an annotation to the property to
"autowire" it
• To inject it by type
Lab 1.4: Dependency Injection 32
CHECK IF YOUR BEAN
WORKS CORRECTLY
Tasks to Perform
Run CatalogTest (in the test folder) and make sure it still passes
– The output should also indicate that the catalog has a repository (You'll
see this if you've output Catalog.toString() to the console)
Open CatalogTest and find testCatalogPositive()
– Annotate it as a test method, and add the following tests
– Call the size() method on the catalog, check (with a JUnit assert)
that it's not zero, then print out its value
• It gives a result now - where did the data come from?
– Call catalog's findByKeyword("a")
• What is returned? Check (with a JUnit assert) that at least one item was
found
• Print out the returned data
Run your test class again and check the results for errors
Lab 1.4: Dependency Injection 33
BREAK YOUR
PROGRAM AND TEST
IT Tasks to Perform
In CatalogImpl, try commenting out the annotation for the
dependency wiring (the injection)
Run your test again - What happens? Why?
Change your code back to your original solution before going
on
STOP
Lab 1.4: Dependency Injection 34