SpringApplicationContextSupport.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.kmall.common;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.support.AbstractApplicationContext;
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;
  7. import org.springframework.web.context.ContextLoader;
  8. /**
  9. * 加载刷新 Spring 配置
  10. *
  11. * @author Scott Chen
  12. * @date 2017/2/27
  13. *
  14. */
  15. public abstract class SpringApplicationContextSupport {
  16. private final static Logger logger = LoggerFactory.getLogger(SpringApplicationContextSupport.class);
  17. private static AbstractApplicationContext applicationContext;
  18. /**
  19. * Create a new ClassPathXmlApplicationContext, loading the definitions
  20. * from the given XML file and automatically refreshing the context.
  21. * @param contextConfigPath context file
  22. * @return
  23. */
  24. public static final AbstractApplicationContext loadApplicationContext(final String contextConfigPath) {
  25. synchronized (logger) {
  26. if(applicationContext == null){
  27. logger.info("Initializing Spring context...");
  28. applicationContext = new ClassPathXmlApplicationContext(contextConfigPath);
  29. logger.info("Spring context initialized!");
  30. applicationContext.registerShutdownHook();
  31. }
  32. }
  33. return applicationContext;
  34. }
  35. /**
  36. * 获取Spring IOC 容器
  37. * @return
  38. */
  39. public static final ApplicationContext getApplicationContext() {
  40. if(applicationContext == null) {
  41. return ContextLoader.getCurrentWebApplicationContext();
  42. } else {
  43. return applicationContext;
  44. }
  45. }
  46. }