Your SlideShare is downloading. ×
An Introduction to Spring 4.x
Ilio Catallo – Politecnico di Milano
ilio.catallo@polimi.it
Outline
¤ What is Dependency Injection?
¤ The Spring Framework
¤ Writing applications in Spring
¤ References
What is Dependency Injection?
Component dependencies
¤ Applications typically consist of components that work
together to form what the user sees as a ...
The MovieLister example
¤ Assume that we need to write a component that
provides a list of movies directed by a particula...
Business logic
¤ Here’s a possible implementation:
public List<Movie> moviesDirectedBy(String directorName) {
List<Movie>...
MovieLister dependency
¤ MovieLister depends on MovieFinder to obtain the list
of movies
MovieLister MovieFinder
Obtaining the movie list
¤ There are many different ways of storing the movie list:
¤ Database
¤ File system
¤ Remote ...
MovieFinder as an interface
¤ To enforce decoupling, we define MovieFinder as an
interface with a unique method
public in...
MovieFinder as an interface
¤ Each MovieFinder implementation has its own way of
retrieving the data
«interface»
MovieFin...
Obtaining a MovieFinder
implementation
¤ However, at a certain point we need to decide for a
specific implementation of M...
Obtaining a MovieFinder
implementation
¤ Unfortunately, this makes MovieLister dependent on
both the interface and the im...
Obtaining a MovieFinder
implementation
¤ We would like MovieLister to be dependent only on
the interface
¤ To do so, the...
Composing objects
¤ We can now provide different implementations of
MovieFinder to MovieLister
¤ This allows different d...
Composing objects
¤ However, we still have a problem…
Who is going to compose the different objects into a
fully working ...
Composing objects
¤ Short answer: YOU!
¤ Long answer:
¤ Developers of the application are in charge of wiring the
diffe...
Composing objects
¤ Developers would be happy to give up this control to
someone else
¤ We would like an external assemb...
Dependency Injection
¤ Dependency injection (DI) is a design pattern in which an
external entity called the assembler is ...
Dependency Injection
MovieLister
MovieFinder
I need a
MovieFinder
Assembler
I’ll give you a
MovieFinder
injected into
Geek&Poke
Geek&Poke
The Spring Framework
The Spring framework
¤ The Spring framework is a Java framework that provides
comprehensive infrastructure support for de...
The Spring DI Container
¤ In Spring, application components are instantiated and
managed directly by the framework
¤ Nam...
Spring Beans
¤ A bean is an application object that is instantiated, and
otherwise managed by a Spring DI container
A
C
B...
Decoupling dependencies from
business logic
¤ The DI Container allows you to decouple the
specification of dependencies f...
Configuration metadata
¤ The configuration metadata represents how the
developer tells the Spring container to assemble o...
Configuration metadata
¤ The configuring metadata can be represented in:
¤ XML
¤ Java annotation
¤ Java code
Writing applications with Spring
Plain Old Java Objects
¤ Many Java frameworks require developers to extend
classes or implement interfaces provided by th...
Plain Old Java Objects
¤ In Spring, application components are written as Plain
Old Java Objects (POJOs)
¤ That is, comp...
The MovieLister Example
¤ Assume that we want to take advantage of the Spring
framework for our MovieLister application
¤...
Configuring the container
¤ We need to configure Spring to tell it
¤ what beans it should contain
¤ how to wire those b...
The <beans> element
¤ The root element of the Spring configuration file is the
<beans> element
<?xml version="1.0" encodi...
The <bean> element
¤ Each application bean is associated with a <bean>
element in the XML configuration file
<bean id="fa...
The <bean> element
¤ Every bean has:
¤ one (or more) id attribute
¤ a class attribute
¤ Namely:
¤ If more identifiers...
How to inject dependencies
¤ In Spring, dependencies are injected through:
¤ Properties that are set on the object insta...
Setter-based injection
¤ Setter-based injection is accomplished by the container
calling setter methods on the bean
¤ Th...
Constructor-based injection
¤ Constructor-based injection is accomplished by the
container invoking the bean constructor
...
Spring Beans vs. JavaBeans
¤ The DI container is not limited to actual JavaBeans
¤ It can manage virtually any class
¤ ...
Spring DI Container
¤ In Spring-based applications, your beans will live within
the Spring DI container
¤ Spring comes w...
ApplicationContext
¤ The BeanFactory interface provides basic support for DI
¤ The ApplicationContext interface extends
...
ApplicationContext
¤ The ApplicationContext interface is a sophisticated
implementation of the factory pattern
¤ By usin...
ApplicationContext
¤ Example of bean retrieving:
¤ ClassPathXmlApplicationContext is a concrete
implementation of Applic...
Concrete implementations
¤ Spring comes with several implementations of the
ApplicationContext interface
¤ The most comm...
Geek&Poke
(yetagain)
References
References
¤ Martin Fowler, Inversion of Control and Dependency
Injection pattern
http://martinfowler.com/articles/inject...
Upcoming SlideShare
Loading in...5
×

An Introduction To Spring 4

599

Published on

A gentle introduction to the concept of dependency injection and its usage when writing applications in Spring

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
599
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "An Introduction To Spring 4"

  1. 1. An Introduction to Spring 4.x Ilio Catallo – Politecnico di Milano ilio.catallo@polimi.it
  2. 2. Outline ¤ What is Dependency Injection? ¤ The Spring Framework ¤ Writing applications in Spring ¤ References
  3. 3. What is Dependency Injection?
  4. 4. Component dependencies ¤ Applications typically consist of components that work together to form what the user sees as a coherent application ¤ Such components have dependencies on each other A C B D
  5. 5. The MovieLister example ¤ Assume that we need to write a component that provides a list of movies directed by a particular director* *The example has been adapted from the original Martin Fowler’s illustrating example on IoC (see references) public class MovieLister { private MovieFinder finder; public List<Movie> moviesDirectedBy(String directorName); }
  6. 6. Business logic ¤ Here’s a possible implementation: public List<Movie> moviesDirectedBy(String directorName) { List<Movie> movies = finder.findAll(); Iterator<Movie> it = movies.iterator(); while (it.hasNext()) { Movie movie = it.next(); if (!movie.getDirector().equals(directorName)) it.remove(); } return movies; } The MovieLister class depends on the MovieFinder class to complete its work
  7. 7. MovieLister dependency ¤ MovieLister depends on MovieFinder to obtain the list of movies MovieLister MovieFinder
  8. 8. Obtaining the movie list ¤ There are many different ways of storing the movie list: ¤ Database ¤ File system ¤ Remote web service ¤ MovieLister asks for the list of movies without knowing how the movies are stored public List<Movie> moviesDirectedBy(String directorName) { List<Movie> movies = finder.findAll(); ... }
  9. 9. MovieFinder as an interface ¤ To enforce decoupling, we define MovieFinder as an interface with a unique method public interface MovieFinder { List<Movie> findAll(); }
  10. 10. MovieFinder as an interface ¤ Each MovieFinder implementation has its own way of retrieving the data «interface» MovieFinder SQLMovieFinder CommaDelimitedMovieFinder WebServiceMovieFinder
  11. 11. Obtaining a MovieFinder implementation ¤ However, at a certain point we need to decide for a specific implementation of MovieFinder ¤ We could let the MovieLister look up the right MovieFinder implementation by directly instantiating it public class MovieLister { private MovieFinder finder; public MovieLister() { finder = new CommaDelimitedMovieFinder("movies.csv"); } }
  12. 12. Obtaining a MovieFinder implementation ¤ Unfortunately, this makes MovieLister dependent on both the interface and the implementation «interface» MovieFinder CommaDelimitedMovieFinder MovieLister «creates»
  13. 13. Obtaining a MovieFinder implementation ¤ We would like MovieLister to be dependent only on the interface ¤ To do so, the MovieFinder implementation is provided as an external dependency public class MovieLister { private MovieFinder finder; public MovieLister(MovieFinder finder) { this.finder = finder; } }
  14. 14. Composing objects ¤ We can now provide different implementations of MovieFinder to MovieLister ¤ This allows different developers to reuse the same components in different situations public class MovieLister { private MovieFinder finder; public MovieLister(MovieFinder finder) { this.finder = finder; } }
  15. 15. Composing objects ¤ However, we still have a problem… Who is going to compose the different objects into a fully working application?
  16. 16. Composing objects ¤ Short answer: YOU! ¤ Long answer: ¤ Developers of the application are in charge of wiring the different components together ¤ That is, developers are in control of the assembly phase of the application components Who is going to compose the different objects into a fully working application?
  17. 17. Composing objects ¤ Developers would be happy to give up this control to someone else ¤ We would like an external assembler (factory) to take care of creating and wiring the different objects of the application MovieLister movieLister = assembler.getComponent("movieLister");
  18. 18. Dependency Injection ¤ Dependency injection (DI) is a design pattern in which an external entity called the assembler is responsible for creating and wiring application objects ¤ Namely, the assembler will: ¤ Instantiate components ¤ Provide dependencies to each component ¤ Manage the lifecycle of each component
  19. 19. Dependency Injection MovieLister MovieFinder I need a MovieFinder Assembler I’ll give you a MovieFinder injected into
  20. 20. Geek&Poke
  21. 21. Geek&Poke
  22. 22. The Spring Framework
  23. 23. The Spring framework ¤ The Spring framework is a Java framework that provides comprehensive infrastructure support for developing Java applications
  24. 24. The Spring DI Container ¤ In Spring, application components are instantiated and managed directly by the framework ¤ Namely, objects live within a DI container ¤ The DI container plays the role of the assembler class ¤ It is responsible for instantiating and assembling the application objects
  25. 25. Spring Beans ¤ A bean is an application object that is instantiated, and otherwise managed by a Spring DI container A C B D Spring DI Container
  26. 26. Decoupling dependencies from business logic ¤ The DI Container allows you to decouple the specification of dependencies from the actual program logic ¤ The container gets instructions on what objects to instantiate and configure by reading configuration metadata
  27. 27. Configuration metadata ¤ The configuration metadata represents how the developer tells the Spring container to assemble objects The Spring ContainerConfiguration metadata (e.g., XML file) Fully configured system Business objects
  28. 28. Configuration metadata ¤ The configuring metadata can be represented in: ¤ XML ¤ Java annotation ¤ Java code
  29. 29. Writing applications with Spring
  30. 30. Plain Old Java Objects ¤ Many Java frameworks require developers to extend classes or implement interfaces provided by the framework itself public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response); public void doPost(HttpServletRequest request, HttpServletResponse response); public void init(); public void destroy(); }
  31. 31. Plain Old Java Objects ¤ In Spring, application components are written as Plain Old Java Objects (POJOs) ¤ That is, components in a Spring-based application often have no indication that they are being used by Spring @Controller @RequestMapping("/contacts") public class ContactsController { @RequestMapping(method = RequestMethod.GET) public List<Contact> get() {...} @RequestMapping(method = RequestMethod.POST) public String add(...) {...} }
  32. 32. The MovieLister Example ¤ Assume that we want to take advantage of the Spring framework for our MovieLister application ¤ We need to instruct the Spring DI container about the dependency between MovieLister and MovieFinder Spring DI Container MovieLister MovieFinder
  33. 33. Configuring the container ¤ We need to configure Spring to tell it ¤ what beans it should contain ¤ how to wire those beans ¤ For now, we will focus on the traditional XML configuration
  34. 34. The <beans> element ¤ The root element of the Spring configuration file is the <beans> element <?xml version="1.0" encoding="UTF-8"?> <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"> <!-- CONFIGURE APPLICATION BEANS HERE --> </beans>
  35. 35. The <bean> element ¤ Each application bean is associated with a <bean> element in the XML configuration file <bean id="fakeMovieFinder” class="it.polimi.awt.spring.FakeMovieFinder"> ... </bean>
  36. 36. The <bean> element ¤ Every bean has: ¤ one (or more) id attribute ¤ a class attribute ¤ Namely: ¤ If more identifiers are specified, the extra ones are considered as aliases ¤ The class attribute could either specify the class of the bean to be constructed or the name of a static factory method
  37. 37. How to inject dependencies ¤ In Spring, dependencies are injected through: ¤ Properties that are set on the object instance ¤ Constructor arguments ¤ Arguments to a factory method
  38. 38. Setter-based injection ¤ Setter-based injection is accomplished by the container calling setter methods on the bean ¤ The <property> element injects the dependency by calling the property setter <bean id="lostInTranslation" class="it.polimi.awt.spring.Movie"> <property name="title" value="Lost in Translation"/> <property name="director" value="Sophia Coppola"/> </bean>
  39. 39. Constructor-based injection ¤ Constructor-based injection is accomplished by the container invoking the bean constructor ¤ The <constructor-arg> element allows injecting a dependency through a constructor call <bean id="movieLister" class="it.polimi.awt.spring.MovieLister"> <constructor-arg ref="fakeMovieFinder"/> </bean>
  40. 40. Spring Beans vs. JavaBeans ¤ The DI container is not limited to actual JavaBeans ¤ It can manage virtually any class ¤ However, some Spring users prefer JavaBeans, that is, objects with: ¤ only a default constructor ¤ appropriate getters and setters ¤ Rule of thumb: use constructor arguments for mandatory dependencies and setters for optional dependencies
  41. 41. Spring DI Container ¤ In Spring-based applications, your beans will live within the Spring DI container ¤ Spring comes with several containers, which can be subdivided into two families: ¤ Containers that implement the BeanFactory interface ¤ Containers that implement the ApplicationContext interface
  42. 42. ApplicationContext ¤ The BeanFactory interface provides basic support for DI ¤ The ApplicationContext interface extends BeanFactory, providing additional functionalities ¤ Example of additional capabilities: ¤ Internationalization support ¤ The ability to load resource file
  43. 43. ApplicationContext ¤ The ApplicationContext interface is a sophisticated implementation of the factory pattern ¤ By using the method: developers can retrieve instances of the application beans T getBean(String name, Class<T> requiredType)
  44. 44. ApplicationContext ¤ Example of bean retrieving: ¤ ClassPathXmlApplicationContext is a concrete implementation of ApplicationContext ¤ The configuration metadata ex1.xml is loaded from the CLASSPATH ApplicationContext c = new ClassPathXmlApplicationContext(”ex1.xml"); MovieLister movieLister = c.getBean("movieLister", MovieLister.class);
  45. 45. Concrete implementations ¤ Spring comes with several implementations of the ApplicationContext interface ¤ The most common ones: ¤ ClassPathXmlApplicationContext loads the configuration metadata from an XML located in the CLASSPATH ¤ FilesystemXMLApplicationContext loads the configuration metadata from an XML file located in the file system ¤ XmlWebApplicationContext loads the configuration metadata from an XML file within a web application
  46. 46. Geek&Poke (yetagain)
  47. 47. References
  48. 48. References ¤ Martin Fowler, Inversion of Control and Dependency Injection pattern http://martinfowler.com/articles/injection.html ¤ SpringSource, Spring Framework Reference http://docs.spring.io/spring/docs/current/spring- framework-reference/pdf/spring-framework- reference.pdf ¤ Craig Walls, Spring in Action (3rd Edition), Manning Publications

×