ContextUtil.java 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.util;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.ApplicationEvent;
  4. public class ContextUtil {
  5. private static ApplicationContext applicationContext;
  6. public static void setApplicationContext(ApplicationContext applicationContext) {
  7. synchronized (ContextUtil.class) {
  8. ContextUtil.applicationContext = applicationContext;
  9. ContextUtil.class.notifyAll();
  10. }
  11. }
  12. public static ApplicationContext getApplicationContext() {
  13. synchronized (ContextUtil.class) {
  14. while (applicationContext == null) {
  15. try {
  16. ContextUtil.class.wait(6000);
  17. } catch (InterruptedException ex) {
  18. }
  19. }
  20. return applicationContext;
  21. }
  22. }
  23. /**
  24. * 获取bean
  25. *
  26. * @param name
  27. * @return
  28. */
  29. public static Object getBean(String name) {
  30. try {
  31. return getApplicationContext().getBean(name);
  32. } catch (Exception e) {
  33. return null;
  34. }
  35. }
  36. /**
  37. * 获取bean
  38. *
  39. * @param cls
  40. * @return
  41. */
  42. public static <T> T getBean(Class<T> cls) {
  43. return getApplicationContext().getBean(cls);
  44. }
  45. /**
  46. * 触发事件
  47. *
  48. * @param event
  49. */
  50. public static void publishEvent(ApplicationEvent event) {
  51. getApplicationContext().publishEvent(event);
  52. }
  53. }