ContextUtils.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package com.uas.credit.util;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationEvent;
  5. /**
  6. * spring容器上下文对象
  7. * @author liuam
  8. * @since 2018/6/25 0025 下午 15:12
  9. */
  10. public class ContextUtils {
  11. private static ApplicationContext applicationContext;
  12. private static Logger logger = Logger.getLogger(ContextUtils.class);
  13. public static void setApplicationContext(ApplicationContext applicationContext) {
  14. logger.debug("setApplicationContext, notifyAll");
  15. ContextUtils.applicationContext = applicationContext;
  16. }
  17. /**
  18. * 获取上下文对象,需容器启动才可调用
  19. * @return
  20. */
  21. public static ApplicationContext getApplicationContext() {
  22. while (applicationContext == null) {
  23. try {
  24. logger.debug("getApplicationContext, wait...");
  25. ContextUtils.class.wait(60000);
  26. if (applicationContext == null) {
  27. logger.debug("Have been waiting for ApplicationContext to be set for 1 minute", new Exception());
  28. }
  29. } catch (InterruptedException ex) {
  30. logger.debug("getApplicationContext, wait interrupted");
  31. }
  32. }
  33. return applicationContext;
  34. }
  35. /**
  36. * 获取bean
  37. *
  38. * @param name
  39. * @return
  40. */
  41. public static Object getBean(String name) {
  42. return getApplicationContext().getBean(name);
  43. }
  44. /**
  45. * 获取bean
  46. *
  47. * @param cls
  48. * @return
  49. */
  50. public static <T> T getBean(Class<T> cls) {
  51. return getApplicationContext().getBean(cls);
  52. }
  53. /**
  54. * 触发事件
  55. *
  56. * @param event
  57. */
  58. public static void publishEvent(ApplicationEvent event) {
  59. getApplicationContext().publishEvent(event);
  60. }
  61. }