package com.kmall.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;

/**
 * 加载刷新 Spring 配置
 *
 * @author Scott Chen
 * @date 2017/2/27
 *
 */
public abstract class SpringApplicationContextSupport {
  private final static Logger logger = LoggerFactory.getLogger(SpringApplicationContextSupport.class);
  
  private static AbstractApplicationContext applicationContext;
  
  /**
   * Create a new ClassPathXmlApplicationContext, loading the definitions
   * from the given XML file and automatically refreshing the context.
   * @param contextConfigPath context file
   * @return
   */
  public static final AbstractApplicationContext loadApplicationContext(final String contextConfigPath) {
    synchronized (logger) {
      if(applicationContext == null){
        logger.info("Initializing Spring context...");

        applicationContext = new ClassPathXmlApplicationContext(contextConfigPath);

        logger.info("Spring context initialized!");

        applicationContext.registerShutdownHook();
      }
    }
    
    return applicationContext;
  }
  
  /**
   * 获取Spring IOC 容器
   * @return
   */
  public static final ApplicationContext getApplicationContext() {
    if(applicationContext == null) {
      return ContextLoader.getCurrentWebApplicationContext();
    } else {
      return applicationContext;
    }
  }
}