Skip to content

Commit a2b7af7

Browse files
committed
fix getOptionalBean error when beanName is null
(cherry picked from commit fb7e293)
1 parent 16971da commit a2b7af7

File tree

1 file changed

+17
-0
lines changed
  • dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util

1 file changed

+17
-0
lines changed

dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@
2626
import org.apache.dubbo.config.spring.context.DubboBootstrapApplicationListener;
2727
import org.apache.dubbo.config.spring.context.DubboLifecycleComponentApplicationListener;
2828
import org.springframework.beans.BeansException;
29+
import org.springframework.beans.factory.BeanFactoryUtils;
2930
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
3031
import org.springframework.beans.factory.ListableBeanFactory;
3132
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
33+
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
3234
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
3335

3436
import 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

Comments
 (0)