我所知道的在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容器會幫你自動執行這個方法;