1. package com.zara.utils.spring;
    2. import org.springframework.beans.BeansException;
    3. import org.springframework.context.ApplicationContext;
    4. import org.springframework.context.ApplicationContextAware;
    5. import org.springframework.lang.Nullable;
    6. import org.springframework.stereotype.Component;
    7. /**
    8. * Title: Spring 上下文工具
    9. * Description:该工具类必须声明为Spring 容器里的一个Bean对象,否则无法自动注入ApplicationContext对象
    10. * Date: 2021/4/16 10:09
    11. *
    12. * @author JiaQi Ding
    13. * @version 1.0
    14. */
    15. @Component
    16. public class SpringContextUtil implements ApplicationContextAware {
    17. private static ApplicationContext context;
    18. /**
    19. * 根据Bean名称获取Bean对象
    20. *
    21. * @param name Bean名称
    22. * @return 对应名称的Bean对象
    23. */
    24. public static Object getBean(String name) {
    25. return context.getBean(name);
    26. }
    27. /**
    28. * 根据Bean的类型获取对应的Bean
    29. *
    30. * @param requiredType Bean类型
    31. * @return 对应类型的Bean对象
    32. */
    33. public static <T> T getBean(Class<T> requiredType) {
    34. return context.getBean(requiredType);
    35. }
    36. /**
    37. * 根据Bean名称获取指定类型的Bean对象
    38. *
    39. * @param name Bean名称
    40. * @param requiredType Bean类型(可为空)
    41. * @return 获取对应Bean名称的指定类型Bean对象
    42. */
    43. public static <T> T getBean(String name, Class<T> requiredType) {
    44. return context.getBean(name, requiredType);
    45. }
    46. /**
    47. * 判断是否包含对应名称的Bean对象
    48. *
    49. * @param name Bean名称
    50. * @return 包含:返回true,否则返回false。
    51. */
    52. public static boolean containsBean(String name) {
    53. return context.containsBean(name);
    54. }
    55. /**
    56. * 获取对应Bean名称的类型
    57. *
    58. * @param name Bean名称
    59. * @return 返回对应的Bean类型
    60. */
    61. public static Class<?> getType(String name) {
    62. return context.getType(name);
    63. }
    64. /**
    65. * 获取上下文对象,可进行各种Spring的上下文操作
    66. *
    67. * @return Spring上下文对象
    68. */
    69. public static ApplicationContext getContext() {
    70. return context;
    71. }
    72. /**
    73. * Spring在bean初始化后会判断是不是ApplicationContextAware的子类
    74. * 如果该类是,setApplicationContext()方法,会将容器中ApplicationContext作为参数传入进去
    75. */
    76. @Override
    77. public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
    78. context = applicationContext;
    79. }
    80. }