根据Bean名称查找

Spring方式

  1. public static void main(String[] main) {
  2. BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
  3. User user = beanFactory.getBean("user");
  4. }

Spring Boot方式

  1. @Component
  2. public class SpringContextUtil implements ApplicationContextAware {
  3. private static ApplicationContext applicationContext;
  4. public SpringContextUtil() {
  5. }
  6. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  7. applicationContext = applicationContext;
  8. }
  9. public static <T> T getBean(String name) {
  10. return this.applicationContext.getBean(name);
  11. }
  12. }

根据Bean类型查找

Spring方式

  1. # 根据类型查找只有一个bean
  2. public static void main(String[] main) {
  3. BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
  4. User user = beanFactory.getBean(User.class);
  5. }
  6. # 根据类型查找存在多个bean
  7. public static void main(String[] main) {
  8. BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
  9. if(beanFactory intanceof ListableBeanFactory) {
  10. ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
  11. Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
  12. }
  13. }

Spring Boot方式

  1. @Component
  2. public class SpringContextUtil implements ApplicationContextAware {
  3. private static ApplicationContext applicationContext;
  4. public SpringContextUtil() {
  5. }
  6. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  7. applicationContext = applicationContext;
  8. }
  9. public static <T> T getBean(Class<T> clazz) {
  10. return this.applicationContext.getBeansOfType(clazz);
  11. }
  12. }