Spring 5.0 and MVC
Spring 5.0 and MVC
PY
Introduction to
Spring 5 and
d
tie
O
i
ib
oh
C is
pr
N
n
tio
bu
IO di
s tri
AT
or
n
tio
U uc
AL
od
pr
re
ed
EV
riz
ho
ut
na
U
EV
U
na
ut
AL
ho
riz
ed
re
U
pr
od
uc AT tio
n
IO
This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or
or
distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc.
Copyright © LearningPatterns Inc.
di
s
N
For more information about Java Enterprise Java, or related courseware, please contact us. Our courses
tri
C
LearningPatterns. Inc. [email protected] | www.learningpatterns.com
t io
Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA
n
O
212.487.9064 voice and fax
is
pr
PY
Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in
oh
the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns
Inc. All other products referenced herein are trademarks of their respective holders.
ib
itie
d
Table of Contents – Introduction to Spring 5
and Spring MVC/REST
Introduction to Spring 5 and Spring MVC/REST _____________________________ 1
Workshop Overview _______________________________________________________________ 1
Workshop Objectives ______________________________________________________________ 1
EV
Workshop Agenda _________________________________________________________________ 1
Typographic Conventions ___________________________________________________________ 1
U
Labs ____________________________________________________________________________ 1
na
Overview __________________________________________________________________ 1
Spring and Enterprise Applications ____________________________________________________ 1
riz
C
Externalizing Properties______________________________________________________ 2
t
Profiles ____________________________________________________________________ 2
Profile Overview __________________________________________________________________ 2
ib
Repositories ______________________________________________________________________ 3
AL
ho
Getting Started____________________________________________________________________ 3
Mini-Lab: Review Boot Reference _________________________________________________ 3
tio
IO
Mini-Lab: Spring Boot - Starter Projects ___________________________________________ 3
n
U
Session 5: Database Access With Spring ____________________________________ 4
re
Overview __________________________________________________________________ 4
AT
Data Access Support _______________________________________________________________ 4
od
Datasources ______________________________________________________________________ 4
Example: Configuring a DataSource ___________________________________________________ 4
uc
Hibernate Overview________________________________________________________________ 4
Hibernate Configuration File Illustration _______________________________________________ 4
di
N
Using Hibernate Directly____________________________________________________________ 4
Spring Support for Hibernate ________________________________________________________ 4
s tri
LocalSessionFactoryBean ___________________________________________________________ 4
Configuring a Hibernate Session Factory _______________________________________________ 4
bu
Contextual Sessions________________________________________________________________ 4
C
Spring Free Repository Class ________________________________________________________ 4
t io
CrudRepository/JpaRepository Methods________________________________________________ 4
na
NEVER _________________________________________________________________________ 5
NOT_SUPPORTED _______________________________________________________________ 5
pr
PY
REQUIRED______________________________________________________________________ 5
oh
REQUIRES_NEW ________________________________________________________________ 5
SUPPORTS ______________________________________________________________________ 5
ib
ContextLoaderListener - @Configuration_______________________________________________ 6
O
Using the Application Context _______________________________________________________ 6
is
@ModelAttribute__________________________________________________________________ 7
Spring MVC Form Tags <form:form> _________________________________________________ 7
pr
PY
Spring MVC Form Tags <form:input> _________________________________________________ 7
oh
@ModelAttribute on Methods________________________________________________________ 7
Using Reference Data ______________________________________________________________ 7
itie
REST Characteristics_______________________________________________________________ 7
REST Resources and Operations______________________________________________________ 7
riz
Ajax Overview______________________________________________________________ 8
Ajax-JavaScript and REST Resources__________________________________________________ 8
ib
U
Content Negotiation _________________________________________________________ 8
Content Negotiation Overview _______________________________________________________ 8
re
RestTemplate.getForEntity() _________________________________________________________ 9
C
Using HttpEntity and ResponseEntity __________________________________________________ 9
t io
Accessing Headers_________________________________________________________________ 9
n
RestTemplate.exchange() ___________________________________________________________ 9
O
Setting Headers on a Request ________________________________________________________ 9
is
Error Handling____________________________________________________________________ 9
Summary of RestTemplate Usage _____________________________________________________ 9
pr
PY
Lab 11.2: [Optional] Setting / Accessing Headers_____________________________________ 9
oh
Other Capabililties_________________________________________________________________ 9
tri
Recap _______________________________________________________________ 10
pr
Spring MVC/REST
AL
ho
riz
ed
re
prU
od
uc AT
Version: 20180521-b
tio
n
IO
Notes:
or
Version: 20180521-b
di
N
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Workshop Overview
An in-depth course teaching the use of Spring 5 to build
enterprise applications using Java
– Including newer areas of Spring/Java technology
EV
The course covers the following areas of Spring technology
U
na
– Transaction Support
re
U
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Workshop Objectives
Understand the Spring framework and use its capabilities, including:
U
Transactions: Controlling transactions declaratively with Spring
re
Spring MVC/REST
uc
tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Workshop Agenda
Session 1: Introduction to Spring Session 9: RESTful Services with
Spring
Session 2: Configuration in Depth
Session 10: Working with JSON and
Session 3: Intro to Spring Boot
EV
XML
Session 4: Spring Testing
U
Session 6: Transactions
riz
Spring MVC
U
[Optional] Session 14: XML Specific
re
Session 8: More Spring MVC
Configuration
pr
AT
Capabilities
od
uc
tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Typographic Conventions
Code in the text uses a fixed-width code font, e.g.:
Catalog catalog = new CatalogImpl()
U
package com.javatunes.teach;
re
pr
AT
public class CatalogImpl implements Catalog {
od
}
}
tio
n
IO
Notes:
or
(1)
If we had additional information about a particular item in the slide, it would appear here in the notes.
di
s
N
tri
We might also put related information that generally pertains to the material covered in the slide.
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Labs Lab
– The lab details are separate from the main manual pages
U
na
ut
Setup zip files are provided with skeleton code for the labs
AL
ho
Lab slides have an icon like in the upper right corner of this
pr
AT
slide
od
– The end of a lab is marked with a stop like this one: STOP
uc
tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
Overview
ed
U
Spring Introduction
re
Dependency Injection
pr
od
uc AT tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Lesson Objectives
Understand why we need the Spring Framework
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Overview
ut
AL
ho
riz
Overview
ed
U
Spring Introduction
re
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
na
dependencies
ed
Notes:
or
C
– Have some form of persistent storage.
t io
– Have some form of remote access (Web/HTTP, Web service, Distributed Objects, etc).
n
O
– Require some measure of scalability and fault tolerance.
is
Notes:
or
• We supply jars the jars for some labs, and use maven in others
ut
AL
ho
Notes:
or
In earlier releases (up to Spring 3), both the Spring distribution and its dependencies were available as
di
N
a separate download from the Spring download pages.
s tri
– It is assumed that you'll use a build tool like maven to get the Spring libraries and its
C
dependencies.
t io
n
O
(1)
The external dependencies for the core modules for dependency injection are (purposely) minimal.
is
– If you use other technologies however, e.g. Hibernate/JPA, then there are more external
ib
dependencies .
i tie
d
(2)
Modern releases of Java/JEE offer many of the core capabilities of Spring.
– However, it is not productive to try to compare them in an absolute sense.
– Usually there are many constraints and requirements guiding your choice of technology.
– We'll present Spring's capabilities, strengths, and weaknesses, to support your decision making.
U
These are external dependencies (2)
re
Notes:
or
(1)
We supply the Spring project jars needed for the early labs in the lab setup.
di
s
N
– We downloaded these using maven and a pom.xml specifying the different modules available in
tri
Spring (e.g. spring-context) then gathered the jars together for the lab setup.
bu
– Note that the actual jars in the lab setup may vary from this illustration - look at the setup to see
io
in our labs.
pr
PY
(2)
You can see that there are not a large number of external dependencies for the basic Spring
oh
functionality.
ib
– You'll see when we do later, more complex, labs, that maven will include/download quite a few
i tie
additional dependencies.
d
– We'll use them to run tests which drive the lab code
uc
– The tests are the @Test annotated methods (see next slide)
tio
n
IO
Notes:
or
We are using JUnit to drive our slide examples and lab code because it's convenient.
di
N
s
– However, since this is a class for learning new things, we often want some console indication of
bu
what's going on, so we'll produce some console output in our test classes.
t
C
– That's not usually done in test classes written explicitly for testing, but it's good for our purposes.
io
n
– We don't need to adhere to any particular testing practices - our test cases are lab-oriented, not
O
for system testing.
is
– Where appropriate, we do adhere to standard conventions - e.g. in naming our test classes and
pr
PY
test methods.
oh
ib
i tie
d
JUnit Example
To write a JUnit test, we:
– Create a class, one or more methods annotated with @Test
– Make assertions using static methods in org.junit.Assert (e.g.
assertTrue)
EV
– The test creates the application context, and checks that it's non-null
na
import org.junit.Test;
U
public class SpringTests {
re
@Test
pr
AT
public void testContextNotNullPositive() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
od
// Just an example - we'd probably never test that the new operator works
assertNotNull("spring container should not be null", ctx);
uc
}
tio
}
n
IO
Notes:
or
– The familiar way to use these methods would be to import org.junit.Assert, and then call
tri
Assert.assertTrue(collection.isEmpty());
t
C
– This is a little cumbersome, so the static import feature of Java is used - which imports static
io
Assert class.
pr
PY
import static org.junit.Assert.*;
oh
– This allows us to use the static members without qualifying them by the classname, as seen in
ib
assertTrue(collection.isEmpty());
There is much more capability in JUnit.
d
– We won't go into that, since it's beyond the scope of the course.
– We only cover enough to show how the labs work.
– The course is also NOT meant to teach JUnit or JUnit best practices.
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Spring Introduction
ut
AL
ho
riz
Overview
ed
U
Spring Introduction
re
Dependency Injection
pr
od
uc AT tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Notes:
or
The term bean doesn't mean that much - it's a common name (e.g. JavaBeans and EJB).
di
N
s
C
– Also called the Dependency Injection (DI) or Inversion of Control (IoC) container.
t io
– You can then request those instances from the Spring container by type or name.
pr
PY
– We'll see how this works soon.
oh
Configuration metadata can also be provided in the Java properties format, or even provided
ib
– These are generally more cumbersome to use, and we won't cover them in this course.
– In fact, the Spring IoC container is totally decoupled from the external form of the metadata.
d
– It has its own internal format which it uses to store this information.
– The XML format was the original one, and is still in use today, but there are now other, more
sophisticated, ways to configure the container.
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
– com.javatunes.persistence.InMemoryItemRepository :
uc
Notes:
or
(1)
We use a simple online music store as our domain for examples in the slides and for the labs.
di
s
N
– We've tried to give it enough detail to provide good material to work with while keeping it
tri
simple enough so you don't have to spend too much time in figuring it out.
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
package com.javatunes.service;
ed
U
public class CatalogImpl implements Catalog { // Detail omitted
re
pr
AT
public MusicItem findById (long id) { /* */ }
od
Notes:
or
C
(1)
Programming to interfaces provides many advantages by decoupling your code from concrete
t
implementation classes.
io
n
– Many design patterns are based on the decoupling gained by programming to an interface.
pr
– We'll soon see how the Spring framework makes these advantages even more usable and
PY
powerful by helping manage the dependencies that have been abstracted using interfaces.
oh
ib
i tie
d
<!-- The beans namespace is the default one for the document -->
<beans xmlns="http://www.springframework.org/schema/beans"
pr
AT
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
od
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
uc
</beans>
n
IO
Notes:
or
(1)
applicationContext.xml is a standard (and default) name for the Spring config file, but you can name it
di
N
anything that you want.
s tri
(2)
There are more sophisticated ways to create beans, for example with a factory class (shown later), in
C
which case the class name may not be the actual implementation class.
t io
Spring provides an XML Schema for this configuration file, and the examples and lab setup files have
n
O
the necessary XML namespace information in them to refer to this schema.
is
– This is standard XML usage, and we don't go into the details here of how to use an XML
pr
PY
Schema.
oh
The xsi:schemaLocation property in the slide doesn't specify a version number for the schema.
i tie
org.springframework.context.ApplicationContext
ut
Notes:
or
na
import org.springframework.context.support.ClassPathXmlApplicationContext;
riz
ed
Notes:
or
– Based on the configuration, it does whatever work it needs to get ready to supply you with beans.
t
C
(1)
It's generally easier and more reliable to look up beans by their type.
PY
oh
– However, sometimes that's not practical or possible - for example when there is more than one
concrete implementation of an interface.
ib
i
We can pass multiple config files when creating the context, for example as shown below.
ApplicationContext ctx =
new ClassPathXmlApplicationContext( "ctx-1.xml", "ctx-2.xml" );
U
– We don't instantiate our beans directly
re
pr
AT
Very useful for more complex systems
od
Notes:
or
In this simple example, it looks like we've done quite a bit of work to instantiate a single instance of a
di
N
single class.
s tri
The decoupling we've achieved seems like a simple thing, but it has a lot of benefits, especially when
io
maintaining large systems.
n
O
– We'll see how useful it can be when we explore more of the capabilities.
is
pr
PY
oh
ib
i tie
d
na
U
– e.g. use getBean() to look up a bean by type or name
re
• For instance, if you have two beans implementing the same type
od
uc
tio
n
IO
Notes:
or
In this initial introduction we show you one straightforward way of using Spring.
n
O
– We will gradually introduce more capabilities throughout the course.
is
pr
PY
oh
ib
i tie
d
More on ApplicationContext
Access point for many Spring capabilities, including:
– Bean access
– Resource Access: Config files, URLs, other files
– Message resources with I18N capability
EV
ClassPathXmlApplicationContext
AL
ho
FileSystemXmlApplicationContext
ed
– Both in org.springframework.context.support
pr
od
AT
AnnotationConfigApplicationContext
uc
Notes:
or
– It is often regarded as the type that supplies the "framework" capabilities of Spring, rather than
tri
If you are writing applications for a very resource-restricted environment, such as a mobile device,
C
you might consider using BeanFactory over ApplicationContext.
t io
– Then again, even mobile devices these days usually have enough capability to make the
n
O
additional resources used by ApplicationContext negligible.
is
U
– ant-style wildcards: e.g. conf/**/ctx.xml - All ctx.xml files under conf
re
• new FileSystemXmlApplicationContext("classpath:ctx.xml");
uc
Notes:
or
The methods shown are a part of the BeanFactory API inherited by ApplicationContext.
di
N
s
C
– BeansException thrown if an exception occurred while instantiating/preparing the bean
t io
– This is standard Java generics syntax - The first <T> in the return type simply indicates that this
is a generic method, parameterized by the type parameter <T>.
d
– The T return value indicates that the return type is generic (that is, it will take on different types
based on the <T> parameter).
– The Class<T> argument indicates that when you call the method, you pass in the class which
specifies what type <T> actually is in that call.
na
ut
– BeanFactory
riz
– ApplicationContext
ed
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
U
import org.springframework.stereotype.Component;
re
package com.javatunes.service;
pr
od
AT
}
n
IO
Notes:
or
(1)
Common usage in Spring projects is to use the Spring-based annotations.
di
s
N
– Some advocate the usage of JSR-330 annotations since they are a Java standard.
tri
– This would (theoretically) allow you to port to another container that uses JSR-330 annotations -
bu
• However, this would entail a lot more work than just the annotations on the beans, so we
io
don't consider this much of a benefit, especially since it's relatively rare to do this kind of
n
O
transition.
is
– In addition, the behavior of the JSR-330 annotations in the Spring container are not exactly the
pr
PY
same as in a JEE container, so using them is somewhat misleading.
oh
– All these considerations lead us to choose the Spring-standard annotations over the JSR-330
ib
– e.g. @Component
U
na
ut
U
Tools work with the annotated code
re
Notes:
or
(1)
There is a syntax for declaring annotations, a syntax for using them in declarations, a class file
di
N
representation, and an API to read them.
s tri
– We'll only cover the capabilities that we'll be using for our Spring coding.
bu
t
C
Annotations can replace many "side files" – e.g. XML deployment descriptors.
io
n
– It's easier for tools to read the metadata and source if they're all in one place.
is
O
– They're often used for specifying details of high-level technologies (e.g. AOP, EJB, Web
Services …).
pr
PY
– These often result in code generation.
oh
ib
i
Annotations are present in the class file, and can be read by tools.
tie
– The JDK also comes with a command line utility, called apt (Annotation Processing Tool), that
d
<beans xmlns="http://www.springframework.org/schema/beans"
riz
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
ed
xsi:schemaLocation="http://www.springframework.org/schema/beans
U
http://www.springframework.org/schema/beans/spring-beans.xsd
re
http://www.springframework.org/schema/context
pr
AT
http://www.springframework.org/schema/context/spring-context.xsd">
od
<context:component-scan base-package="com.javatunes"/>
uc
</beans>
tio
n
IO
Notes:
or
(1)
In addition to enabling scanning, context:component-scan also enables the capabilities of
di
N
context:annotation-config.
s tri
bu
@Required.
t io
com.javatunes package and all of its sub-packages, and register them as beans.
pr
PY
– Note that annotations are actually detected by bean postprocessors (not important to know, but
oh
na
U
– jms: Configures JMS related beans
re
Notes:
or
(1)
We've seen the usage of <context:component-scan> previously.
di
s
N
– The tags in these schemas typically have capabilities beyond simple bean definitions and
bu
injection.
t
C
– This is one of the nice things about the custom namespaces - they can make configuration much
io
easier.
n
is
O
pr
PY
oh
ib
i tie
d
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Dependency Injection
ut
AL
ho
riz
Overview
ed
U
Spring Introduction
re
Dependency Injection
pr
od
uc AT tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
na
Notes:
or
(1)
In straightforward applications, Object A will often just create an instance of Object B and use it.
di
s
N
– This is initially an easy way to structure a system, but often not the best way.
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
}
ed
re
U
return rep.get(id);
}
uc
}
tio
n
IO
Notes:
or
In that case, CatalogImpl might need to be changed to something like that below.
bu
t io
C
return rep.get(id);
PY
oh
}
}
ib
i tie
– This is not such a big deal if you have to change it in one place.
d
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.
Dependency Inversion
All modules depend on abstractions, not each other
– In other words - program to interfaces
– CatalogImpl only knows about the abstract ItemRepository
• Can be initialized with another type (e.g. FileItemRepository)
EV
• CatalogImpl need not change - the modules are decoupled
U
na
}
AL
ho
}
pr
AT
// Code fragment - most detail omitted
od
catalogImpl.setItemRepository(rep);
tio
Notes:
or
– The idea of "Programming to Interfaces" has been around since long before Java.
tri
– It has been used in non-OO languages also, for example the stdio module in the C programming
bu
language abstracted away the details of the actual devices doing the output.
t
C
We'll soon look at Spring's Dependency Injection which makes this design strategy even easier to use.
io
n
We talk of modules here, which in this example result in dependencies between different classes.
O
is
– But it doesn't know any details of this implementation, and doesn't even know its exact type.
tie
– 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.
<bean id="inMemoryRepository"
re
class="com.javatunes.persistence.InMemoryItemRepository"/>
pr
AT
<bean id="musicCatalog" class="com.javatunes.service.CatalogImpl">
od
</bean>
tio
</beans>
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
ut
AL
@Component("musicCatalog") // Declares bean - most detail omitted
ho
}
re
U
new ClassPathXmlApplicationContext("applicationContext.xml");
Catalog cat = ctx.getBean(Catalog.class); // See note (1)
uc
}
n
IO
Notes:
or
(1) The bean lookup with the code shown directly below works because there is only one bean that
di
N
implements Catalog, so the container can find this bean by type.
s tri
ctx.getBean( Catalog.class );
bu
Note that CatalogImpl and InMemoryItemRepository didn't need anything special to support
io
Spring's DI.
n
O
–They just need to be written according to the design principles of Dependency Inversion (i.e.
is
Note also that there is nothing in your CatalogTests code which shows that CatalogImpl
ib
depends on InMemoryRepository.
i tie
–This is defined in your configuration, and handled for you by the container.
d
import javax.inject.Inject;
U
import javax.inject.Named;
re
@Inject
private ItemRepository itemRepository;
uc
}
tio
n
IO
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
CatalogImpl ItemRepository
(Dependency Inversion)
na
implements
CatalogImpl and
AL
ho
CatalogTests InMemoryItemRepository
InMemoryItemRepository creates
riz
ed
Using DI – CatalogTests
U
<<interface>>
only coupled to Catalog CatalogImpl
Catalog
re
implements
– CatalogImpl only coupled
pr
AT
to ItemRepository injects
od
<<interface>>
looks up ItemRepository
uc
CatalogTests ApplicationContext
tio
n
IO
Notes:
or
In the slide, we show diagrams of the three different ways we structured our code in the earlier slides.
di
N
s
ItemRepository.
n
O
– In the third, Spring is doing the DI, and so CatalogTests and CatalogImpl are only coupled
is
to abstract interfaces.
pr
PY
oh
In the Spring DI version, all the dependencies in the code are ONLY to interfaces.
ib
U
– They're injected into beans without you coding it
re
Notes:
or
Coupling is the measure of how much a module of code relies on other modules.
di
N
s
Consider some of the following scenarios, and how DI makes them easier.
bu
C
– Testing your code with a testing framework such as JUnit can be much easier with DI – you can
t
configure the application to use mock objects wherever you want – without changing your code
io
at all.
n
O
– Testing different versions of classes can be done just by changing the configuration metadata.
is
– In fact, any implementation class that implements the particular interfaces being used can be
pr
PY
swapped into your program simply by changing the configuration information.
oh
There is debate about how worthwhile DI and frameworks like Spring are.
ib
– However, the principles that it is based on that lead to loose coupling are widely accepted.
i tie
– 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.
Constructor Injection
Can easily inject into a constructor (ctor)
– Assume the CatalogImpl constructor shown below
With XML, <constructor-arg> means "inject into constructor"
With @Autowired, apply it to the constructor
EV
na
}
riz
<bean id="musicCatalog"
U
class="com.javatunes.service.CatalogImpl">
re
}
n
IO
Notes:
or
For @Autowired, if there is only one constructor, you can even leave out @Autowired.
di
N
s
If a constructor has multiple arguments, they will all be injected with @Autowired.
bu
C
– For example, assuming that a CatalogImpl needs an ItemChecker to do some sanity
t
checking on items, you might have the following ctor, which will have both arguments injected.
io
n
@Autowired
is
O
<constructor-arg ref="itemRepository"/>
i tie
</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.
U
– Good for required properties (can be immutable if setter omitted)
re
– Less flexible: Need ctors for each scenario, and can't reset properties
tio
n
IO
Notes:
or
(1)
If you leave out a constructor argument while configuring a bean, you'll have an error.
di
s
N
– If using XML configuration or @Autowired, you'll get a runtime exception as soon as the code
tri
is run.
bu
t
C
n
– For example, using constructor injection on required properties, and setter injection on other
O
properties.
is
pr
PY
oh
ib
i tie
d
}
pr
AT
import org.springframework.beans.factory.annotation.Qualifier;
od
@Autowired @Qualifier("cloudItemRepository")
private ItemRepository itemRepository; // Injects the Cloud-based
tio
}
n
IO
Notes:
or
In the first example of injection, where the autowiring is done by type, it fails at runtime.
di
N
s
–The container doesn't know which of the two possible types to use.
bu
C
In the second example of injection we use @Qualifier to supply a bean name.
t io
–This pinpoints exactly which bean should be injected, and works as you'd expect.
n
O
@Autowired
is
@Qualifier("cloudItemRepository")
pr
–This involves defining your own qualifiers, for example @CloudBased instead of using names.
i
–This is compile-time safe, as it is not a string-based approach, so useful for program correctness.
tie
–However, it's fairly complex, and arguably the complexity is often not worth the benefit.
d
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Review Questions
What is Spring, and how does it help you build enterprise
apps?
Spring
AL
ho
riz
What is an ApplicationContext?
ed
re
U
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Lesson Summary
Spring: Lightweight enterprise framework that supports:
– Dependency Injection
– Persistence support (Repository/DAO and ORM)
– Integration with standard Web technologies, and MVC Web apps
EV
U
dependencies
re
pr
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
Lesson Summary
ApplicationContext: API to the Spring container functionality
– Configure/wire beans, access program resources, work with resource
bundles, load multiple contexts, and publish events to beans
– Common implementations include:
EV
ClassPathXmlApplicationContext,
U
na
FileSystemXmlApplicationContext, and
ut
AnnotationConfigApplicationContext
AL
ho
riz
U
– From file system, the classpath, URL access, and more
re
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i tie
d
d
tie
O
i
Spring MVC/REST
ib
oh
C is
pr
N
n
tio
Lab Manual
bu
and
IO di
s tri
AT
or
n
tio
U uc
AL
od
pr
re
ed
EV
riz
ho
ut
na
U
EV
U
na
ut
AL
ho
riz
ed
re
U
pr
od
uc AT tio
n
IO
This material is copyrighted by LearningPatterns Inc. This content and shall not be reproduced, edited, or
or
distributed, in hard copy or soft copy format, without express written consent of LearningPatterns Inc.
Copyright © LearningPatterns Inc.
di
s
N
For more information about Java Enterprise Java, or related courseware, please contact us. Our courses
tri
C
LearningPatterns. Inc. [email protected] | www.learningpatterns.com
t io
Global Courseware Services 982 Main St. Ste. 4-167 | Fishkill NY, 12524 USA
n
O
212.487.9064 voice and fax
is
pr
PY
Java, and all Java-based trademarks and logo trademarks are registered trademarks of Oracle, Inc., in
oh
the United States and other countries. LearningPatterns and its logos are trademarks of LearningPatterns
Inc. All other products referenced herein are trademarks of their respective holders.
ib
itie
d
Labs: Introduction to Spring 5 and Spring MVC/REST Introduction
EV
U
na
Version: 20180521-b
tio
n
IO
Notes:
or
Version 20180521-b
di
N
s tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
pr
Notes:
or
– However, we include some Spring jars and their dependencies with the labs.
bu
C
– If you want to use a different version, then it's up to you to make sure you have all the correct
t
– We will also introduce Maven and Spring Boot to manage all dependencies later in the course.
is
O
pr
– At the time of this writing the latest release version was Spring Boot 2.0.0.RELEASE.
ib
i
tie
All labs have been tested on Microsoft Windows using the software listed above.
– Many have been tested on Mac OS also.
d
– The labs should work on unix variants with little modification, except for the database setup
scripts, which need to use unix shell scripts, which we also supply.
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
Tasks to Perform
AL
ho
above
ed
OK – Now locate your setup files; we're ready to start working (1)
pr
AT
od
uc
tio
n
IO
Notes:
or
(1)
Depending on your training environment, the setup files may be given to you in different ways,
di
N
including the following.
s tri
Tasks to Perform
riz
pr
AT
– This will create the directory structure, described in the next slide,
od
containing files that you will need for doing the labs
uc
– You can unzip it elsewhere - just adjust all locations consistently (1)
tio
n
IO
Notes:
or
– Open a command prompt, and type the below - it should execute and give version information.
tri
java -version
bu
C
– Look in C:\Program Files\Java for an installed JDK.
t io
If Java is not installed, then download it from one of the following, and execute the installer.
n
O
– https://java.com/en/download/index.jsp
is
– https://java.com/en/download/manual.jsp
pr
To make sure Eclipse is installed, check for the install folder (usually C:\Eclipse).
PY
oh
– Select the download packages link, then click on the link for the Eclipse IDE for Java EE
i
Developers, and select the appropriate zip file 32/64 bit, Windows vs. Linux, etc.
tie
– If you need to install Eclipse, unzip the zip file - easiest location to unzip it to is C:\, but another
d
location is fine as long as you can get to it to run the eclipse.exe executable.
(1)
You can install the software and unzip the lab setup anywhere that is convenient to you.
– We give instructions based on the locations above - just adjust accordingly to your locations.
StudentWork\Spring contains
– Derby/DerbyLib: Database files
– mavenRepository: pre-populated
repo for labs
EV
– SpringDependencies: Dependency
U
jars
na
StudentWork\Spring\workspace
ed
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
Root lab folder for this lab, already in your workspace is:
workspace\Lab01.1
–It contains starter files
EV
• All labs either have starter files or build on a previous lab
–You'll create an Eclipse project in this folder
U
na
U
–test: Contains JUnit test classes
re
Notes:
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
U
Other labs include fewer Eclipse details - they may just say
re
build/run as previously
pr
AT
– Just use the same procedures to build/run as in this lab
od
Notes:
or
– IBM's RAD (and it's predecessor WSAD) are built on top of Eclipse.
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
Tasks to Perform
Launch eclipse: Go to c:\eclipse and run eclipse.exe
– A dialog box appears prompting for workbench location (below left)
– Set the workbench location to C:\StudentWork\Spring\workspace
EV
– Click OK
U
– Close the Welcome screen: Click the X on its tab (below right)
na
ut
AL
ho
riz
ed
re
prU
od
uc AT tio
n
IO
Notes:
or
If Eclipse was installed elsewhere, adjust the paths to the Eclipse executable accordingly.
di
N
s
C
– Again, just adjust the lab instructions as required.
t io
If a different default workspace location is set when you start Eclipse, then change it.
n
O
– Sometimes Eclipse is set up to automatically open to a different workspace location.
is
– If this is the case, you can switch workspaces after Eclipse starts by going to File | Switch
pr
Workspace.
PY
oh
ib
itie
d
Tasks to Perform
Open a Java Perspective: Click the Perspective icon at the top
right of the Workbench, and select Java (bottom left)
– See notes on Perspective Icons and text labels
EV
AL
ho
Notes:
or
– Other versions may open in a different perspective. If you're already in a Java perspective, you
tri
don't need to switch perspectives, and there is nothing for you to do.
bu
You can reset the perspective to its defaults via: Window | Reset Perspective.
O
is
In Eclipse Neon (4.6) and later, the perspective switcher does not show the perspective text by
default.
pr
PY
– To change this, right click on the perspective icons, select Show Text - see examples below.
oh
ib
itie
d
Notes:
or
di
s tri
N bu
tio
C
n
is
O
pr
PY
oh
ib
itie
d
Tasks to Perform
ut
– Click New… , in the dialog, call the library Spring, and press OK
riz
StudentWork\Spring\SpringLibraries
U
– Select the Spring library again, click Add External JARs…, browse to
od
AT
StudentWork\Spring\SpringDependencies
uc
Notes:
or
We include all the Spring jars from the Spring distribution in our setup
di
N
s
– Otherwise you would need to download them somehow - which is no longer a trivial job since
bu
there is no archive available from the Spring project with all the jar files that make up the Spring
C
distribution
t io
n
O
We supply all needed dependencies in the SpringDependencies folder
is
– These were figured out by using Maven and seeing what dependencies were added to the project
pr
PY
– In this folder, we supply all the external dependencies for all the labs
oh
Tasks to Perform
Create a Java Project (1)
– Call the project Lab01.1
• You MUST call it this to pick up
EV
starter files
U
– Click Next
ed
Settings dialog
pr
AT
– It should show the src and test
od
Notes:
or
(1)
To create a Java Project, use the menu item:
di
s
N
You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a
pr
(2)
You should see the following two folders picked up automatically by Eclipse as source folders.
ib
itie
d
Tasks to Perform
In Java Settings
dialog, click the
Libraries tab (1)
EV
–Click Add Library
U
U
then click Finish out
re
of all dialogs
pr
od
uc AT tio
n
IO
Notes:
or
(1)
If you forget to add the library in this step, you can always add it later as follows.
di
s
N
– Right click on the project in Package Explorer, and select Build Path | Add Libraries.
tri
– That should bring you to the Libraries tab, so add in the Spring library as described above.
bu
t io
C
classpath.
pr
PY
oh
When the project is created, Eclipse will attempt to compile all the Java source.
ib
– This may lead to warnings about unused imports, variables, etc. depending on our setup files.
i
– You can just ignore these – most of them are because the files we give you are just skeletons, and
tie
not complete..
d
Tasks to Perform
We use Eclipse to run a test case
in SpringTest.java
– No coding needed in this class (1)
EV
environment
na
following
riz
on SpringTest.java
re
U
• In com.javatunes.spring
package under the test folder
pr
AT
Notes:
or
(1)
Don't worry about the Spring code at this point…we'll cover all of it the next section.
di
s
N
– This lab is designed to ensure that the project is set up and runs properly.
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
itie
d
You should see JUnit output in a JUnit view, as shown below, and
output in the Eclipse Console view as shown at bottom
– These should all be error free (1)
Note: You'll follow similar procedures whenever you have a JUnit
EV
test to run in the labs (2)
U
na
ut
AL
ho
riz
ed
re
prU
od
uc AT
STOP
tio
n
IO
Notes:
or
(1)
If you see any errors in the JUnit test, or exceptions in the Console output, then you've got something
di
N
configured incorrectly.
s tri
bu
(2)
When running tests in other labs, the only thing that may change is the test class that you'll need to
C
right click on to run.
t io
www.ITCourseware.com
or
di
s
N
tri
bu
t io
C
n
is
O
pr
PY
oh
ib
i
tie
d
9-06-00087-000-09-10-18