Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.

Slides:



Advertisements
Similar presentations
Feature requests for Case Manager By Spar Nord Bank A/S IBM Insight 2014 Spar Nord Bank A/S1.
Advertisements

Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Session-02. Index. Jsp in Struts 2 Web.xml File in Struts 2.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
1 November 21st 2009 Shaun Abram An Introduction to Spring.
Stateful Web Application Development with Spring Web Flow John Case Senior Consultant Centare Group, Ltd.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Spring Basic Bean wiring
To define a class in Visual Basic.NET, you can follow this general procedure: 1. Add a class to the project. 2. Provide an appropriate file name for.
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
Intermediate Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Parsley Introduction Kui Huang Oct. 13, Topics Background Dependency Injection Object Lifecycle Message Bus Sample FW Extensions.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright © 2005 Finetix LLC All Rights Reserved 0 SpringFramework.Net Developer Session Chris Donnan The Peer Frameworks Series -.Net and Java.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Spring Training 17/09/ Dependency Injection.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework,
Slide 1 Extending Tuscany Raymond Feng Apache Tuscany committer.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
A Presentation By V AIBHAV S AHARAN Web-enHanced Information Management COMS E6125.
Client Call Back Client Call Back is useful for multiple clients to keep up to date about changes on the server Example: One auction server and several.
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Module Name Subtitle.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring Remoting Simplifying.
Programming in Java CSCI-2220 Object Oriented Programming.
Apache JMeter By Lamiya Qasim. Apache JMeter Tool for load test functional behavior and measure performance. Questions: Does JMeter offers support for.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Views Rendering custom views.
INTEGRATION OF BACKBONE.JS WITH SPRING 3.1. Agenda New Features and Enhancements in Spring 3.1 What is Backbone.js and why I should use it Spring 3.1.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
KEW Definitions Document Type The Document Type defines the routing definition and other properties for a set of documents. Each document is an instance.
Chapter 5 Introduction to Defining Classes
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Spring and DWR Frameworks for Rich Web Enterprise Application Thomas Wiradikusuma Presentation to the 20 th.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
1 Spring Framework April, 2012 Lam Ho Lam To. © 2010 Cisco and/or its affiliates. All rights reserved. Cisco Confidential 2 1.Spring Overview 2.Framework.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring AOP – Part 2 Advanced Aspect-Oriented.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Classes, Interfaces and Packages
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Overview of the Spring Framework Introducing.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Creative Commons Attribution- NonCommercial-ShareAlike 2.5 License Sakai Programmer's Café Sakai Montreal CRIM Workshop Introduction to Spring Framework.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Enterprise Java Beans. Contents  Understanding EJBs  Practice Section.
Spring Fling Phillip Warner. Spring Framework ● Dependency Injection (DI) Framework – “Inversion of Control” ● Facilitates Good Programming Practices.
Callbacks and Interceptors. Contents  Session Beans Life Cycle  Interceptors.
Event Sources and Realtime Actions
J2EE Lecture 6: Spring – IoC and Dependency Injection
Internationalization
Remote Method Invocation
Chapter 4: Writing Classes
Plug-In Architecture Pattern
Presentation transcript:

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An In-depth Look at Spring’s Lifecycle Management Features

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Topics in this session The lifecycle of a Spring application context –The initialization phase –The use phase –The destruction phase Other lifecycle considerations

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 Topics in this session The lifecycle of a Spring application context –The initialization phase –The use phase –The destruction phase Other lifecycle considerations

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 Phases of the Application Lifecycle InitializationUseDestruction Prepares for use Application services –Are created –Configured –May allocate system resources Application is not usable until this phase is complete Used by clients Application services –Process client requests –Carry out application behaviors 99.99% of the time is spent in this phase Shuts down Application services –Release any system resources –Are eligible for garbage collection

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 Spring’s Role as a Lifecycle Manager For nearly any class of application –Standalone Java application –JUnit System Test –Java EE™ web application –Java EE™ enterprise application Spring fits in to manage the application lifecycle –Plays an important role in all phases

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6 The Lifecycle of a Spring Application Context (1) - The Initialization Phase When you create a context the initialization phase completes But exactly what happens in this phase? // Create the application from the configuration ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { “application-config.xml”, “test-infrastructure-config.xml” });

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 The Context Initialization Lifecycle 1.Load bean definitions 2.Setup standard context services 3.Initialize bean instances

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 Load Bean Definitions 1.The XML files are parsed 2.Bean definitions are loaded into the context’s BeanFactory Each indexed under its id 3.Special BeanFactoryPostProcessor beans are invoked Can modify the definition of any bean

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9 Application Context Loading Bean Definitions <bean id=“transferService” … <bean id=“accountRepository”… <bean id=“transferService” … <bean id=“accountRepository”… application-config.xml <bean id=“dataSource” … <bean id=“dataSource” … test-infrastructure-config.xml transferService accountRepository transferService accountRepository BeanFactory BeanFactoryPostProcessors postProcess(BeanFactory) transferService accountRepository dataSource transferService accountRepository dataSource Can modify the definition of any bean in the factory before any objects are created

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 The BeanFactoryPostProcessor Extension Point Useful for applying transformations to groups of bean definitions –Before any objects are actually created Several useful ones are already provided in the framework You can also write your own

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 Useful BeanFactoryPostProcessors provided by Spring PropertyPlaceholderConfigurer subsitutes ${variables} in bean definitions with values from.properties files PropertyOverrideConfigurer overrides default bean definition property values with values in.properties files Explore the BeanFactoryPostProcessor type hierarchy for more

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 How PropertyPlaceholderConfigurer Works PropertyPlaceholderConfigurer Spring Application Context (after bean definitions are loaded) Bean definition “dataSource” URL=${datasource.url} user=${datasource.user} postProcess(BeanFactory) Bean definition “dataSource” URL=jdbc:oracle:… user=moneytransfer-app

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 Using PropertyPlaceholderConfigurer <bean class=“org.springframework.beans.factory.config. PropertyPlaceholderConfigurer”> File where the variable values reside datasource.user=moneytransfer-app datasource.properties Variables to replaceEasily editable

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 Using PropertyOverrideConfigurer <bean class=“org.springframework.beans.factory.config. PropertyOverrideConfigurer”> File where the default overrides reside dataSource.user=admin datasource.properties Default values Easily editable

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 Implementing Your Own BeanFactoryPostProcessor Implement this interface Configure as a bean (detected automatically) public interface BeanFactoryPostProcessor { void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException; } public interface BeanFactoryPostProcessor { void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory) throws BeansException; } … …

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 Ordered There may be many BeanFactoryPostProcessors per context Implement the Ordered interface to order them –Remember this as many things in Spring are Ordered … …

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17 Inside the Application Context Initialization Lifecycle 1.Load bean definitions 2.Setup standard context services 3.Initialize bean instances

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 Setup Standard Context Services A Spring application context sets itself up as a –ResourceLoader for loading environmental resources –MessageSource for resolving messages –ApplicationEventPublisher as an event bus Any bean can obtain a reference to these services when initialized

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 Standard Application Context Services ResourceLoader > MessageSource > ApplicationEventPublisher > ApplicationContext > getResource(String)publishEvent(AppEvent) getBean(String) getMessage(String)

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20 The Application Context as a Resource Loader Default resource loading rules depend on the ApplicationContext implementation in use –ClassPathXmlApplicationContext defaults to the classpath –FileSystemXmlApplicationContext defaults to the filesystem –WebApplicationContexts defaults to the web application root directory Use a resource prefix to override the default –classpath: - class path resources –file: or http: - URL resources

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Resource Loading Examples Class path context Web application context ClassPathXmlApplicationContext context = … context.getResource(“com/springsource/foo.xml”); context.getResource(“file:/home/rod/image.gif”); context.getResource(“file:working-directory/file.txt”); context.getResource(“ ClassPathXmlApplicationContext context = … context.getResource(“com/springsource/foo.xml”); context.getResource(“file:/home/rod/image.gif”); context.getResource(“file:working-directory/file.txt”); context.getResource(“ WebApplicationContext context = … context.getResource(“/WEB-INF/web.xml”); context.getResource(“classpath:com/springsource/foo.xml”); WebApplicationContext context = … context.getResource(“/WEB-INF/web.xml”); context.getResource(“classpath:com/springsource/foo.xml”);

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 Configuring Standard Context Services You may customize several of the other standard context services For example, configure a messageSource to customize how messages are resolved –Common for web applications

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Configuring a Message Source … <bean id=“messageSource” class=“org.springframework.context.support. ReloadableResourceBundleMessageSource”> … <bean id=“messageSource” class=“org.springframework.context.support. ReloadableResourceBundleMessageSource”> Automatically detected by the context Automatically detected by the context Will be automatically injected into beans that need messages Will be automatically injected into beans that need messages

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 The Context Initialization Lifecycle 1.Load bean definitions 2.Setup standard context services 3.Initialize bean instances

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Initialize Bean Instances Each bean is eagerly instantiated by default –Created in the right order with its dependencies injected After dependency injection each bean goes through a post-processing phase –Where further configuration and initialization can occur After post processing the bean is fully initialized and ready for use –Tracked by its id until the context is destroyed

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26 Bean Initialization Steps Bean Instantiated Dependencies Injected Bean Post Processed Bean Post Processed Bean Ready For Use Bean Ready For Use

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27 Bean Post Processing Bean post processing consists of several steps 1.Configure context services 2.Initialize the bean if instructed 3.Call special BeanPostProcessors to perform additional configuration

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 Bean Post Processing Steps 1.Configure context services 2.Initialize the bean if instructed 3.Call special BeanPostProcessors to perform additional configuration

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 Configure Context Services Recall a ApplicationContext is a provider of several services –ResourceLoader –MessageSource A bean can register itself as a consumer of one or more of these services Spring will automatically inject those services into the bean as part of post processing

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30 Registering for Context Services Register for context services by implementing special “aware” interfaces –ResourceLoaderAware for the resource loader –MessageSourceAware for the message source –ApplicationEventPublisherAware for the event bus –ApplicationContextAware for the context itself Useful if your bean needs to access files, resolve messages, publish events, or lookup other beans (respectively)

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31 A ResourceLoaderAware Bean public class BatchFileSender implements ResourceLoaderAware { private ResourceLoader resourceLoader; public void setResourceLoader(ResourceLoader rl) { this.resourceLoader = rl; } … } public class BatchFileSender implements ResourceLoaderAware { private ResourceLoader resourceLoader; public void setResourceLoader(ResourceLoader rl) { this.resourceLoader = rl; } … } Implements special “aware” interface Spring invokes setter automatically No other configuration required

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32 A MessageSourceAware Bean public class TransferMoneyAction implements Action, MessageSourceAware { private MessageSource messageSource; public void setMessageSource(MessageSouce ms) { this.messageSource = ms; } … } public class TransferMoneyAction implements Action, MessageSourceAware { private MessageSource messageSource; public void setMessageSource(MessageSouce ms) { this.messageSource = ms; } … } Implements special “aware” interface Spring invokes setter automatically No other configuration required

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33 Bean Post Processing Steps 1.Configure context services 2.Initialize the bean if instructed 3.Call special BeanPostProcessors to perform additional configuration

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34 Initialize the Bean if Instructed A bean can register for one or more initialization callbacks –Useful for executing custom initialization behaviors

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35 Registering for an Initialization Callback Register for a bean initialization callback by implementing the InitializingBean interface Spring will invoke this method at the right time public interface InitializingBean { void afterPropertiesSet() throws Exception; } public interface InitializingBean { void afterPropertiesSet() throws Exception; }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36 Implementing InitializingBean public class MessageReceiver implements InitializingBean { public void afterPropertiesSet() { // allocate message receiving resources } Implements special Spring lifecycle interface Spring invokes method automatically No other configuration required

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37 Initializing a Bean You Do Not Control Use init-method to initialize a bean you do not control the implementation of <bean id=“broker” class=“org.apache.activemq.broker.BrokerService” init-method=“start”> … Method must be a public with no arguments Class with no Spring dependency

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38 Bean Post Processing Steps 1.Configure context services 2.Initialize the bean if instructed 3.Call special BeanPostProcessors to perform additional configuration

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39 The BeanPostProcessor Extension Point Useful for applying additional configuration to groups of bean instances –Powerful enabling feature Several useful ones are already provided in the framework You can also write your own –Not that common

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40 How a BeanPostProcessor Works Every BeanPostProcessor gets two callbacks for each bean created by Spring The post processor manipulates the bean instance as it sees fit –Can even return a different object in place of the original public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName); Object postProcessAfterInitialization(Object bean, String beanName); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41 Invoking a BeanPostProcessor ApplicationContextBeanPostProcessor postProcessBeforeInitialization(Object, String) One of Your Beans create inject dependencies initialize postProcessAfterInitialization(Object, String) bean bean (or wrapper)

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 42 Implementing a BeanPostProcessor public class LogProvidingBeanPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) { if (bean instanceof LogAware) { Log log = LogFactory.getLog(bean.getClass()); ((LogAware) bean).setLog(log); } return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; } public interface LogAware { void setLog(Log log); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 43 Configuring a BeanPostProcessor Any bean that implements BeanPostProcessor is detected automatically The callbacks will be invoked as part of the bean instantiation phase …

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 44 Useful BeanPostProcessors provided by Spring RequiredAnnotationBeanPostProcessor enforces properties are set A factory that wraps your bean in a proxy to apply additional behaviors –Basis for Aspect Oriented Programming (AOP) in Spring –Extremely powerful Explore the BeanPostProcessor type hierarchy for more

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45 Using RequiredAnnotationBeanPostProcessor public void TransferServiceImpl implements TransferService { private AccountRepository public void setAccountRepository(AccountRepository ar) { this.accountRepository = ar; } public void TransferServiceImpl implements TransferService { private AccountRepository public void setAccountRepository(AccountRepository ar) { this.accountRepository = ar; } Indicates the dependency is required <bean class=“org.springframework.beans.factory.annotation. RequiredAnnotationBeanPostProcessor” /> <bean class=“org.springframework.beans.factory.annotation. RequiredAnnotationBeanPostProcessor” /> Automatically detected; no other configuration is necessary

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 46 The Lifecycle of a Spring Application Context (2) - The Use Phase When you invoke a bean obtained from the context the application is used But exactly what happens in this phase? ApplicationContext context = // get it from somewhere // Lookup the entry point into the application TransferService service = (TransferService) context.getBean(“transferService”); // Use it! service.transfer(new MonetaryAmount(“50.00”), “1”, “2”);

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 47 Inside The Bean Request (Use) Lifecycle If the bean is just your raw object it is simply invoked directly (nothing special) If your bean has been wrapped in a proxy things get more interesting TransferServiceImpl transfer(“$50”, “1”, 2”) TransferServiceImpl Spring Proxy

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 48 Proxy Power Dynamic proxies created by BeanPostProcessors may have added behaviors to your application logic transparently TransferServiceImpl transfer(“$50”, “1”, 2”) Spring TransactionInterceptor TransactionManager begincommit Transaction management behavior is added around your code Spring Proxy

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 49 Proxies are Central to the Spring Triangle Simple Object Dependency Injection Aspect-Oriented Programming Enterprise Service Abstractions 1. The Application context drives bean configuration 2.Dynamic proxies add behaviors to your beans 3.Spring can integrate many enterprise behaviors

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 50 The Lifecycle of a Spring Application Context (3) - The Destruction Phase When you close a context the destruction phase completes But exactly what happens in this phase? ConfigurableApplicationContext context = … // Destroy the application context.close();

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 51 Inside the Application Context Destruction Lifecycle 1.Destroy bean instances 2.Destroy itself The context is not usable again

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 52 Registering for a Destruction Callback Register for a bean destruction callback by implementing the DisposableBean interface Spring invokes this method at the right time public interface DisposableBean { void destroy(); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 53 Destroying a Bean You Do Not Control Use destroy-method to dispose a bean you do not control the implementation of <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource” destroy-method=“close”> … Method must be a public with no arguments Class with no Spring dependency

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 54 Topics in this session The lifecycle of a Spring application context –The initialization phase –The use phase –The destruction phase Other lifecycle considerations

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 55 Other Lifecycle Considerations Bean Scoping Lazy Beans Lifecycle interface

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 56 Bean Scoping Spring puts each bean instance in a scope Singleton scope is the default –The “single” instance is scoped by the context itself –By far the most common Other scopes can be used on a bean-by-bean basis <bean id=“myBean” class=“example.MyBean” scope=“…”> Put this bean in some other scope

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 57 Available Scopes prototype - A new instance is created each time the bean is referenced session - A new instance is created once per user session request - A new instance is created once per request custom - You define your own rules –Advanced feature

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 58 Lazy Beans Mark singleton beans that are expensive to create and rarely used lazy <bean id=“backupDataSource” class=“org.apache.commons.dbcp.BasicDataSource” destroy-method=“close” lazy-init=“true”> … Will not be created until referenced

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 59 The Lifecycle Interface Implement the Lifecycle interface for beans that start and stop threads ApplicationContext is a Lifecycle, and invokes Lifecycle methods on all enclosed Lifecycle beans public interface Lifecycle { void start(); void stop(); boolean isRunning(); } public interface Lifecycle { void start(); void stop(); boolean isRunning(); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 60 Implementing Lifecycle (and More) public class MessageReceiver implements InitializingBean, DisposableBean, Lifecycle { public void afterPropertiesSet() { // allocate message receiving resources } public void destroy() { // call stop (in case it hasn’t already been called) and de-allocate } public void start() { // start listening for messages } … Spring invokes init/destroy methods automatically; Lifecycle methods are called if invoked at the container level You may implement several Spring lifecycle interfaces

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Lab Understanding the Bean Lifecycle