SpringUtils.java 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package com.dataeasy.server.utiis;
  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. * Spring上下文 工具类
  8. */
  9. @Component
  10. public class SpringUtils implements ApplicationContextAware {
  11. private static ApplicationContext applicationContext;
  12. @Override
  13. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  14. SpringUtils.applicationContext = applicationContext;
  15. }
  16. /**
  17. * 通过class获取Bean.
  18. *
  19. * @param clazz
  20. * @param <T>
  21. * @return
  22. */
  23. public static <T> T getBean(Class<T> clazz) {
  24. return applicationContext.getBean(clazz);
  25. }
  26. /**
  27. * 通过bean的名称获取对应的bean
  28. * @param beanName bean的名称
  29. * @return
  30. * @param <T>
  31. */
  32. public static <T> T getBean(String beanName) {
  33. return (T) applicationContext.getBean(beanName);
  34. }
  35. }