001
002 /*
003 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004 *
005 * $Id: BeanNameComparator.java 209 2012-01-12 15:52:06Z archie.cobbs $
006 */
007
008 package org.dellroad.stuff.spring;
009
010 import java.util.Comparator;
011 import java.util.HashMap;
012
013 import org.springframework.beans.factory.ListableBeanFactory;
014
015 /**
016 * A {@link Comparator} that orders Spring bean names in the same order as the corresponding
017 * beans appear in a {@link ListableBeanFactory}.
018 *
019 * <p>
020 * Names that are not present in the configured {@link ListableBeanFactory} cause an exception.
021 */
022 public class BeanNameComparator implements Comparator<String> {
023
024 private final HashMap<String, Integer> beanNameMap;
025 private final String factoryName;
026
027 public BeanNameComparator(ListableBeanFactory beanFactory) {
028 String[] beanNames = beanFactory.getBeanDefinitionNames();
029 this.beanNameMap = new HashMap<String, Integer>(beanNames.length);
030 for (int i = 0; i < beanNames.length; i++)
031 this.beanNameMap.put(beanNames[i], i);
032 this.factoryName = "" + beanFactory;
033 }
034
035 @Override
036 public int compare(String name1, String name2) {
037 Integer index1 = this.beanNameMap.get(name1);
038 Integer index2 = this.beanNameMap.get(name2);
039 if (index1 == null)
040 throw new IllegalArgumentException("failed to find bean `" + name1 + "' in bean factory " + this.factoryName);
041 if (index2 == null)
042 throw new IllegalArgumentException("failed to find bean `" + name2 + "' in bean factory " + this.factoryName);
043 return index1 - index2;
044 }
045 }
046