ContextUtil.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.uas.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. ex.printStackTrace();
  20. }
  21. }
  22. return applicationContext;
  23. }
  24. }
  25. /**
  26. * 获取bean
  27. *
  28. * @param name
  29. * @return
  30. */
  31. public static Object getBean(String name) {
  32. try {
  33. return getApplicationContext().getBean(name);
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. return null;
  37. }
  38. }
  39. /**
  40. * 获取bean
  41. *
  42. * @param cls
  43. * @return
  44. */
  45. public static <T> T getBean(Class<T> cls) {
  46. return getApplicationContext().getBean(cls);
  47. }
  48. /**
  49. * 动态注册bean
  50. *
  51. * @param beanName
  52. * bean组件名称
  53. * @param className
  54. * 类名
  55. */
  56. public static void registerBean(String beanName, String className) {
  57. try {
  58. getApplicationContext().getAutowireCapableBeanFactory().createBean(Class.forName(className));
  59. } catch (BeansException e) {
  60. BaseUtil.showError("组件注册失败");
  61. } catch (IllegalStateException e) {
  62. BaseUtil.showError("组件注册失败");
  63. } catch (ClassNotFoundException e) {
  64. BaseUtil.showError("组件注册失败");
  65. }
  66. }
  67. /**
  68. * 触发事件
  69. *
  70. * @param event
  71. */
  72. public static void publishEvent(ApplicationEvent event) {
  73. getApplicationContext().publishEvent(event);
  74. }
  75. }