e8d0879ad6b08f90ba12a7b589f97a68312609af.svn-base 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package org.jeecg.common.util;
  2. import cn.hutool.core.util.ObjectUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. /**
  7. * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
  8. *
  9. * @author zyf
  10. */
  11. @Slf4j
  12. public class SpringContextHolder implements ApplicationContextAware {
  13. private static ApplicationContext applicationContext;
  14. /**
  15. * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
  16. */
  17. @Override
  18. public void setApplicationContext(ApplicationContext applicationContext) {
  19. // NOSONAR
  20. SpringContextHolder.applicationContext = applicationContext;
  21. }
  22. /**
  23. * 取得存储在静态变量中的ApplicationContext.
  24. */
  25. public static ApplicationContext getApplicationContext() {
  26. checkApplicationContext();
  27. return applicationContext;
  28. }
  29. /**
  30. * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
  31. */
  32. public static <T> T getBean(String name) {
  33. checkApplicationContext();
  34. return (T) applicationContext.getBean(name);
  35. }
  36. /**
  37. * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
  38. */
  39. public static <T> T getHandler(String name, Class<T> cls) {
  40. T t = null;
  41. if (ObjectUtil.isNotEmpty(name)) {
  42. checkApplicationContext();
  43. try {
  44. t = applicationContext.getBean(name, cls);
  45. } catch (Exception e) {
  46. log.error("####################" + name + "未定义");
  47. }
  48. }
  49. return t;
  50. }
  51. /**
  52. * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
  53. */
  54. public static <T> T getBean(Class<T> clazz) {
  55. checkApplicationContext();
  56. return applicationContext.getBean(clazz);
  57. }
  58. /**
  59. * 清除applicationContext静态变量.
  60. */
  61. public static void cleanApplicationContext() {
  62. applicationContext = null;
  63. }
  64. private static void checkApplicationContext() {
  65. if (applicationContext == null) {
  66. throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
  67. }
  68. }
  69. }