SmartApplicationContext.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package net.lab1024.smartadmin.third;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * [ApplicationContextHelper]
  8. *
  9. * @author yandanyang
  10. * @version 1.0
  11. * @since JDK1.8
  12. */
  13. @Component
  14. public class SmartApplicationContext implements ApplicationContextAware {
  15. /**
  16. * 上下文对象实例
  17. */
  18. private static ApplicationContext applicationContext = null;
  19. @Override
  20. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  21. if(SmartApplicationContext.applicationContext == null){
  22. SmartApplicationContext.applicationContext = applicationContext;
  23. }
  24. }
  25. /**
  26. * 获取applicationContext
  27. * @return
  28. */
  29. public static ApplicationContext getApplicationContext() {
  30. return applicationContext;
  31. }
  32. /**
  33. * 通过name获取 Bean.
  34. * @param name
  35. * @return
  36. */
  37. public static Object getBean(String name){
  38. ApplicationContext applicationContext = getApplicationContext();
  39. if(applicationContext == null){
  40. return null;
  41. }
  42. return applicationContext.getBean(name);
  43. }
  44. /**
  45. * 通过class获取Bean.
  46. * @param clazz
  47. * @param <T>
  48. * @return
  49. */
  50. public static <T> T getBean(Class<T> clazz){
  51. ApplicationContext applicationContext = getApplicationContext();
  52. if(applicationContext == null){
  53. return null;
  54. }
  55. return applicationContext.getBean(clazz);
  56. }
  57. /**
  58. * 通过name,以及Clazz返回指定的Bean
  59. * @param name
  60. * @param clazz
  61. * @param <T>
  62. * @return
  63. */
  64. public static <T> T getBean(String name,Class<T> clazz){
  65. ApplicationContext applicationContext = getApplicationContext();
  66. if(applicationContext == null){
  67. return null;
  68. }
  69. return applicationContext.getBean(name, clazz);
  70. }
  71. }