03 spring core2
TRANSCRIPT
-
7/31/2019 03 Spring Core2
1/35
2008 coreservlets.com
Core Capabilities Part 2
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/spring.html
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
2008 coreservlets.com
For live Spring & Hibernate training, seecourses a p: courses.coreserv e s.com .Taught by the experts that brought you this tutorial.
,can be held on-site at your organization.
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
ourses eve ope an aug y ar y a Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails
Contact [email protected] for details
-
7/31/2019 03 Spring Core2
2/35
Topics in This Section
Bean naming
Bean scoping
Dependency injection
Java EE trainin : htt ://courses.coreservlets.com4
2008 coreservlets.com
Review
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
-
7/31/2019 03 Spring Core2
3/35
General Approach Review
Define and create service interfaces
Implement service interfaces
Add bean definitions
Access and use container-managed beans
Java EE trainin : htt ://courses.coreservlets.com6
2008 coreservlets.com
Name
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
-
7/31/2019 03 Spring Core2
4/35
-
7/31/2019 03 Spring Core2
5/35
Bean Definition Example
Adapts names from client contexts
beanFactor . etBean "beanAlias"
Java EE trainin : htt ://courses.coreservlets.com
Naming Convention
Establish a convention in order to predictbean names
Identify objects according to the interface
se unqua e c ass names
Start name with a lower-case letter
Java EE trainin : htt ://courses.coreservlets.com11
-
7/31/2019 03 Spring Core2
6/35
Naming Convention
Conventions are guidelinesWhen necessary, it is okay to depart from the convention
This may demonstrate the need to refactor ,
Java EE trainin : htt ://courses.coreservlets.com12
Naming Convention Example
Bean interface
BookLibrary bookLibrary = (BookLibrary)
beanFactory.getBean("bookLibrary");
Java EE trainin : htt ://courses.coreservlets.com14
Naming Convention Example
Convention coordinates naming within aean e n on ocumen
Bean name
" "
Bean reference
class="coreservlets.JavaBookLibrary" />
Java EE trainin : htt ://courses.coreservlets.com
15
-
7/31/2019 03 Spring Core2
8/35
Naming Convention Example
Convention coordinates naming acrosssepara e ean e n on es
Bean name
Java EE trainin : htt ://courses.coreservlets.com
16
Bean reference
Naming Convention Example
Coordinating names across contextsTest
Production
Java EE trainin : htt ://courses.coreservlets.com17
-
7/31/2019 03 Spring Core2
9/35
Bean Naming Summary
Establish a naming conventionUnqualified class name
Name starting with a lower-case letter
Use the convention to predict names across
Use the XML bean id attribute for declaringthe bean name
Rely on the same conventions for
referencing other beans
Java EE trainin : htt ://courses.coreservlets.com18
General Approach Review
Define and create service interfaces
Implement services interfaces
Add the bean definitionsEstablish bean identifiers using the id attribute
Aliases can be established using name attribute oralias
elementDevelop bean names consistently using a convention
Access and use container-managed beansThe access and integration method is context-dependent
Java EE trainin : htt ://courses.coreservlets.com19
-
7/31/2019 03 Spring Core2
10/35
2008 coreservlets.com
Bean Scope
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Bean Scope
Bean scopes control bean creation and storage
The Spring IoC container defines five beanscopes
prototype
* session*
globalSession*
*Only available in web application environments
Bean scope configuration is exposed through
Java EE trainin : htt ://courses.coreservlets.com
the XML bean attribute scope
21
-
7/31/2019 03 Spring Core2
11/35
Singleton Scope
The default bean scope Explicitly specifying singleton is allowed but redundant
Caches and distributes the same bean instance
BeanFactorybean access requests
Re laces sin leton im lementations
Java EE trainin : htt ://courses.coreservlets.com22
Singleton Scope Example
BeanFactory beanFactory =
new ClassPathXmlApplicationContext(
Bean scope
"/applicationContext.xml");
Object a = beanFactory.getBean("bookLibrary");
" ".
Object c = beanFactory.getBean("bookLibrary");
Object d = beanFactory.getBean("bookLibrary");
System.out.printf("%s, %s, %s%n",
a == b, b == c, c == d);
Bean references
Java EE trainin : htt ://courses.coreservlets.com23
Standard output
true, true, true
-
7/31/2019 03 Spring Core2
12/35
Prototype Scope
Prototype scope caches and distributes a newean ns ance or var ous ypes o ean
requests Collaborative references
BeanFactorybean access requests
Java EE trainin : htt ://courses.coreservlets.com24
Prototype Scope Example
BeanFactory beanFactory = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
Bean scope
Object a = beanFactory.getBean("bookLibrary");
Object b = beanFactory.getBean("bookLibrary");
" " .
Object d = beanFactory.getBean("bookLibrary");
System.out.printf("%s, %s, %s%n", Bean references
a == b, b == c, c == d);
Java EE trainin : htt ://courses.coreservlets.com25
Standard output
false, false, false
-
7/31/2019 03 Spring Core2
13/35
Externally-Stored Bean Scopes
Java Servlet scope support
Spring scope name Java Servlet
request request
globalSession application
n/a page
Java EE trainin : htt ://courses.coreservlets.com26
General Approach Review
Define and create service interfaces
Implement services interfaces
Add the bean definitionsEstablish identifiers using the id attribute
Aliases can be established using name attribute oralias
elementDevelop bean names consistently using a convention
Default to singleton beans verr e ean crea on an cac ng us ng scope a r u e
Access and use container-managed beans -
Java EE trainin : htt ://courses.coreservlets.com
27
-
7/31/2019 03 Spring Core2
14/35
2008 coreservlets.com
epen ency
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Dependency Injection Targetpublic class BookReader {
private BookLibrary bookLibrary;
public BookReader() {
}
public BookReader(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;
}
pu c vo setBoo L rary Boo L rary oo L rary
this.bookLibrary = bookLibrary;
}
Java EE trainin : htt ://courses.coreservlets.com
...
}
29
-
7/31/2019 03 Spring Core2
15/35
Property Setter DI Target
public class BookReader {
private BookLibrary bookLibrary;
public BookReader() {
}
public BookReader(BookLibrary bookLibrary) {
this.bookLibrary = bookLibrary;
}
pu c vo setBoo L rary Boo L rary oo L rary
this.bookLibrary = bookLibrary;
}
Java EE trainin : htt ://courses.coreservlets.com
...
}
30
Property Setter DI Example
< =" "
class="coreservlets.JavaBookLibrary"/>
Java EE trainin : htt ://courses.coreservlets.com31
-
7/31/2019 03 Spring Core2
16/35
Property Setter DI Details
Matches on qualified setter methods by name
Based on JavaBean conventions
The property setter has no relationship to a class field
set
e.g., property foo as the setter method setFoo
Configuration fails with private, protected, or package-private
modifiers
Incompatible with chaining setter methods
Must accept exactly one parameter
Java EE trainin : htt ://courses.coreservlets.com
Must e enc ose y a c ass t at as a no-args constructor No requirements on the access modifier
32
Property Setter DI Implications
Forces the class to be mutable
Includes the property name in the DIdeclaration
Java EE trainin : htt ://courses.coreservlets.com33
-
7/31/2019 03 Spring Core2
17/35
Property Setter DI Bean
Configuration is exposed by the XML elementypeproperty
child to the XML element bean re uires a value for the XML element attribute name
Supports shorthand configuration value attribute for directly specifying a value
ref attribute for referring to beans defined elsewhere
Supports child references , , ,
Java EE trainin : htt ://courses.coreservlets.com34
Property Setter DI Process
Verify the presence of a no-args constructor
Verify the method signature public access modifier
void return type
bean-oriented name
Create the nested XMLproperty element
Identif the ro ert usin the name attribute
Identify the value to be passed into the setter method as aparameter value
Java EE trainin : htt ://courses.coreservlets.com35
-
7/31/2019 03 Spring Core2
18/35
Property Setter DI Example
public class BookReader {
private BookLibrary bookLibrary;
public BookReader() {
}
public BookReader(BookLibrary bookLibrary) {
No-args constructor
this.bookLibrary = bookLibrary;
}
pu c vo setBoo L rary Boo L rary oo L rary
this.bookLibrary = bookLibrary;
} Bean-oriented name Single parameter
Java EE trainin : htt ://courses.coreservlets.com
...
}
36 public access modifier
void return type
Property Setter DI Example
< =" "
class="coreservlets.JavaBookLibrary"/>
BookReader property
Setter parameter value
Java EE trainin : htt ://courses.coreservlets.com37
-
7/31/2019 03 Spring Core2
19/35
Alternative Property Setter DI
< =" "
class="coreservlets.JavaBookLibrary"/>
BookReader property
Setter parameter value
Java EE trainin : htt ://courses.coreservlets.com38
Constructor DI Targetpublic class BookReader {
private BookLibrary bookLibrary;
public BookReader() {
}
public BookReader(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;
}
pu c vo setBoo L rary Boo L rary oo L rary
this.bookLibrary = bookLibrary;
}
Java EE trainin : htt ://courses.coreservlets.com
...
}
39
-
7/31/2019 03 Spring Core2
20/35
Constructor DI Example
< =" "
class="coreservlets.JavaBookLibrary"/>
Java EE trainin : htt ://courses.coreservlets.com40
Constructor DI Details
Matches on a constructor using parameterypes
Must share matching quantities
Must share matchin t es
Must match while preserving parameter ordering
Constructor by type matching is ambiguous Multiple constructors may match the constructor-argconfiguration
Java EE trainin : htt ://courses.coreservlets.com41
-
7/31/2019 03 Spring Core2
21/35
Constructor DI Implications
Supports an immutable class design
Does not support parameter naming
Requires multiple constructors for eachparame er parame er com na on
Java EE trainin : htt ://courses.coreservlets.com42
Constructor DI Bean Definition
Configuration is exposed by the XML element type-
Child of the XML element bean
Supports shorthand configuration value attribute for directl in ectin a value
ref for referring to beans defined elsewhere
Supports child references , , ,
Offers fine-tuned constructor matching options index
type
Java EE trainin : htt ://courses.coreservlets.com43
-
7/31/2019 03 Spring Core2
22/35
Constructor DI Example
public class BookReader {
private BookLibrary bookLibrary;
public BookReader(BookLibrary bookLibrary) {
this.bookLibrary = bookLibrary;
}
...Dependency injection interface
}
Java EE trainin : htt ://courses.coreservlets.com44
Implied Constructor DI
Implied index and type
-
7/31/2019 03 Spring Core2
23/35
Explicit Constructor DI
Explicit index and type
-
7/31/2019 03 Spring Core2
24/35
Implied Constructor Matching
Arguments can be automatically re-ordered
public class Values {
public Values(Integer integer, String string){
public Values(String string, Integer integer){
}
Java EE trainin : htt ://courses.coreservlets.com
48
Implied Constructor Matching
Implied matches are unreliable
public class Values {
public Values(Integer integer, String string){
}
" ".
Standard output
Java EE trainin : htt ://courses.coreservlets.com49
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException
Failed to convert value of type [java.lang.String] to required
type [java.lang.Integer]
-
7/31/2019 03 Spring Core2
25/35
Explicit Constructor Matching
Implied matches can be corrected byspec y ng e index an or type
public class Values {
public Values(Integer integer, String string){
}
}
" " " "-
Java EE trainin : htt ://courses.coreservlets.com50
Constructor Matching
Always specify index and type when youhave overloaded constructors
Java EE trainin : htt ://courses.coreservlets.com51
-
7/31/2019 03 Spring Core2
26/35
Constructor DI Alternative
public class ValuesFactory {
private Integer integer;
private String string;
Factory method
public Values newValuesInstance() {
return new Values(integer, string);
}
Additional setter
public void setIntegerValueFromString(String string) {
this.integerValue = Integer.parseInt(string);
public void setIntegerValue(Integer integerValue) {
Java EE trainin : htt ://courses.coreservlets.com
.
}
...
52
Constructor DI Alternative
Target bean
Factory bean
Standard output
Java EE trainin : htt ://courses.coreservlets.com5353
stringValue=123 integerValue=456
-
7/31/2019 03 Spring Core2
27/35
DI Alternatives
Lookup Method
Autowiring
Annotation-driven autowiring
Java EE trainin : htt ://courses.coreservlets.com54
Lookup Method DI
Overrides or implements a factory method abstract keyword is optional
public modifier is required
Accommodates special use cases
specifies a more transient scope
Version of the abstract template pattern
Requires the cglib library
Java EE trainin : htt ://courses.coreservlets.com55
-
7/31/2019 03 Spring Core2
28/35
Lookup Method DI
public abstract class AbstractBookLibraryVisitor
im lements BookLibrar Visitor
public int visitLibrary(int visitCount){
Setset = new HashSet();while(visitCount-- > 0){
set.add(getBookLibrary().hashCode());
}
return set.size();
public abstract BookLibrary getBookLibrary();
}
Java EE trainin : htt ://courses.coreservlets.com
< ean>
56
Lookup Method DIpublic class Main {
BeanFactory beanFactory = new
ClassPathXmlApplicationContext(
"/applicationContext.xml");
BookLibraryVisitor visitor = (BookLibraryVisitor)
beanFactory.getBean("bookLibraryVisitor");
System.out.println("BookLibraryVisitor class: %s%n",
visitor.getClass().getSimpleName());
}
Standard output
object from cglib generated class
Java EE trainin : htt ://courses.coreservlets.com57
BookLibraryVisitor class:
AbstractBookLibraryVisitor$$EnhancerByCGLIB$$9fec4bdc
-
7/31/2019 03 Spring Core2
29/35
Autowiring DI
Enabled by specifying an autowiringstrategy
Autowiring is implied reso u on may qu e y a
Property setter dependency resolution
Java EE trainin : htt ://courses.coreservlets.com58
Autowiring DIpublic class BookReader {
this.bookLibrary = bookLibrary;
}
...
}
< ean =" oo L rary"
class="coreservlets.JavaBookLibrary"/>
Java EE trainin : htt ://courses.coreservlets.com
-
7/31/2019 03 Spring Core2
30/35
Annotation-Driven Autowiring
Uses annotations for specifyingdependencies
Reduces XML configuration n ro uces pr ng c ass mpor s n o source
code
Decentralizes application configuration
Implies dependencies
Java EE trainin : htt ://courses.coreservlets.com60
Annotation-Driven Autowiring
Declare an empty XML element,context:annotat on-conf g
Requirement depends on BeanFactory
Annotate dependency target
Method
Constructor
Java EE trainin : htt ://courses.coreservlets.com61
-
7/31/2019 03 Spring Core2
31/35
Annotation-Driven Autowiring
-
7/31/2019 03 Spring Core2
32/35
Annotation-Driven Autowiring
import org.springframework.beans.factory.annotation.*;
public class BookReader {
private BookLibrary bookLibrary;
@Autowired
public BookReader(BookLibrary bookLibrary) {
this.bookLibrary = bookLibrary;
}
...
Java EE trainin : htt ://courses.coreservlets.com64
Annotation-Driven Autowiringimport org.springframework.beans.factory.annotation.*;
public class BookReader {
private BookLibrary bookLibrary;
@Autowired
public void setBookLibrary(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;
}
...
Java EE trainin : htt ://courses.coreservlets.com65
-
7/31/2019 03 Spring Core2
33/35
Autowired Test Contexts
import org.springframework.beans.factory.annotation.*;
public class BookLibraryTest {
@Autowired
public BookLibrary bookLibrary;
@Test
public void verify() { ... }
...
Java EE trainin : htt ://courses.coreservlets.com66
General Approach Review
Define and create service interfaces
Implement services interfaces
Add the bean definitionsEstablish identifiers using the id attribute
Aliases can be established using name attribute oralias
elementDevelop bean names consistently using a convention
Default to singleton beans verr e ean crea on an cac ng us ng scope a r u e
Specify bean inter-dependencies using DI mechanisms Property setter, constructor, lookup-method, autowiring
Java EE trainin : htt ://courses.coreservlets.com
Access and use container-managed beansThe access and integration method is context-dependent
67
-
7/31/2019 03 Spring Core2
34/35
2008 coreservlets.com
Wrap-up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
Bean namingEstablish naming standards
Use id and/orname attributes or separate alias
Favorid attribute
Sim le bean confi urationUse constructor-arg elements
Complex bean configurationUseproperty elements
Consider using a separate factory bean withproperty
Java EE trainin : htt ://courses.coreservlets.com
Target bean: factory-bean and factory-method
Factory bean: id and class69
-
7/31/2019 03 Spring Core2
35/35
Summary Continued
Transient bean collaborator referenceAdd cglib library
Use nested lookup-method element with name
AutowiredMa re uire XML context element
annotation-config
Java EE trainin : htt ://courses.coreservlets.com70
2008 coreservlets.com
ues ons