柯桥增值式服务
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

96 líneas
2.8KB

  1. package com.ningdatech.kqapi.common.util;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.util.Assert;
  4. import java.util.Map;
  5. /**
  6. * Spring工具类
  7. *
  8. * @author WendyYang
  9. * @date 2017-12-25 16:27
  10. */
  11. public final class SpringUtils {
  12. private SpringUtils() {
  13. }
  14. /**
  15. * 单例Holder模式: 优点:将懒加载和线程安全完美结合的一种方式(无锁)。(推荐)
  16. *
  17. * @return 实实例
  18. */
  19. public static SpringUtils getInstance() {
  20. return SpringUtilsHolder.INSTANCE;
  21. }
  22. private static ApplicationContext applicationContext;
  23. private static ApplicationContext parentApplicationContext;
  24. public static ApplicationContext getApplicationContext() {
  25. return applicationContext;
  26. }
  27. public static void setApplicationContext(ApplicationContext ctx) {
  28. Assert.notNull(ctx, "SpringUtil injection ApplicationContext is null");
  29. applicationContext = ctx;
  30. parentApplicationContext = ctx.getParent();
  31. }
  32. public static Object getBean(String name) {
  33. Assert.hasText(name, "SpringUtil name is null or empty");
  34. try {
  35. return applicationContext.getBean(name);
  36. } catch (Exception e) {
  37. return parentApplicationContext.getBean(name);
  38. }
  39. }
  40. public static <T> T getBean(String name, Class<T> type) {
  41. Assert.hasText(name, "SpringUtil name is null or empty");
  42. Assert.notNull(type, "SpringUtil type is null");
  43. try {
  44. return applicationContext.getBean(name, type);
  45. } catch (Exception e) {
  46. return parentApplicationContext.getBean(name, type);
  47. }
  48. }
  49. public static <T> T getBean(Class<T> type) {
  50. Assert.notNull(type, "SpringUtil type is null");
  51. try {
  52. return applicationContext.getBean(type);
  53. } catch (Exception e) {
  54. return parentApplicationContext.getBean(type);
  55. }
  56. }
  57. public static <T> Map<String, T> getBeansOfType(Class<T> type) {
  58. Assert.notNull(type, "SpringUtil type is null");
  59. try {
  60. return applicationContext.getBeansOfType(type);
  61. } catch (Exception e) {
  62. return parentApplicationContext.getBeansOfType(type);
  63. }
  64. }
  65. public static ApplicationContext publishEvent(Object event) {
  66. applicationContext.publishEvent(event);
  67. return applicationContext;
  68. }
  69. /**
  70. * <p>
  71. * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
  72. * 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
  73. */
  74. private static class SpringUtilsHolder {
  75. /**
  76. * 静态初始化器,由JVM来保证线程安全
  77. */
  78. private static final SpringUtils INSTANCE = new SpringUtils();
  79. }
  80. }