- Spring Essentials
- Shameer Kunjumohamed Hamidreza Sattari
- 224字
- 2021-07-16 13:05:47
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>
- C# 7 and .NET Core Cookbook
- LabVIEW入門與實戰開發100例
- Flask Web開發入門、進階與實戰
- Python數據可視化之Matplotlib與Pyecharts實戰
- 基于Swift語言的iOS App 商業實戰教程
- Mastering Apache Maven 3
- C#應用程序設計教程
- iOS自動化測試實戰:基于Appium、Python與Pytest
- Kivy Cookbook
- HTML+CSS+JavaScript網頁設計從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Hands-On JavaScript for Python Developers
- C語言程序設計實訓教程與水平考試指導
- scikit-learn Cookbook(Second Edition)
- After Effects CC案例設計與經典插件(視頻教學版)
- 信息學奧林匹克競賽初賽精講精練