SpringContextUtil.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package com.huaxu.zoniot.utils;
  2. import org.apache.commons.lang3.ArrayUtils;
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * @author pengdi
  9. */
  10. @Component
  11. public class SpringContextUtil implements ApplicationContextAware {
  12. private static ApplicationContext context;
  13. @Override
  14. public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException {
  15. SpringContextUtil.context = applicationcontext;
  16. }
  17. public static Object getBean(String beanName) {
  18. return context.getBean(beanName);
  19. }
  20. public static <T> T getBean(Class<T> clazz) {
  21. String[] beanNames = context.getBeanNamesForType(clazz);
  22. if (ArrayUtils.isEmpty(beanNames)) {
  23. throw new IllegalArgumentException("There are no bean of type " + clazz.getName());
  24. } else if (beanNames.length > 1) {
  25. throw new IllegalArgumentException("There are more than one bean of type " + clazz.getName());
  26. }
  27. return (T) getBean(beanNames[0]);
  28. }
  29. }