2626import org .apache .dubbo .config .spring .context .DubboBootstrapApplicationListener ;
2727import org .apache .dubbo .config .spring .context .DubboLifecycleComponentApplicationListener ;
2828import org .springframework .beans .BeansException ;
29+ import org .springframework .beans .factory .BeanFactoryUtils ;
2930import org .springframework .beans .factory .BeanNotOfRequiredTypeException ;
3031import org .springframework .beans .factory .ListableBeanFactory ;
3132import org .springframework .beans .factory .NoSuchBeanDefinitionException ;
33+ import org .springframework .beans .factory .NoUniqueBeanDefinitionException ;
3234import org .springframework .beans .factory .support .BeanDefinitionRegistry ;
3335
3436import java .util .ArrayList ;
@@ -102,6 +104,10 @@ public static void registerCommonBeans(BeanDefinitionRegistry registry) {
102104 * @return
103105 */
104106 public static <T > T getOptionalBean (ListableBeanFactory beanFactory , String beanName , Class <T > beanType ) throws BeansException {
107+ if (beanName == null ) {
108+ return getOptionalBeanByType (beanFactory , beanType );
109+ }
110+
105111 T bean = null ;
106112 try {
107113 bean = beanFactory .getBean (beanName , beanType );
@@ -115,6 +121,17 @@ public static <T> T getOptionalBean(ListableBeanFactory beanFactory, String bean
115121 return bean ;
116122 }
117123
124+ private static <T > T getOptionalBeanByType (ListableBeanFactory beanFactory , Class <T > beanType ) {
125+ // Issue : https://github.com/alibaba/spring-context-support/issues/20
126+ String [] beanNames = BeanFactoryUtils .beanNamesForTypeIncludingAncestors (beanFactory , beanType , true , false );
127+ if (beanNames == null || beanNames .length == 0 ) {
128+ return null ;
129+ } else if (beanNames .length > 1 ){
130+ throw new NoUniqueBeanDefinitionException (beanType , Arrays .asList (beanNames ));
131+ }
132+ return (T ) beanFactory .getBean (beanNames [0 ]);
133+ }
134+
118135 public static <T > T getBean (ListableBeanFactory beanFactory , String beanName , Class <T > beanType ) throws BeansException {
119136 return beanFactory .getBean (beanName , beanType );
120137 }
0 commit comments