ContextUtil.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package com.uas.eis.utils;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationEvent;
  5. public class ContextUtil {
  6. private static ApplicationContext applicationContext;
  7. public static void setApplicationContext(ApplicationContext applicationContext) {
  8. synchronized (ContextUtil.class) {
  9. ContextUtil.applicationContext = applicationContext;
  10. ContextUtil.class.notifyAll();
  11. }
  12. }
  13. public static ApplicationContext getApplicationContext() {
  14. synchronized (ContextUtil.class) {
  15. while (applicationContext == null) {
  16. try {
  17. ContextUtil.class.wait(6000);
  18. } catch (InterruptedException ex) {
  19. }
  20. }
  21. return applicationContext;
  22. }
  23. }
  24. /**
  25. * 获取bean
  26. *
  27. * @param name
  28. * @return
  29. */
  30. public static Object getBean(String name) {
  31. try {
  32. return getApplicationContext().getBean(name);
  33. } catch (Exception e) {
  34. return null;
  35. }
  36. }
  37. /**
  38. * 获取bean
  39. *
  40. * @param cls
  41. * @return
  42. */
  43. public static <T> T getBean(Class<T> cls) {
  44. return getApplicationContext().getBean(cls);
  45. }
  46. /**
  47. * 动态注册bean
  48. *
  49. * @param beanName
  50. * bean组件名称
  51. * @param className
  52. * 类名
  53. */
  54. public static void registerBean(String beanName, String className) {
  55. try {
  56. getApplicationContext().getAutowireCapableBeanFactory().createBean(Class.forName(className));
  57. } catch (BeansException e) {
  58. BaseUtil.showError("组件注册失败");
  59. } catch (IllegalStateException e) {
  60. BaseUtil.showError("组件注册失败");
  61. } catch (ClassNotFoundException e) {
  62. BaseUtil.showError("组件注册失败");
  63. }
  64. }
  65. /**
  66. * 触发事件
  67. *
  68. * @param event
  69. */
  70. public static void publishEvent(ApplicationEvent event) {
  71. getApplicationContext().publishEvent(event);
  72. }
  73. }