我们在使用Spring框架的时候,常常需要注入相关的Bean,如果需要注入有相同类型的Bean的时候,会比较麻烦,需要一个一个注入,并且相对来说扩展性不是很好。
因此提供一种策略模式下获取Bean的方式。
public interface FactoryList<E extends MatchingBean<K>, K> extends List<E> {
E getBean(K factor);
List<E> getBeanList(K factor);
}
public interface MatchingBean<K> {
boolean matching(K factor);
}
public class FactoryListEditor extends CustomCollectionEditor {
public FactoryListEditor() {
super(FactoryArrayList.class);
this.addPropertyChangeListener(new InitializingBeanListener());
}
private class InitializingBeanListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
Object value = ((FactoryListEditor) evt.getSource()).getValue();
if (value instanceof InitializingBean) {
try {
((InitializingBean) value).afterPropertiesSet();
} catch (Exception e) {
throw new RuntimeException("初始化bean afterPropertiesSet异常", e);
}
}
}
}
}
public class FactoryArrayList<E extends MatchingBean<K>, K> extends ArrayList<E>
implements FactoryList<E, K>, InitializingBean, Serializable {
public FactoryArrayList() {
super();
}
public FactoryArrayList(int size) {
super(size);
}
public E getBean(K factor) {
Iterator<E> itr = iterator();
while (itr.hasNext()) {
E beanMatch = itr.next();
if (beanMatch.matching(factor)) {
return beanMatch;
}
}
return null;
}
public List<E> getBeanList(K factor) {
Iterator<E> itr = iterator();
while (itr.hasNext()) {
E beanMatch = itr.next();
if (!beanMatch.matching(factor)) {
itr.remove();
}
}
return this;
}
public void afterPropertiesSet() throws Exception {
if (!isEmpty()) {
Object[] a = toArray();
OrderComparator.sort(a);
ListIterator i = listIterator();
for (int j = 0; j < a.length; j++) {
i.next();
i.set(a[j]);
}
}
}
}
使用场景
public interface IProcessor<F> extends MatchingBean<F> {
public boolean go();
public InterfaceEnum getFunction();
}
public abstract class AbstractProcessor implements IProcessor<InterfaceEnum> {
@Override
public boolean matching(InterfaceEnum func) {
return this.getFunction() == func;
}
}
@Service
public class ChildProcessor extends AbstractProcessor {
@Override
public boolean go() {
XX
}
@Override
public InterfaceEnum getFunction() {
return InterfaceEnum.XXX;
}
}
最终使用
@Resource
private FactoryList<IProcessor<InterfaceEnum>, InterfaceEnum> processors;
private IProcessor getProcessor(InterfaceEnum enum) {
IProcessor p = processors.getBean(enum); //没有则返回null
return p;
}
此处可用作适配器,用来串联起整个标准化的接口业务
也可用Map<String,Interface> beanMap 来自动加载interface的Bean,不过要注意的是beanMap中的key是BeanName