spring的初始化bean,销毁bean之前的操作详解
我所知道的在spring初始化bean,销毁bean之前的操作有三种方式:
第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
第二种是:通过 在xml中定义init-method 和 destory-method方法
第三种是: 通过bean实现InitializingBean和 DisposableBean接口
直接上xml中配置文件:
<bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="singleton" init-method="init" destroy-method="cleanUp">
</bean>
@PostConstruct和 @PreDestroy注解在bean中方法名上即可在初始化或销毁bean之前执行。
实现InitializingBean和DisposableBean接口接口,举例如下:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.suning.ecif.admin.app.cfg.KeyValueService;
import com.suning.ecif.admin.entity.KeyValue;
/**
* 配置管理,增加后台对tb9005的jvm缓存配置
*
* @author djw
* @version 1.0 2015-12-01
*/
@Service
public class DBConfigManager implements InitializingBean {
@Autowired
KeyValueService keyValueService;
private static Logger log = LoggerFactory.getLogger(DBConfigManager.class);
// Config file properties
private Map<String, String> theProperties = new HashMap<String, String>();
/**
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet() throws Exception {
init();
}
public void init() {
try {
List<KeyValue> queryKeyValues = keyValueService.queryKeyValue(null);
Map<String, String> map = new HashMap<String, String>();
for (KeyValue keyValue : queryKeyValues) {
String key = keyValue.getKey() == null ? null : keyValue.getKey().trim();
String value = keyValue.getValue() == null ? null : keyValue.getValue().trim();
map.put(key, value);
}
theProperties = map;
} catch (Exception e) {
log.error("DBConfigManager.init()", e);
} finally {
}
}
/**
* get the Config Value
*
* @param key
* Config_key
* @return Config_value
*/
public String getConfigValue(String key) {
return theProperties.get(key);
}
/**
* get the Config Value, if not exists then return the default value
*
* @param key
* Config_key
* @param defaultValue
* default_Value
* @return Config_value or default_Value
*/
public String getConfigValue(String key, String defaultValue) {
if ( theProperties.get(key) == null) {
return defaultValue;
}
return theProperties.get(key);
}
}
实现InitializingBean接口,实现afterPropertiesSet方法,该方法表明是在资源加载完以后,初始化bean之前执行的方法,同样DisposableBean就是在一个bean被销毁的时候,spring容器会帮你自动执行这个方法;
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~