官术网_书友最值得收藏!

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" init-method="init" destroy-method="cleanup">
...
</bean>
主站蜘蛛池模板: 南靖县| 香港| 松潘县| 洮南市| 萨嘎县| 泊头市| 南城县| 西吉县| 兴城市| 宜都市| 正安县| 靖边县| 历史| 偏关县| 宜州市| 牟定县| 轮台县| 大同市| 宿松县| 梁山县| 诏安县| 和静县| 泾源县| 礼泉县| 景洪市| 仙桃市| 尤溪县| 滨海县| 盐山县| 汉阴县| 邵东县| 大洼县| 噶尔县| 广东省| 连江县| 苗栗县| 永和县| 昌平区| 宜都市| 达日县| 孟州市|