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容器会帮你自动执行这个方法;

 

posted @ 2016-08-03 10:31  前度刘郎  阅读(2246)  评论(0编辑  收藏  举报
欢迎来到戴建伟的博客!