1. import org.apache.commons.lang3.Validate;
    2. import org.springframework.beans.factory.DisposableBean;
    3. import org.springframework.context.ApplicationContext;
    4. import org.springframework.context.ApplicationContextAware;
    5. import org.springframework.context.annotation.Lazy;
    6. import org.springframework.stereotype.Service;
    7. @Service
    8. @Lazy(false)
    9. public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    10. private static ApplicationContext applicationContext = null;
    11. /**
    12. * 取得存储在静态变量中的ApplicationContext.
    13. */
    14. public static ApplicationContext getApplicationContext() {
    15. assertContextInjected();
    16. return applicationContext;
    17. }
    18. /**
    19. * 通过name获取 Bean
    20. * @param name 类名称
    21. * @return 实例对象
    22. */
    23. public static Object getBean(String name){
    24. return getApplicationContext().getBean(name);
    25. }
    26. /**
    27. * 通过class获取Bean
    28. */
    29. public static <T> T getBean(Class<T> clazz){
    30. return getApplicationContext().getBean(clazz);
    31. }
    32. /**
    33. * 通过name,以及Clazz返回指定的Bean
    34. */
    35. public static <T> T getBean(String name,Class<T> clazz){
    36. return getApplicationContext().getBean(name, clazz);
    37. }
    38. /**
    39. * 清除SpringContextHolder中的ApplicationContext为Null.
    40. */
    41. public static void clearHolder() {
    42. applicationContext = null;
    43. }
    44. /**
    45. * 实现ApplicationContextAware接口, 注入Context到静态变量中.
    46. */
    47. @Override
    48. public void setApplicationContext(ApplicationContext appContext) {
    49. applicationContext = appContext;
    50. }
    51. /**
    52. * 实现DisposableBean接口, 在Context关闭时清理静态变量.
    53. */
    54. @Override
    55. public void destroy() throws Exception {
    56. SpringContextHolder.clearHolder();
    57. }
    58. /**
    59. * 检查ApplicationContext不为空.
    60. */
    61. private static void assertContextInjected() {
    62. Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    63. }
    64. }