當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
Spring动态注入泛型集合Bean
生活随笔
收集整理的這篇文章主要介紹了
Spring动态注入泛型集合Bean
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
我們?cè)谑褂肧pring框架的時(shí)候,常常需要注入相關(guān)的Bean,如果需要注入有相同類型的Bean的時(shí)候,會(huì)比較麻煩,需要一個(gè)一個(gè)注入,并且相對(duì)來(lái)說(shuō)擴(kuò)展性不是很好。
因此提供一種策略模式下獲取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]);}}} }使用場(chǎng)景
public interface IProcessor<F> extends MatchingBean<F> {public boolean go();public InterfaceEnum getFunction(); } public abstract class AbstractProcessor implements IProcessor<InterfaceEnum> {@Overridepublic boolean matching(InterfaceEnum func) {return this.getFunction() == func;} } @Service public class ChildProcessor extends AbstractProcessor {@Overridepublic boolean go() {XX}@Overridepublic InterfaceEnum getFunction() {return InterfaceEnum.XXX;} }最終使用
@Resourceprivate FactoryList<IProcessor<InterfaceEnum>, InterfaceEnum> processors; private IProcessor getProcessor(InterfaceEnum enum) {IProcessor p = processors.getBean(enum); //沒(méi)有則返回nullreturn p;}此處可用作適配器,用來(lái)串聯(lián)起整個(gè)標(biāo)準(zhǔn)化的接口業(yè)務(wù)
也可用Map<String,Interface> beanMap 來(lái)自動(dòng)加載interface的Bean,不過(guò)要注意的是beanMap中的key是BeanName
轉(zhuǎn)載于:https://my.oschina.net/guanhe/blog/1821060
總結(jié)
以上是生活随笔為你收集整理的Spring动态注入泛型集合Bean的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: matlab-----均值滤波函数的实现
- 下一篇: SpringCloud学习成长之 十一