Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An."— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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” });

7 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

8 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

9 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

10 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

11 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

12 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

13 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.url=jdbc:oracle:thin:@localhost:1521:BANK datasource.user=moneytransfer-app datasource.properties Variables to replaceEasily editable

14 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.URL=jdbc:oracle:thin:@localhost:1521:BANK dataSource.user=admin datasource.properties Default values Easily editable

15 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; } … …

16 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 … …

17 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

18 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

19 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)

20 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

21 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(“http://springsource.com/training/index.html”); ClassPathXmlApplicationContext context = … context.getResource(“com/springsource/foo.xml”); context.getResource(“file:/home/rod/image.gif”); context.getResource(“file:working-directory/file.txt”); context.getResource(“http://springsource.com/training/index.html”); 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”);

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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)

31 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

32 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

33 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

34 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

35 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; }

36 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

37 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

38 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

39 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

40 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); }

41 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)

42 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); }

43 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 …

44 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 44 Useful BeanPostProcessors provided by Spring RequiredAnnotationBeanPostProcessor enforces that @Required 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

45 Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 45 Using RequiredAnnotationBeanPostProcessor public void TransferServiceImpl implements TransferService { private AccountRepository accountRepository; @Required public void setAccountRepository(AccountRepository ar) { this.accountRepository = ar; } public void TransferServiceImpl implements TransferService { private AccountRepository accountRepository; @Required 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

46 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”);

47 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

48 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

49 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

50 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();

51 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

52 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(); }

53 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

54 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

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

56 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

57 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

58 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

59 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(); }

60 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

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


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

Similar presentations


Ads by Google