码迷,mamicode.com
首页 > 编程语言 > 详细

spring之Hooking to bean life cycles

时间:2016-04-29 19:23:05      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

spring之Hooking to bean life cycles


Often, in enterprise application development, developers will want to plug in some extra functionality to be executed just after the construction and before the destruction of a business service. Spring provides multiple methods for interacting with such stages in the life cycle of a bean.

Implementing InitializingBean and DisposableBean

The Spring IoC container invokes the callback methods afterPropertiesSet() of
org.springframework.beans.factory.InitializingBean and destroy() of org.springframework.beans.factory.DisposableBean on any Spring bean and implements them:


public class UserServiceImpl implements UserService, InitializingBean,
DisposableBean {
	...
	@Override
	public void afterPropertiesSet() throws Exception
	{
		logger.debug( this + ".afterPropertiesSet() invoked!" );
/* Your initialization code goes here.. */
	}


	@
	Override
	public void destroy() throws Exception
	{
		logger.debug( this + ".destroy() invoked!" );
/* Your cleanup code goes here.. */
	}


	...
}


Annotating @PostConstruct and @PreDestroy on @Components

Spring supports JSR 250 @PostConstruct and @PreDestroy annotations on any Spring bean in an annotation supported environment, as shown here. Spring encourages this approach over implementing Spring-specific interfaces, as given in the previous section:

@Service
public class AnnotatedTaskService implements TaskService {
	...
	@PostConstruct
	public void init()
	{
		logger.debug( this.getClass().getName() + " started!" );
	}


	@
	PreDestroy
	public void cleanup()
	{
		logger.debug( this.getClass().getName() + " is about to destroy!" );
	}


	...
}


The init-method and destroy-method attributes of <bean/>


If you are using XML-only bean configuration metadata, then your best option is to declare init-method and destroy-method attributes on your <bean/> tags:

<bean id = "xmlTaskService" class = "com…XmlDefinedTaskService" 
               initmethod = "init" 
               destroy - method = "cleanup" >
												       ...
< / bean>

Container-level default-init-method and default-destroy-method


You can even set container-level default init and destroy methods so that you don’t need to set it for each bean. The container invokes these methods on beans only if they are present:
<beans default - init - method = "init" default - destroy - method = "cleanup" >
								     ...
< / beans>



读书笔记:

Spring Essentials

Copyright ? 2016 Packt Publishing

First published: February 2016
Production reference: 1230216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-234-9
www.packtpub.com


spring之Hooking to bean life cycles

标签:

原文地址:http://blog.csdn.net/doctor_who2004/article/details/51232664

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!