Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Lifecycle of Spring beans

A full-length sample module from our Spring training (http://www.oktech.hu/training/spring).
by

Szabolcs Szádeczky-Kardoss

on 8 December 2011

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Lifecycle of Spring beans

Initialization
Use
Destruction
Loading bean definitions
Initialize bean instances
Setup context services
Parsing XML configuration files
Loading bean definitions into the
BeanFactory
Each bean is indexed with its id
Bean definition post processing, if requested
via
BeanFactoryPostProcessor
s
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xmlns:context="..." xsi:schemaLocation="...">

<bean id="exampleBean" class="com.example.ExampleBean">
<property name="username" value="${example.username}"/>
<property name="password" value="${example.password}"/>
</bean>

<bean class="org.springframework.beans.factory.config.
PropertyPlaceholderConfigurer
">
<property name="location" value="
/META-INF/auth.properties
"/>
</bean>

<!-- Or use the following shorthand notation, courtesy of XML namespaces since 2.5 -->
<context:property-placeholder location="
/META-INF/auth.properties
"/>

</beans>
#Contents of
/META-INF/auth.properties
example.username=admin
example.password=adminadmin
#Contents of
/META-INF/auth.properties
exampleBean.username=admin
exampleBean.password=adminadmin
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xmlns:context="..." xsi:schemaLocation="...">

<bean id="exampleBean" class="com.example.ExampleBean">
<property name="username" value="guest"/>
</bean>

<bean class="org.springframework.beans.factory.config.
PropertyOverrideConfigurer
">
<property name="location" value="
/META-INF/auth.properties
"/>
</bean>

<!-- Or use the following shorthand notation, courtesy of XML namespaces since 2.5 -->
<context:property-override location="
/META-INF/auth.properties
"/>

</beans>
/* You can also create your custom BeanFactoryPostProcessor easily */
public interface BeanFactoryPostProcessor {

/**
* Modify the application context's internal bean factory after its
* standard initialization. All bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for
* overriding or adding properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException ();

}
An
ApplicationContext
includes the bean instantiation feature of a
BeanFactory
and more:
Internationalization using
MessageSource
s
ApplicationEvent
publication
Access to
Resource
s such as URLs and Files
Automatic
BeanFactoryPostProcessor
and
BeanPostProcessor
registration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">

<bean id="
messageSource
"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages"/>
</bean>

<!-- If messageSource is not explicitly specified, an empty StaticMessageSource is created -->

</beans>
The Observer design pattern is realized:
The
ApplicationContext
notifies all beans implementing the
ApplicationListener
interface about all published
ApplicationEvent
s
Spring provides these standard events:
ContextRefreshedEvent
ContextStartedEvent
ContextStoppedEvent
ContextClosedEvent
RequestHandledEvent
Resources are enhanced java.net.URLs that help in obtaining low-level resources from the file system, classpath or URL
<!-- Resources can be injected... -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">

<bean id="exampleBean" class="com.example.ExampleBean">
<property name="myResource" value="com/example/example.xml"/>
</bean>

</beans>
// ... or requested
ApplicationContext context = new
ClassPathXmlApplicationContext("application-config.xml");
Resource myResource =
context.getResource("com/example/example.xml");
After standard instantiation post-processing can happen, if requested
Beans are eagerly instantiated, by default
Creation and dependency injection in the right order
Finally the beans are fully initialized and can be used
Configure context services
Applying
BeanPostProcessor
s
Custom bean initialization
A bean can register for one or more of the context services by implementing special interfaces
(ResourceLoaderAware,

MessageSourceAware,

ApplicationEventPublisherAware
/
ApplicationListener,

ApplicationContextAware)
Spring automatically detects such beans and injects the requested service(s)
package com.example;
public class ExampleBean implements
ApplicationEventPublisherAware
,
ResourceLoaderAware
{
private ApplicationEventPublisher eventPublisher;
private ResourceLoader resourceLoader;

public void businessMethod(...) {
...
Resource myResource =
resourceLoader.
getResource
("classpath:com/example/example.xml");
eventPublisher.
publishEvent
(new ResourceLoadedEvent(myResource));
...
}

public void
setApplicationEventPublisher
(
ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}

public void
setResourceLoader
(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
Spring can be instructed to call a special method in your bean during initialization
package com.example;
public class ExampleBean implements

InitializingBean
{
...
public void
afterPropertiesSet
() {
...
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<bean id="exampleBean" class="com.example.ExampleBean"
init-method="
init
"/>
</beans>
_________________________________________________________________
package com.example;
public class ExampleBean {
...
public void
init()
{
...
}
}
Spring puts an emphasis on „convention over configuration” in several areas
Bean initialization and destroy methods are such
Default initialization and destroy method names can be specified
Use the
default-init-method
and
default-destroy-method
attributes on the
<beans>
element
Default name can be overriden on a particular bean
Additional configuration or transformations can be applied on one or more bean instances
There are some useful BeanPostProcessors:
AbstractAutoProxyCreator
and its subclasses
ApplicationContextAwareProcessor
A custom one can also be implemented
public interface
BeanPostProcessor
{
Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException ();
Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException ();
}
package com.example;
public class ExampleBean {
private AnotherBean anotherBean;


@Required
public void setAnotherBean(AnotherBean anotherBean) {
this.anotherBean = anotherBean;
}
}
____________________________________________________________________________________________________________
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<bean id="exampleBean" class="com.example.ExampleBean">
...
</bean>

<bean class="org.springframework.beans.factory.annotation.
RequiredAnnotationBeanPostProcessor
">
</bean>
</beans>
If you want lazy initialization:
Use lazy-init=”true” on the bean element
Such beans will be only instantiated when they are first requested
Except if they are a dependency of another not-lazily initiated bean
The default behavior of the container can also be changed
Things to do at shutdown:
Resources have to be released properly
Allocated memory should be freed up
How?
Triggers of an application shutdown:
Web/EJB application stop/undeploy
Web/EJB container shutdown
JVM exit
// Get a reference to the application context
ConfigurableApplicationContext context = ...;
// Shut it down
context.close();
Web-based application contexts handle web application shutdown appropriately.
Non-web IoC containers can also do so easily:
context.registerShutdownHook();
Indirectly using java.lang.Runtime's addShutdownHook(...) in the background
Stop beans that implement the
Lifecycle
interface
Call destroy method(s) on beans
Destroy the context itself
public interface Lifecycle {
/**
* Start this component.
* Should not throw an exception if the component is already running.
*/
void start();

/**
* Stop this component.
* Should not throw an exception if the component isn't started yet.
*/
void stop();

/**
* Check whether this component is currently running.
* @return whether the component is currently running
*/
boolean isRunning();
}
Spring takes care to destroy dependent beans first
In opposite order to initialization
package com.example;
public class ExampleBean implements
DisposableBean
{
...
public void
destroy()
{
...
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="..." xmlns:xsi="..." xsi:schemaLocation="...">
<bean id="exampleBean" class="com.example.ExampleBean"
destroy-method="
kill
"/>
</beans>
_________________________________________________________________
package com.example;
public class ExampleBean {
...
public void
kill()
{
...
}
}
Full transcript