31
© 2008 coreservlets.com The Spring Framework: The Spring Framework: Core Capabilities Part 1 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, see t htt // lt / courses at http://courses.coreservlets.com/. Taught by the experts that brought you this tutorial. Available at public venues or customized versions Available at public venues, or customized versions can be held on-site at your organization. C d l d dt ht b M t H ll 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. Courses developed and taught by Marty Hall 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

The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Embed Size (px)

Citation preview

Page 1: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

© 2008 coreservlets.com

The Spring Framework:The Spring Framework: Core Capabilities Part 1

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, see t htt // l t /courses at http://courses.coreservlets.com/.

Taught by the experts that brought you this tutorial. Available at public venues or customized versionsAvailable at public venues, or customized versions

can be held on-site at your organization.

C d l d d t ht b M t H ll

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.

• Courses developed and taught by Marty Hall– 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

Page 2: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Topics in This Sectionp

• Spring IoC container• Interface-oriented development• Spring framework composition• Spring container instantiation• Spring bean definitions

Java EE training: http://courses.coreservlets.com4

© 2008 coreservlets.com

S i I C C t iSpring IoC Container

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.

Page 3: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC Containerp g

• Fundamental features– Registration system (applicationContext.xml)

• Complex initialization• Object creationj• Dependency injection• Application configuration

Access API

Java EE training: http://courses.coreservlets.com

– Access API• BeanFactory#getBean

6

Spring IoC Container Relevancep g

• Inversion of control– Moves object creation and dependency resolution

responsibilities out of business logic– Enables business logic to be portable– Enables business logic to be portable– Allows components to be reconfigured with minimal

effort

• Loose coupling– Clients are insulated from implementations

I l i h i li i i i ibl li– Implementation technicalities are invisible to clients– Clients are only aware of the interface contract and

unaware of:

Java EE training: http://courses.coreservlets.com

u awa e o :• Concrete type selections• Concrete type initialization mechanisms

7

Page 4: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC Container and POJO InstantiationInstantiation

• Integrate Spring IoC container – Replace custom ServiceProviderFramework with

BeanFactory

• Delegate to Spring IoC container• Delegate to Spring IoC container– Object creation

Java EE training: http://courses.coreservlets.com8

Spring IoC Objectivep g j

• Create a BookLibrary object based on the lJavaBookLibrary class

Java EE training: http://courses.coreservlets.com9

Page 5: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC Processp g

• Create an XML file conforming to spring beans xsdspring-beans.xsd– Name the file

• Conventional name is applicationContext.xmlH ill ffi• However, any name will suffice

– Place the file in an accessible location• For example, in a filesystem directory which will be accessible from the

classpathclasspath

– Register objects• Objects are registered by declaring bean XML elements• Conventional approach is to use bean attributes: id and classConventional approach is to use bean attributes: id and class

• Access object(s) managed by the Spring IoC container– Instantiate a BeanFactory implementation

Use interfaces such as BeanFactory#getBean( ):Object

Java EE training: http://courses.coreservlets.com

– Use interfaces such as BeanFactory#getBean(...):Object

10

Spring IoC Configurationp g g

• Object registration process

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"p // g/ /xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="bookLibrary" class="coreservlets.JavaBookLibrary"/>

</beans>

Registered name Concrete type

Java EE training: http://courses.coreservlets.com11

Page 6: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC BeanFactoryp g y

import org.springframework.beans.factory.*;import org.springframework.context.support.*;p g p g pp ;

public class Main {public static void main(String[] args) {

BeanFactory beanFactory =new ClassPathXmlApplicationContext(

"/applicationContext.xml");

Spring BeanFactory configuration

BookLibrary service =(BookLibrary)beanFactory.getBean("bookLibrary");

Spring BeanFactory access API

System.out.printf("Retrieved BookLibrary type: \"%s\"%n",service.getClass().getSimpleName());

}Standard outputInterface type

Java EE training: http://courses.coreservlets.com

}

12

Standard output

Retrieved BookLibrary type: "JavaBookLibrary"

Interface type

Spring IoC Container Summaryp g y

• Loaded B d fi i i f li i l– Bean definitions from applicationContext.xml

• Created – coreservlets.JavaBookLibrary instance

• Registered– Object under the name bookLibrary

Requested• Requested– A BookLibrary object from the Spring IoC container using the

access API, BeanFactory#getBean(…)

• Received– An instance of JavaBookLibrary, a BookLibrary

implementation instance

Java EE training: http://courses.coreservlets.com13

Page 7: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Model Analysisy

• Dynamic implementation choices– Implementation types are excluded from the program

• Portable model configurationObj d l fi i i l d i hi h– Object model configuration is encapsulated within the framework

• Flexible model configurationFlexible model configuration– Object model configuration is a declarative system based

on spring-beans.xsd

Java EE training: http://courses.coreservlets.com14

Spring IoC Container and Dependency InjectionDependency Injection

• Delegate to Spring IoC container– Object instantiation– Dependency injection

Java EE training: http://courses.coreservlets.com15

Page 8: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC Objectivep g j

• Create a BookLibrary object based on the J B kLib classJavaBookLibrary class

• Create a BookReader object based on the BookReader class

• Inject the BookLibrary object into BookReader

Java EE training: http://courses.coreservlets.com16

Spring Processp g

• Create an XML file conforming to spring beans xsdspring-beans.xsd– Name the file – Place the file in an accessible location such as the classpath– Register objects using XML bean elements– Add bean dependency injection instructions

• Add references to beans values collections or• Add references to beans, values, collections, or configuration properties

• Also known as “wiring” the application

Access object(s) managed by the Spring IoC container• Access object(s) managed by the Spring IoC container– Instantiate a BeanFactory implementation– Use interfaces such as BeanFactory#getBean(...):Object

Java EE training: http://courses.coreservlets.com17

Page 9: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring XML Configurationp g g

• Object registration process

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"p // g/ /xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> Referenceable bean

<bean id="bookLibrary" class="coreservlets.JavaBookLibrary"/>

<bean id="bookReader" class="coreservlets.BookReader"><constructor-arg ref="bookLibrary"/>

</bean>

</beans>Bean reference

Java EE training: http://courses.coreservlets.com

</beans>

18

BookReader Constructor

public class BookReader {public class BookReader {

private BookLibrary bookLibrary;

public BookReader(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;

}

public List<Book> read() {List<Book> books = bookLibrary.search("Java");for(Book book : books){

Dependency injection interface

System.out.printf("Reading: %s%n", book);}return books;

}

Java EE training: http://courses.coreservlets.com

}}

19

Page 10: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring BeanFactoryp g y

public class Main {public static void main(String[] args) {public static void main(String[] args) {

BeanFactory beanFactory =new ClassPathXmlApplicationContext(

Spring BeanFactory configuration

"/applicationContext.xml");

BookReader client = (BookReader) beanFactory getBean("bookReader");

Spring BeanFactory access API

beanFactory.getBean( bookReader );

List<Book> books = client.read();

System.out.printf("Client read: %s books%n", books.size()); }

} Standard output

Java EE training: http://courses.coreservlets.com20

Reading: Core Servlets and JavaServer PagesReading: More Servlets and JavaServer PagesClient read: 2 books

Spring IoC Container Summaryp g y

• Loaded d fi i i f– Bean definitions from applicationContext.xml

• Created – coreservlet JavaBookLibrary instancecoreservlet.JavaBookLibrary instance– coreservlet.BookReader instance

• Registeredg– Object under the name bookLibrary– Object under the name bookReader

I j t d d d• Injected dependency– BookLibrary implementation instance, JavaBookLibrary, into the BookReader object

Java EE training: http://courses.coreservlets.com

y, j

21

Page 11: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring IoC Container SummaryContinuedContinued

• RequestedA bj f h S i C i– A BookReader object from the Spring IoC container using the access API, BeanFactory#getBean(…)

• ReceivedReceived– An instance of BookReader

• Used– The BookLibrary dependency was previously fulfilled

during the injection step– BookReader used BookLibrary interfaces to accessBookReader used BookLibrary interfaces to access

and read Book information

Java EE training: http://courses.coreservlets.com22

Model Analysisy

• Dynamic implementation choices– Implementation types are excluded from the program– Decoupled design allows new types to be configured into

the program without having to recompilethe program without having to recompile

• Portable model configuration– Object model configuration is encapsulated within the O j g p

framework

• Flexible model configuration– Object model configuration is a declarative system based

on spring-beans.xsd– BeanFactory clients are also decoupled from the bean

Java EE training: http://courses.coreservlets.com

BeanFactory clients are also decoupled from the bean types accessed from the container

23

Page 12: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

© 2008 coreservlets.com

Interface-OrientedInterface OrientedDevelopment

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.

Interface-Oriented Developmentp

• Take advantage of type-polymorphism– Flexible architecture – Tolerant to changes

Enables new capabilities with minimal effort– Enables new capabilities with minimal effort

• Commit to interfaces, not implementations– Included but not limited to compiled interactionsIncluded, but not limited to, compiled interactions– Declarative interfaces

Java EE training: http://courses.coreservlets.com25

Page 13: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Interface-Oriented Examplep

<bean id="bookLibrary"class="coreservlets.JavaBookLibrary"/>y

<bean id="bookReader"class="coreservlets.BookReader" >

<constructor arg ref "bookLibrary"/>Interface type

<constructor-arg ref="bookLibrary"/></bean>

public class BookReader {

private BookLibrary bookLibrary;

public BookReader(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;

}

Java EE training: http://courses.coreservlets.com

...}

Interface-Oriented Examplep

<bean id="bookLibrary"class="coreservlets.JavaBookLibrary" />class= coreservlets.JavaBookLibrary />

Interface type

public class Main {public static void main(String[] args) {

Interface type

...BookLibrary service =(BookLibrary)beanFactory.getBean("bookLibrary");

}}

Java EE training: http://courses.coreservlets.com

Page 14: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Service Abstraction

• Abstract elements such as third-party APIs d i fand infrastructure

• Decouple business logic enabling portabilityportability

Java EE training: http://courses.coreservlets.com

© 2008 coreservlets.com

S i F kSpring Framework

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.

Page 15: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring Framework Compositionp g p

• IoC Container– Core libraries

• spring-core• spring-beansspring beans

– Integration extensions• spring-context

i b• spring-web

Java EE training: http://courses.coreservlets.com30

Spring FrameworkModulesModules

• Aspect-Oriented Programming– spring-aop

• Service abstractionsJDBC templates and transaction management– JDBC templates and transaction management• spring-jdbc• spring-tx

– O/R mapping frameworks• spring-orm

– JMS• spring-jms

– JEE, EJB, JMX, JNDI, etc…• spring-context

Java EE training: http://courses.coreservlets.com

• spring-context

– Java Mail, Quartz, etc…• spring-context-support

31

Page 16: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Spring Framework Compositionp g p

• Test support– TestNG and JUnit, IoC container, and transaction

management integration• spring-testspring test

• Web Application Framework– Spring Web MVC, FreeMarker, and Jasper Reportsp g p p

• spring-webmvc

Java EE training: http://courses.coreservlets.com32

© 2008 coreservlets.com

S iSpring BeanFactory

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.

Page 17: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

BeanFactoryy

• BeanFactory– Defines core but non-specific

functionality

ApplicationContext• ApplicationContext– Context resources– Bundle resourcesBundle resources– Event listeners– Post processors

Java EE training: http://courses.coreservlets.com34

Coarse-Grained Interfaces

• Covers typical integration scenarios• Automated but implicit functionality• Committed to specific integration strategies

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

BeanFactory beanFactory = new FileSystemXmlApplicationContext("/etc/app/applicationContext.xml");

Java EE training: http://courses.coreservlets.com35

Page 18: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Fine-Grained Interfaces

• Fine integration control – Bean configuration abstraction– I/O abstraction

BeanFactory beanFactory = new GenericApplicationContext();

Parses and loads bean definitions

I t ti ith i I/O i t fXmlBeanDefinitionReader xmlReader =new XmlBeanDefinitionReader(beanFactory);

Integration with generic I/O interfaces

Integration with spring I/O abstractionsxmlReader.loadBeanDefinitions(new FileInputStream("/etc/applicationContext.xml"));

i i i

Integration with spring I/O abstractions

Java EE training: http://courses.coreservlets.com

xmlReader.loadBeanDefinitions(new ClassPathResource("/applicationContext.xml"));

36

Servlet Integrationg

<web-app><context-param><context param><param-name>contextConfigLocation</param-name><param-value>WEB-INF/applicationContext.xmlclasspath:/applicationContext.xml

</param-value></context-param><listener> E l f S i<listener><listener-class>org.springframework.web.context.ContextLoaderListener

</listener-class>

Example of Spring resource abstraction

</listener></web-app>

Java EE training: http://courses.coreservlets.com37

Page 19: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

JavaServer Faces Integrationg

• Multiple variable and EL resolver i l iimplementations– JSF 1.1

• DelegatingVariableResolver• DelegatingVariableResolver• SpringBeanVariableResolver

– JSF 1.2• SpringBeanFacesELResolver

<faces-config><application><application><variable-resolver>

org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>

Java EE training: http://courses.coreservlets.com

</application></faces-config>

38

JUnit Test Integrationg

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration@ContextConfigurationpublic class BookLibraryTest {

@Autowired Loads bean definitionsdefaults to applicationContext.xml

JUnit integration

public BookLibrary bookLibrary;

@Testpublic void verifySearch(){ }

defaults to applicationContext.xml

public void verifySearch(){ ... }

}

Loads bean definitionsusing explicit paths

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"/applicationContext.xml"})public class BookLibraryTest {

Java EE training: http://courses.coreservlets.com

...}

39

Page 20: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

JUnit Test Integrationg

@ContextConfigurationpublic class BookLibraryTestpublic class BookLibraryTest

extends AbstractJUnit4SpringContextTests {

@Autowiredpublic BookLibrary bookLibrary;

@Testpublic void verifySearch(){...

}}}

Java EE training: http://courses.coreservlets.com40

Container Event Listener

• Lifecycle event model– Event listener interface org.springframework.context.ApplicationListener

– Event objects ve objec sorg.springframework.context.ApplicationEvent• ContextRefreshEvent• ContextStartedEvent• ContextStoppedEvent• ContextClosedEvent• RequestHandledEvent

• Registration model– Enabled by registering new listener instances as

t i d b

Java EE training: http://courses.coreservlets.com

container-managed beans

41

Page 21: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Container Event Listener ExampleExample

import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.context.ApplicationListener;

public class SimpleApplicationListenerimplements ApplicationListener {

public void onApplicationEvent(ApplicationEvent event) {System.out.printf("Event type: %s%n",

event getClass() getSimpleName());event.getClass().getSimpleName());}

}

<beans><bean id="applicationListener"

class="coreservlets.SimpleApplicationListener" />/b

Java EE training: http://courses.coreservlets.com

</beans>

42

Container Event Listener ExampleExample

import org.springframework.beans.factory.*;import org.springframework.context.*;import org.springframework.context. ;import org.springframework.context.support.*;public class Main {public static void main(String[] args) {

Instantiate container

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

Expose interfacesfor triggering lifecycle events

ConfigurableApplicationContext configurableContext = (ConfigurableApplicationContext) beanFactory;

configurableContext.start(); T i lif lconfigurableContext.stop();

configurableContext.close();}

}

Trigger lifecycle events

Standard output

Event type: ContextRefreshedEvent

Java EE training: http://courses.coreservlets.com

}

43

Event type: ContextRefreshedEventEvent type: ContextStartedEventEvent type: ContextStoppedEventEvent type: ContextClosedEvent

Page 22: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

© 2008 coreservlets.com

Bean Definition

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 Definitions

• Default bean definition• Factory bean• Static factory method• Abstract bean

Java EE training: http://courses.coreservlets.com45

Page 23: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Default Bean Definition

• Create container-managed objects directly out of bean elementsbean elements– Standard bean definitions:

• XML bean element. Child to document root, bean,

– Inner bean definitions• XML bean element. Child to property or constructor-arg elementsconstructor arg elements

Java EE training: http://courses.coreservlets.com46

Default Bean Definition

• Standard bean element – Referenceable, aka collaborator, beans

• Inner beanA– Anonymous

– Prototype– Used to fulfill dependency injection settingsUsed to fulfill dependency injection settings

• Invocation prerequisite(s)--one combination requiredq– class

– class and factory-methodd

Java EE training: http://courses.coreservlets.com

– factory-bean and factory-method– abstract bean attribute set to true

47

Page 24: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Default Bean Definition

• Optional bean properties– id and name

• defaults to a generated and unique value

– scopescope• defaults to singleton

– abstract/lazy-init/primary• defaults to false

– autowire• defaults to no

– dependency-check – defaults to none– parent/depends-on/autowire-candidate/init-method/destroy method

Java EE training: http://courses.coreservlets.com

method/destroy-method• defaults to null

48

Standard bean

• Matches on a Constructor– See java.lang.Class and java.lang.reflect

• Invokes the ConstructorAnalogous to the new keyword invoking a Constructor is– Analogous to the new keyword, invoking a Constructor is the same as invoking the new operator

<bean id="bookLibrary"<bean id= bookLibraryclass="coreservlets.JavaBookLibrary">

<!-- empty constructor arguments --></bean>

C d fi i i

public class JavaBookLibrary {public JavaBookLibrary() {...

Constructor definition

Java EE training: http://courses.coreservlets.com

...}...

}49

Target constructor

Page 25: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Standard bean

• Matches on a Constructor by type

<bean id="bookLibrary"class="coreservlets.JavaBookLibrary">

</bean></bean>

<bean id="bookReader" class="coreservlets.BookReader" >t t f "b kLib "/

Bean aka collaborator

<constructor-arg ref="bookLibrary"/></bean>

public class BookReader { Constructor definitionpprivate BookLibrary bookLibrary;public BookReader(BookLibrary bookLibrary) {this.bookLibrary = bookLibrary;

}

& bean reference

Java EE training: http://courses.coreservlets.com

}...

}50

Constructor target

Inner bean Element

• Nested bean definitions

<bean id="bookReader" class="coreservlets.BookReader" ><constructor-arg><bean class="coreservlets JavaBookLibrary"/><bean class= coreservlets.JavaBookLibrary />

</constructor-arg></bean>

Anonymous inner bean

public class BookReader {private BookLibrary bookLibrary;public BookReader(BookLibrary bookLibrary) {this bookLibrary = bookLibrary;

Constructor definition

this.bookLibrary = bookLibrary;}...

}

Target constructor

Java EE training: http://courses.coreservlets.com51

Page 26: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Factory Beany

• The invocation of a method on a container-d f b hmanaged factory bean to create other

container-managed beansReferences to the target bean class are• References to the target bean class are excluded– The class information for the target bean is unnecessaryThe class information for the target bean is unnecessary

Java EE training: http://courses.coreservlets.com52

Factory Beany

• Factory beanA i d b ibl f i i i h– A container-managed bean responsible for instantiating other container-managed beans

– Referenced by a bean element attribute, factory-bean

• Factory method– The factory bean exposes a method for instantiating the target

bean typebean type– Referenced by a bean element attribute, factory-method

• Target bean– The bean declaration uses factory-bean and factory-method to map its origin to the factory bean and factory method

Java EE training: http://courses.coreservlets.com

– The factory information substitutes the XML class attribute specification

53

Page 27: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Factory Bean Exampley p

public class BookLibraryFactory {public BookLibrary newInstance() {p y () {

return new JavaBookLibrary();}

}

Factory class

Factory method

<bean id="bookLibraryFactory"class="coreservlets.BookLibraryFactory"/>

Factory bean

<bean id="bookLibrary"factory-bean="bookLibraryFactory"factory-method="newInstance" />

F t b f

Factory method

Factory bean reference

Java EE training: http://courses.coreservlets.com54

Static Factory Methody

• The invocation of a static factory method to h i d bcreate the container-managed bean

• Separate container-managed bean is not requiredrequired

• The target bean references the class and method information as the originmethod information as the origin

Java EE training: http://courses.coreservlets.com55

Page 28: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Static Factory Method Exampley p

public class BookLibraries {public static BookLibrary newInstance() {public static BookLibrary newInstance() {return new JavaBookLibrary();

}}

Static factory method

<beans><bean id="bookLibrary"

class="coreservlets.BookLibraries"factory-method="newInstance"/>

</beans>S i f h d

Class defining factory method

Static factory method

Java EE training: http://courses.coreservlets.com56

Abstract Bean

• Bean templating facility• Establishes default bean properties

– Constructor arguments, property setter parameters, bean lifecycle callbackslifecycle callbacks

• Candidate classes for abstract bean definitionsdefinitions– Concrete, abstract, or none at all

Java EE training: http://courses.coreservlets.com57

Page 29: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Abstract Bean Examplep

<bean id="dataSourceTemplate" abstract="true"><property name="url" value="jdbc:shinydb:" /><property name url value jdbc:shinydb: /><property name="driver" value="jdbc.ShinyDriver" /><property name="username" value="webapp" />

</bean>

<bean id="dataSource" class="DriverManagerDataSource">parent="dataSourceTemplate">

<property name="password" value="orioles" /><property name= password value= orioles /></bean>

Abstract discriminator

Template bean reference

Java EE training: http://courses.coreservlets.com58

© 2008 coreservlets.com

WWrapup

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.

Page 30: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

General Approachpp

• Develop POJOs– Implement creational patterns as needed– Assume the framework will accommodate the

ti l tt i d b th tcreational patterns required by the system

• Plan on using a framework to manage the instantiation of all POJOsinstantiation of all POJOs

• Create the XML bean definitions fileThis file is typically named– This file is typically named applicationContext.xml

– For large projects comprised of numerous modules,

Java EE training: http://courses.coreservlets.com

o a ge p ojects co p sed o u e ous odu es,develop a predictable naming system for context files

60

General Approach (Continued)pp ( )

• Declare bean definitions with interdependencies– Spring IoC provides comprehensive support for

i t ti ti ttinstantiation patterns• Constructor• Factory methody• Static factory method• Template beans

I l d th b d fi iti fil t f• Include the bean definitions file as part of the distribution

Thi fil ill d f lt b t ti l

Java EE training: http://courses.coreservlets.com

– This file will serve as a default, but optional, blueprint

61

Page 31: The Spring Framework:The Spring Framework: Core ...courses.coreservlets.com/Course-Materials/pdf/spring/02-spring... · Topics in This Section • Spring IoC container • Interface-oriented

Summaryy

• Select a Spring IoC container integration approach to match the runtime context– Broad integration options are available

P ti t t• Programmatic contexts– ClassPathXmlApplicationContext

– FileSystemXmlApplicationContext

• Platform-specific contexts– ContextLoaderListener

• Test contexts– AbstractJUnit4SpringContextTests

– ApplicationContext is favored over BeanFactory implementations

Java EE training: http://courses.coreservlets.com

implementations• Improved defaults, integration extensions, and

automated behavior62

© 2008 coreservlets.com

Q ti ?Questions?

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.