From 4f3454002414f19ee07664c731a02aa30c4d8b27 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Tue, 20 Mar 2018 11:08:56 +0800 Subject: [PATCH 01/18] Manually merge pull request #1486, to make travis ci and codecov work after apache incubator transition. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f818df97a18..6a631991374 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Dubbo Project -[![Build Status](https://travis-ci.org/alibaba/dubbo.svg?branch=master)](https://travis-ci.org/alibaba/dubbo) -[![codecov](https://codecov.io/gh/alibaba/dubbo/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/dubbo) +[![Build Status](https://travis-ci.org/apache/incubator-dubbo.svg?branch=master)](https://travis-ci.org/apache/incubator-dubbo) +[![codecov](https://codecov.io/gh/apache/incubator-dubbo/branch/master/graph/badge.svg)](https://codecov.io/gh/apache/incubator-dubbo) [![Gitter](https://badges.gitter.im/alibaba/dubbo.svg)](https://gitter.im/alibaba/dubbo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) ![license](https://img.shields.io/github/license/alibaba/dubbo.svg) ![maven](https://img.shields.io/maven-central/v/com.alibaba/dubbo.svg) From 1e5b28f458ee5bb9ea3cb656fc5932e1296b3ee4 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 30 Mar 2018 23:33:37 +0800 Subject: [PATCH 02/18] Polish alibaba/dubbo#1306 --- .../AnnotationPropertyValuesAdapter.java | 92 ++++++++++ .../DubboConfigBindingBeanPostProcessor.java | 115 +++++++++++-- .../ReferenceAnnotationBeanPostProcessor.java | 161 +++++++++++++++--- .../annotation/ReferenceBeanBuilder.java | 26 ++- .../ServiceAnnotationBeanPostProcessor.java | 49 +++--- .../DubboConfigBindingRegistrar.java | 64 ++----- .../properties/AbstractDubboConfigBinder.java | 69 ++++++++ .../properties/DefaultDubboConfigBinder.java | 46 +++++ .../context/properties/DubboConfigBinder.java | 58 +++++++ .../converter/StringArrayToMapConverter.java | 38 +++++ .../StringArrayToStringConverter.java | 37 ++++ .../config/spring/util/AnnotationUtils.java | 89 ++++++++++ .../dubbo/config/spring/util/ObjectUtils.java | 37 ++++ .../spring/util/PropertySourcesUtils.java | 18 +- .../provider/AnnotationServiceImpl.java | 2 +- .../AnnotationPropertyValuesAdapterTest.java | 158 +++++++++++++++++ ...bboConfigBindingBeanPostProcessorTest.java | 66 +++++++ ...erenceAnnotationBeanPostProcessorTest.java | 95 +++++++++-- ...erviceAnnotationBeanPostProcessorTest.java | 3 +- .../DefaultDubboConfigBinderTest.java | 56 ++++++ .../StringArrayToMapConverterTest.java | 52 ++++++ .../StringArrayToStringConverterTest.java | 46 +++++ 22 files changed, 1241 insertions(+), 136 deletions(-) create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/ObjectUtils.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessorTest.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java new file mode 100644 index 00000000000..751399f8499 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.PropertyValue; +import org.springframework.beans.PropertyValues; +import org.springframework.core.env.PropertyResolver; + +import java.lang.annotation.Annotation; + +import static com.alibaba.dubbo.config.spring.util.AnnotationUtils.getAttributes; + +/** + * {@link Annotation} {@link PropertyValues} Adapter + * + * @see Annotation + * @see PropertyValues + * @since 2.5.11 + */ +class AnnotationPropertyValuesAdapter implements PropertyValues { + + private final Annotation annotation; + + private final PropertyResolver propertyResolver; + + private final boolean ignoreDefaultValue; + + private final PropertyValues delegate; + + public AnnotationPropertyValuesAdapter(Annotation annotation, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { + this.annotation = annotation; + this.propertyResolver = propertyResolver; + this.ignoreDefaultValue = ignoreDefaultValue; + this.delegate = adapt(annotation, ignoreDefaultValue, ignoreAttributeNames); + } + + public AnnotationPropertyValuesAdapter(Annotation annotation, PropertyResolver propertyResolver, String... ignoreAttributeNames) { + this(annotation, propertyResolver, true, ignoreAttributeNames); + } + + private PropertyValues adapt(Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) { + return new MutablePropertyValues(getAttributes(annotation, propertyResolver, ignoreDefaultValue, ignoreAttributeNames)); + } + + public Annotation getAnnotation() { + return annotation; + } + + public boolean isIgnoreDefaultValue() { + return ignoreDefaultValue; + } + + @Override + public PropertyValue[] getPropertyValues() { + return delegate.getPropertyValues(); + } + + @Override + public PropertyValue getPropertyValue(String propertyName) { + return delegate.getPropertyValue(propertyName); + } + + @Override + public PropertyValues changesSince(PropertyValues old) { + return delegate.changesSince(old); + } + + @Override + public boolean contains(String propertyName) { + return delegate.contains(propertyName); + } + + @Override + public boolean isEmpty() { + return delegate.isEmpty(); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java index 6899ad42fc1..6248ed32ffd 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java @@ -17,13 +17,25 @@ package com.alibaba.dubbo.config.spring.beans.factory.annotation; import com.alibaba.dubbo.common.utils.Assert; +import com.alibaba.dubbo.config.AbstractConfig; import com.alibaba.dubbo.config.spring.context.annotation.DubboConfigBindingRegistrar; import com.alibaba.dubbo.config.spring.context.annotation.EnableDubboConfigBinding; +import com.alibaba.dubbo.config.spring.context.properties.DefaultDubboConfigBinder; +import com.alibaba.dubbo.config.spring.context.properties.DubboConfigBinder; +import com.alibaba.dubbo.config.spring.util.BeanFactoryUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.Environment; import org.springframework.validation.DataBinder; import java.util.Arrays; @@ -35,43 +47,52 @@ * @see DubboConfigBindingRegistrar * @since 2.5.8 */ -public class DubboConfigBindingBeanPostProcessor implements BeanPostProcessor { + +public class DubboConfigBindingBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware, InitializingBean { private final Log log = LogFactory.getLog(getClass()); /** - * Binding Bean Name + * The prefix of Configuration Properties */ - private final String beanName; + private final String prefix; /** - * Binding {@link PropertyValues} + * Binding Bean Name */ - private final PropertyValues propertyValues; + private final String beanName; + private DubboConfigBinder dubboConfigBinder; + + private ApplicationContext applicationContext; + + private boolean ignoreUnknownFields = true; + + private boolean ignoreInvalidFields = true; /** - * @param beanName Binding Bean Name - * @param propertyValues {@link PropertyValues} + * @param prefix the prefix of Configuration Properties + * @param beanName the binding Bean Name */ - public DubboConfigBindingBeanPostProcessor(String beanName, PropertyValues propertyValues) { + public DubboConfigBindingBeanPostProcessor(String prefix, String beanName) { + Assert.notNull(prefix, "The prefix of Configuration Properties must not be null"); Assert.notNull(beanName, "The name of bean must not be null"); - Assert.notNull(propertyValues, "The PropertyValues of bean must not be null"); + this.prefix = prefix; this.beanName = beanName; - this.propertyValues = propertyValues; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (beanName.equals(this.beanName)) { - DataBinder dataBinder = new DataBinder(bean); - // TODO ignore invalid fields by annotation attribute - dataBinder.setIgnoreInvalidFields(true); - dataBinder.bind(propertyValues); + if (beanName.equals(this.beanName) && bean instanceof AbstractConfig) { + + AbstractConfig dubboConfig = (AbstractConfig) bean; + + dubboConfigBinder.bind(prefix, dubboConfig); + if (log.isInfoEnabled()) { - log.info("The properties of bean [name : " + beanName + "] have been binding by values : " - + Arrays.asList(propertyValues.getPropertyValues())); + log.info("The properties of bean [name : " + beanName + "] have been binding by prefix of " + + "configuration properties : " + prefix); } } @@ -79,10 +100,70 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) thro } + public boolean isIgnoreUnknownFields() { + return ignoreUnknownFields; + } + + public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { + this.ignoreUnknownFields = ignoreUnknownFields; + } + + public boolean isIgnoreInvalidFields() { + return ignoreInvalidFields; + } + + public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { + this.ignoreInvalidFields = ignoreInvalidFields; + } + + public DubboConfigBinder getDubboConfigBinder() { + return dubboConfigBinder; + } + + public void setDubboConfigBinder(DubboConfigBinder dubboConfigBinder) { + this.dubboConfigBinder = dubboConfigBinder; + } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + @Override + public void afterPropertiesSet() throws Exception { + + if (dubboConfigBinder == null) { + try { + dubboConfigBinder = applicationContext.getBean(DubboConfigBinder.class); + } catch (BeansException ignored) { + if (log.isDebugEnabled()) { + log.debug("DubboConfigBinder Bean can't be found in ApplicationContext."); + } + // Use Default implementation + dubboConfigBinder = createDubboConfigBinder(applicationContext.getEnvironment()); + } + } + + dubboConfigBinder.setIgnoreUnknownFields(ignoreUnknownFields); + dubboConfigBinder.setIgnoreInvalidFields(ignoreInvalidFields); + + } + + /** + * Create {@link DubboConfigBinder} instance. + * + * @param environment + * @return {@link DefaultDubboConfigBinder} + */ + protected DubboConfigBinder createDubboConfigBinder(Environment environment) { + DefaultDubboConfigBinder defaultDubboConfigBinder = new DefaultDubboConfigBinder(); + defaultDubboConfigBinder.setEnvironment(environment); + return defaultDubboConfigBinder; + } + } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index d8411de3640..31478f6cff7 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -33,6 +33,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.PriorityOrdered; +import org.springframework.core.env.Environment; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; @@ -41,9 +42,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -73,8 +72,8 @@ public class ReferenceAnnotationBeanPostProcessor extends InstantiationAwareBean private ClassLoader classLoader; - private final ConcurrentMap injectionMetadataCache = - new ConcurrentHashMap(256); + private final ConcurrentMap injectionMetadataCache = + new ConcurrentHashMap(256); private final ConcurrentMap> referenceBeansCache = new ConcurrentHashMap>(); @@ -101,9 +100,9 @@ public PropertyValues postProcessPropertyValues( * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ - private List findFieldReferenceMetadata(final Class beanClass) { + private List findFieldReferenceMetadata(final Class beanClass) { - final List elements = new LinkedList(); + final List elements = new LinkedList(); ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { @Override @@ -136,9 +135,9 @@ public void doWith(Field field) throws IllegalArgumentException, IllegalAccessEx * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ - private List findMethodReferenceMetadata(final Class beanClass) { + private List findMethodReferenceMetadata(final Class beanClass) { - final List elements = new LinkedList(); + final List elements = new LinkedList(); ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { @Override @@ -180,15 +179,10 @@ public void doWith(Method method) throws IllegalArgumentException, IllegalAccess * @param beanClass * @return */ - private InjectionMetadata buildReferenceMetadata(final Class beanClass) { - - final List elements = new LinkedList(); - - elements.addAll(findFieldReferenceMetadata(beanClass)); - - elements.addAll(findMethodReferenceMetadata(beanClass)); - - return new InjectionMetadata(beanClass, elements); + private ReferenceInjectionMetadata buildReferenceMetadata(final Class beanClass) { + Collection fieldElements = findFieldReferenceMetadata(beanClass); + Collection methodElements = findMethodReferenceMetadata(beanClass); + return new ReferenceInjectionMetadata(beanClass, fieldElements, methodElements); } @@ -196,7 +190,7 @@ private InjectionMetadata findReferenceMetadata(String beanName, Class clazz, // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. - InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); + ReferenceInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); @@ -270,6 +264,43 @@ public Collection> getReferenceBeans() { return this.referenceBeansCache.values(); } + + /** + * {@link Reference} {@link InjectionMetadata} implementation + * + * @since 2.5.11 + */ + private static class ReferenceInjectionMetadata extends InjectionMetadata { + + private final Collection fieldElements; + + private final Collection methodElements; + + + public ReferenceInjectionMetadata(Class targetClass, Collection fieldElements, + Collection methodElements) { + super(targetClass, combine(fieldElements, methodElements)); + this.fieldElements = fieldElements; + this.methodElements = methodElements; + } + + private static Collection combine(Collection... elements) { + List allElements = new ArrayList(); + for (Collection e : elements) { + allElements.addAll(e); + } + return allElements; + } + + public Collection getFieldElements() { + return fieldElements; + } + + public Collection getMethodElements() { + return methodElements; + } + } + /** * {@link Reference} {@link Method} {@link InjectionMetadata.InjectedElement} */ @@ -279,6 +310,8 @@ private class ReferenceMethodElement extends InjectionMetadata.InjectedElement { private final Reference reference; + private volatile ReferenceBean referenceBean; + protected ReferenceMethodElement(Method method, PropertyDescriptor pd, Reference reference) { super(method, pd); this.method = method; @@ -290,11 +323,11 @@ protected void inject(Object bean, String beanName, PropertyValues pvs) throws T Class referenceClass = pd.getPropertyType(); - Object referenceBean = buildReferenceBean(reference, referenceClass); + referenceBean = buildReferenceBean(reference, referenceClass); ReflectionUtils.makeAccessible(method); - method.invoke(bean, referenceBean); + method.invoke(bean, referenceBean.getObject()); } @@ -309,6 +342,8 @@ private class ReferenceFieldElement extends InjectionMetadata.InjectedElement { private final Reference reference; + private volatile ReferenceBean referenceBean; + protected ReferenceFieldElement(Field field, Reference reference) { super(field, null); this.field = field; @@ -320,17 +355,17 @@ protected void inject(Object bean, String beanName, PropertyValues pvs) throws T Class referenceClass = field.getType(); - Object referenceBean = buildReferenceBean(reference, referenceClass); + referenceBean = buildReferenceBean(reference, referenceClass); ReflectionUtils.makeAccessible(field); - field.set(bean, referenceBean); + field.set(bean, referenceBean.getObject()); } } - private Object buildReferenceBean(Reference reference, Class referenceClass) throws Exception { + private ReferenceBean buildReferenceBean(Reference reference, Class referenceClass) throws Exception { String referenceBeanCacheKey = generateReferenceBeanCacheKey(reference, referenceClass); @@ -348,8 +383,8 @@ private Object buildReferenceBean(Reference reference, Class referenceClass) } + return referenceBean; - return referenceBean.get(); } @@ -360,11 +395,17 @@ private Object buildReferenceBean(Reference reference, Class referenceClass) * @param beanClass {@link Class} * @return */ - private static String generateReferenceBeanCacheKey(Reference reference, Class beanClass) { + private String generateReferenceBeanCacheKey(Reference reference, Class beanClass) { String interfaceName = resolveInterfaceName(reference, beanClass); - String key = reference.group() + "/" + interfaceName + ":" + reference.version(); + String key = reference.url() + "/" + interfaceName + + "/" + reference.version() + + "/" + reference.group(); + + Environment environment = applicationContext.getEnvironment(); + + key = environment.resolvePlaceholders(key); return key; @@ -390,4 +431,70 @@ private static String resolveInterfaceName(Reference reference, Class beanCla } + + /** + * Get {@link ReferenceBean} {@link Map} in injected field. + * + * @return non-null {@link Map} + * @since 2.5.11 + */ + public Map> getInjectedFieldReferenceBeanMap() { + + Map> injectedElementReferenceBeanMap = + new LinkedHashMap>(); + + for (ReferenceInjectionMetadata metadata : injectionMetadataCache.values()) { + + Collection fieldElements = metadata.getFieldElements(); + + for (ReferenceFieldElement fieldElement : fieldElements) { + + injectedElementReferenceBeanMap.put(fieldElement, fieldElement.referenceBean); + + } + + } + + return injectedElementReferenceBeanMap; + + } + + /** + * Get {@link ReferenceBean} {@link Map} in injected method. + * + * @return non-null {@link Map} + * @since 2.5.11 + */ + public Map> getInjectedMethodReferenceBeanMap() { + + Map> injectedElementReferenceBeanMap = + new LinkedHashMap>(); + + for (ReferenceInjectionMetadata metadata : injectionMetadataCache.values()) { + + Collection methodElements = metadata.getMethodElements(); + + for (ReferenceMethodElement methodElement : methodElements) { + + injectedElementReferenceBeanMap.put(methodElement, methodElement.referenceBean); + + } + + } + + return injectedElementReferenceBeanMap; + + } + + private T getFieldValue(Object object, String fieldName, Class fieldType) { + + Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType); + + ReflectionUtils.makeAccessible(field); + + return (T) ReflectionUtils.getField(field, object); + + } + + } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java index d2cc56d2bf0..5d9418fbc8a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java @@ -19,12 +19,18 @@ import com.alibaba.dubbo.config.ConsumerConfig; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; +import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToMapConverter; +import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToStringConverter; import org.springframework.context.ApplicationContext; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; +import org.springframework.validation.DataBinder; import static com.alibaba.dubbo.config.spring.util.BeanFactoryUtils.getOptionalBean; +import static com.alibaba.dubbo.config.spring.util.ObjectUtils.of; /** * {@link ReferenceBean} Builder @@ -80,14 +86,30 @@ private void configureConsumerConfig(Reference reference, ReferenceBean refer @Override protected ReferenceBean doBuild() { - return new ReferenceBean(annotation); + return new ReferenceBean(); } @Override - protected void preConfigureBean(Reference annotation, ReferenceBean bean) { + protected void preConfigureBean(Reference reference, ReferenceBean referenceBean) { Assert.notNull(interfaceClass, "The interface class must set first!"); + DataBinder dataBinder = new DataBinder(referenceBean); + // Set ConversionService + dataBinder.setConversionService(getConversionService()); + // Ignore those fields + String[] ignoreAttributeNames = of("application", "module", "consumer", "monitor", "registry"); +// dataBinder.setDisallowedFields(ignoreAttributeNames); + // Bind annotation attributes + dataBinder.bind(new AnnotationPropertyValuesAdapter(reference, applicationContext.getEnvironment(), ignoreAttributeNames)); } + private ConversionService getConversionService() { + DefaultConversionService conversionService = new DefaultConversionService(); + conversionService.addConverter(new StringArrayToStringConverter()); + conversionService.addConverter(new StringArrayToMapConverter()); + return conversionService; + } + + @Override protected String resolveModuleConfigBeanName(Reference annotation) { return annotation.module(); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 1d273451bfc..207b3f7d03d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -21,20 +21,11 @@ import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.dubbo.config.spring.ServiceBean; import com.alibaba.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; - import org.springframework.beans.BeansException; +import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.config.SingletonBeanRegistry; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.config.*; +import org.springframework.beans.factory.support.*; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.AnnotationBeanNameGenerator; @@ -44,18 +35,11 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import org.springframework.util.*; + +import java.util.*; +import static com.alibaba.dubbo.config.spring.util.ObjectUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; @@ -356,11 +340,20 @@ private Set resolvePackagesToScan(Set packagesToScan) { private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class interfaceClass, String annotatedServiceBeanName) { - BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class) - .addConstructorArgValue(service) - // References "ref" property to annotated-@Service Bean - .addPropertyReference("ref", annotatedServiceBeanName) - .addPropertyValue("interface", interfaceClass.getName()); + BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class); + + AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); + + MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); + + String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", "interface"); + + propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames)); + + // References "ref" property to annotated-@Service Bean + addPropertyReference(builder, "ref", annotatedServiceBeanName); + // Set interface + builder.addPropertyValue("interface", interfaceClass.getName()); /** * Add {@link com.alibaba.dubbo.config.ProviderConfig} Bean reference diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java index cd9cadd3e7b..452d9d3a236 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java @@ -20,8 +20,6 @@ import com.alibaba.dubbo.config.spring.beans.factory.annotation.DubboConfigBindingBeanPostProcessor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; @@ -30,15 +28,21 @@ import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.env.*; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; +import org.springframework.core.env.PropertySources; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import java.util.*; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; +import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.normalizePrefix; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName; @@ -82,9 +86,7 @@ private void registerDubboConfigBeans(String prefix, boolean multiple, BeanDefinitionRegistry registry) { - PropertySources propertySources = environment.getPropertySources(); - - Map properties = getSubProperties(propertySources, prefix); + Map properties = getSubProperties(environment.getPropertySources(), prefix); if (CollectionUtils.isEmpty(properties)) { if (log.isDebugEnabled()) { @@ -94,16 +96,14 @@ private void registerDubboConfigBeans(String prefix, return; } - Set beanNames = multiple ? resolveMultipleBeanNames(prefix, properties) : - Collections.singleton(resolveSingleBeanName(configClass, properties, registry)); + Set beanNames = multiple ? resolveMultipleBeanNames(properties) : + Collections.singleton(resolveSingleBeanName(properties, configClass, registry)); for (String beanName : beanNames) { registerDubboConfigBean(beanName, configClass, registry); - MutablePropertyValues propertyValues = resolveBeanPropertyValues(beanName, multiple, properties); - - registerDubboConfigBindingBeanPostProcessor(beanName, propertyValues, registry); + registerDubboConfigBindingBeanPostProcessor(prefix, beanName, multiple, registry); } @@ -125,14 +125,16 @@ private void registerDubboConfigBean(String beanName, Class processorClass = DubboConfigBindingBeanPostProcessor.class; BeanDefinitionBuilder builder = rootBeanDefinition(processorClass); - builder.addConstructorArgValue(beanName).addConstructorArgValue(propertyValues); + String actualPrefix = multiple ? normalizePrefix(prefix) + beanName : prefix; + + builder.addConstructorArgValue(actualPrefix).addConstructorArgValue(beanName); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); @@ -147,36 +149,6 @@ private void registerDubboConfigBindingBeanPostProcessor(String beanName, Proper } - private MutablePropertyValues resolveBeanPropertyValues(String beanName, boolean multiple, - Map properties) { - - MutablePropertyValues propertyValues = new MutablePropertyValues(); - - if (multiple) { // For Multiple Beans - - MutablePropertySources propertySources = new MutablePropertySources(); - propertySources.addFirst(new MapPropertySource(beanName, new TreeMap(properties))); - - Map subProperties = getSubProperties(propertySources, beanName); - - propertyValues.addPropertyValues(subProperties); - - - } else { // For Single Bean - - for (Map.Entry entry : properties.entrySet()) { - String propertyName = entry.getKey(); - if (!propertyName.contains(".")) { // ignore property name with "." - propertyValues.addPropertyValue(propertyName, entry.getValue()); - } - } - - } - - return propertyValues; - - } - @Override public void setEnvironment(Environment environment) { @@ -186,7 +158,7 @@ public void setEnvironment(Environment environment) { } - private Set resolveMultipleBeanNames(String prefix, Map properties) { + private Set resolveMultipleBeanNames(Map properties) { Set beanNames = new LinkedHashSet(); @@ -207,7 +179,7 @@ private Set resolveMultipleBeanNames(String prefix, Map } - private String resolveSingleBeanName(Class configClass, Map properties, + private String resolveSingleBeanName(Map properties, Class configClass, BeanDefinitionRegistry registry) { String beanName = properties.get("id"); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java new file mode 100644 index 00000000000..b10336797f8 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.context.properties; + +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; +import org.springframework.core.env.PropertySource; + +/** + * Abstract {@link DubboConfigBinder} implementation + */ +public abstract class AbstractDubboConfigBinder implements DubboConfigBinder { + + private Iterable> propertySources; + + private boolean ignoreUnknownFields = true; + + private boolean ignoreInvalidFields = false; + + /** + * Get multiple {@link PropertySource propertySources} + * + * @return multiple {@link PropertySource propertySources} + */ + protected Iterable> getPropertySources() { + return propertySources; + } + + public boolean isIgnoreUnknownFields() { + return ignoreUnknownFields; + } + + @Override + public void setIgnoreUnknownFields(boolean ignoreUnknownFields) { + this.ignoreUnknownFields = ignoreUnknownFields; + } + + public boolean isIgnoreInvalidFields() { + return ignoreInvalidFields; + } + + @Override + public void setIgnoreInvalidFields(boolean ignoreInvalidFields) { + this.ignoreInvalidFields = ignoreInvalidFields; + } + + @Override + public final void setEnvironment(Environment environment) { + + if (environment instanceof ConfigurableEnvironment) { + this.propertySources = ((ConfigurableEnvironment) environment).getPropertySources(); + } + + } +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java new file mode 100644 index 00000000000..52cc87ca4f5 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.context.properties; + +import com.alibaba.dubbo.config.AbstractConfig; +import org.springframework.beans.MutablePropertyValues; +import org.springframework.validation.DataBinder; + +import java.util.Map; + +import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; + +/** + * Default {@link DubboConfigBinder} implementation based on Spring {@link DataBinder} + */ +public class DefaultDubboConfigBinder extends AbstractDubboConfigBinder { + + @Override + public void bind(String prefix, C dubboConfig) { + DataBinder dataBinder = new DataBinder(dubboConfig); + // Set ignored* + dataBinder.setIgnoreInvalidFields(isIgnoreInvalidFields()); + dataBinder.setIgnoreUnknownFields(isIgnoreUnknownFields()); + // Get properties under specified prefix from PropertySources + Map properties = getSubProperties(getPropertySources(), prefix); + // Convert Map to MutablePropertyValues + MutablePropertyValues propertyValues = new MutablePropertyValues(properties); + // Bind + dataBinder.bind(propertyValues); + } + +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java new file mode 100644 index 00000000000..c19fadce278 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.context.properties; + +import com.alibaba.dubbo.config.AbstractConfig; +import org.springframework.context.EnvironmentAware; + +/** + * {@link AbstractConfig DubboConfig} Binder + * + * @see AbstractConfig + * @see EnvironmentAware + * @since 2.5.11 + */ +public interface DubboConfigBinder extends EnvironmentAware { + + /** + * Set whether to ignore unknown fields, that is, whether to ignore bind + * parameters that do not have corresponding fields in the target object. + *

Default is "true". Turn this off to enforce that all bind parameters + * must have a matching field in the target object. + * + * @see #bind + */ + void setIgnoreUnknownFields(boolean ignoreUnknownFields); + + /** + * Set whether to ignore invalid fields, that is, whether to ignore bind + * parameters that have corresponding fields in the target object which are + * not accessible (for example because of null values in the nested path). + *

Default is "false". + * + * @see #bind + */ + void setIgnoreInvalidFields(boolean ignoreInvalidFields); + + /** + * Bind the properties to {@link C Dubbo Config} Object under specified prefix. + * + * @param prefix + * @param dubboConfig + */ + void bind(String prefix, C dubboConfig); +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java new file mode 100644 index 00000000000..56c6d4c4ccd --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.convert.converter; + +import com.alibaba.dubbo.common.utils.CollectionUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.ObjectUtils; + +import java.util.Map; + +/** + * {@link String}[] to {@link Map} {@link Converter} + * + * @see CollectionUtils#toStringMap(String[]) + * @since 2.5.11 + */ +public class StringArrayToMapConverter implements Converter> { + + @Override + public Map convert(String[] source) { + return ObjectUtils.isEmpty(source) ? null : CollectionUtils.toStringMap(source); + } + +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java new file mode 100644 index 00000000000..23e948b0644 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.convert.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + + +/** + * String[] to String {@ConditionalGenericConverter} + * + * @see StringUtils#arrayToCommaDelimitedString(Object[]) + * @since 2.5.11 + */ +public class StringArrayToStringConverter implements Converter { + + @Override + public String convert(String[] source) { + return ObjectUtils.isEmpty(source) ? null : StringUtils.arrayToCommaDelimitedString(source); + } + +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java new file mode 100644 index 00000000000..aa15e567eb0 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.util; + +import org.springframework.core.env.PropertyResolver; + +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import static java.lang.String.valueOf; +import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; +import static org.springframework.core.annotation.AnnotationUtils.getDefaultValue; +import static org.springframework.util.CollectionUtils.arrayToList; +import static org.springframework.util.ObjectUtils.nullSafeEquals; +import static org.springframework.util.StringUtils.trimAllWhitespace; + +/** + * Annotation Utilities Class + * + * @see org.springframework.core.annotation.AnnotationUtils + * @since 2.5.11 + */ +public class AnnotationUtils { + + /** + * Get {@link Annotation} attributes + * + * @param annotation + * @param propertyResolver + * @param ignoreDefaultValue + * @return non-null + */ + public static Map getAttributes(Annotation annotation, PropertyResolver propertyResolver, + boolean ignoreDefaultValue, String... ignoreAttributeNames) { + + Set ignoreAttributeNamesSet = new HashSet(arrayToList(ignoreAttributeNames)); + + Map attributes = getAnnotationAttributes(annotation); + + Map actualAttributes = new LinkedHashMap(); + + boolean requiredResolve = propertyResolver != null; + + for (Map.Entry entry : attributes.entrySet()) { + + String attributeName = entry.getKey(); + Object attributeValue = entry.getValue(); + + // ignore default attribute value + if (ignoreDefaultValue && nullSafeEquals(attributeValue, getDefaultValue(annotation, attributeName))) { + continue; + } + + // ignore attribute name + if (ignoreAttributeNamesSet.contains(attributeName)) { + continue; + } + + if (requiredResolve && attributeValue instanceof String) { // Resolve Placeholder + String resolvedValue = propertyResolver.resolvePlaceholders(valueOf(attributeValue)); + attributeValue = trimAllWhitespace(resolvedValue); + } + + actualAttributes.put(attributeName, attributeValue); + + } + + return actualAttributes; + + } + +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/ObjectUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/ObjectUtils.java new file mode 100644 index 00000000000..00db1e770f5 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/ObjectUtils.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.util; + +/** + * Object Utilities Class + * + * @since 2.5.11 + */ +public class ObjectUtils { + + /** + * of factory method + * + * @param values + * @param + * @return + */ + public static T[] of(T... values) { + return values; + } + +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java index fe1c61bbbde..5b183e1f2f7 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java @@ -35,16 +35,16 @@ public abstract class PropertySourcesUtils { /** * Get Sub {@link Properties} * - * @param propertySources {@link PropertySources} + * @param propertySources {@link PropertySource} Iterable * @param prefix the prefix of property name - * @return Map + * @return Map * @see Properties */ - public static Map getSubProperties(PropertySources propertySources, String prefix) { + public static Map getSubProperties(Iterable> propertySources, String prefix) { Map subProperties = new LinkedHashMap(); - String normalizedPrefix = prefix.endsWith(".") ? prefix : prefix + "."; + String normalizedPrefix = normalizePrefix(prefix); for (PropertySource source : propertySources) { if (source instanceof EnumerablePropertySource) { @@ -62,4 +62,14 @@ public static Map getSubProperties(PropertySources propertySourc } + /** + * Normalize the prefix + * + * @param prefix the prefix + * @return the prefix + */ + public static String normalizePrefix(String prefix) { + return prefix.endsWith(".") ? prefix : prefix + "."; + } + } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java index 7766a1a6025..327f4d91bac 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java @@ -23,7 +23,7 @@ /** * DemoServiceImpl */ -@Service(version = "1.2") +@Service(version = "${provider.version}") public class AnnotationServiceImpl implements DemoService { public String sayName(String name) { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java new file mode 100644 index 00000000000..36def719d36 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapterTest.java @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + + +import com.alibaba.dubbo.common.utils.CollectionUtils; +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.spring.ReferenceBean; +import com.alibaba.dubbo.config.spring.api.DemoService; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.support.DefaultConversionService; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.util.ReflectionUtils; +import org.springframework.validation.DataBinder; + +import java.lang.reflect.Field; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; + +/** + * {@link AnnotationPropertyValuesAdapter} Test + * + * @since 2.5.11 + */ +public class AnnotationPropertyValuesAdapterTest { + + @Test + public void test() { + + MockEnvironment mockEnvironment = new MockEnvironment(); + + mockEnvironment.setProperty("version", "1.0.0"); + + mockEnvironment.setProperty("url", " dubbo://localhost:12345"); + + Field field = ReflectionUtils.findField(TestBean.class, "demoService"); + + Reference reference = AnnotationUtils.getAnnotation(field, Reference.class); + + AnnotationPropertyValuesAdapter propertyValues = new AnnotationPropertyValuesAdapter(reference, mockEnvironment); + + ReferenceBean referenceBean = new ReferenceBean(); + + DataBinder dataBinder = new DataBinder(referenceBean); + + dataBinder.setDisallowedFields("application", "module", "consumer", "monitor", "registry"); + + DefaultConversionService conversionService = new DefaultConversionService(); + + conversionService.addConverter(new Converter() { + @Override + public String convert(String[] source) { + return arrayToCommaDelimitedString(source); + } + }); + + conversionService.addConverter(new Converter>() { + @Override + public Map convert(String[] source) { + return CollectionUtils.toStringMap(source); + } + }); + + + dataBinder.setConversionService(conversionService); + + + dataBinder.bind(propertyValues); + +// System.out.println(referenceBean); + + Assert.assertEquals(DemoService.class, referenceBean.getInterfaceClass()); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService", referenceBean.getInterface()); + Assert.assertEquals("1.0.0", referenceBean.getVersion()); + Assert.assertEquals("group", referenceBean.getGroup()); + Assert.assertEquals("dubbo://localhost:12345", referenceBean.getUrl()); + Assert.assertEquals("client", referenceBean.getClient()); + Assert.assertEquals(true, referenceBean.isGeneric()); + Assert.assertEquals(true, referenceBean.isInjvm()); + Assert.assertEquals(false, referenceBean.isCheck()); + Assert.assertEquals(true, referenceBean.isInit()); + Assert.assertEquals(true, referenceBean.getLazy()); + Assert.assertEquals(true, referenceBean.getStubevent()); + Assert.assertEquals("reconnect", referenceBean.getReconnect()); + Assert.assertEquals(true, referenceBean.getSticky()); + + Assert.assertEquals("javassist", referenceBean.getProxy()); + + Assert.assertEquals("stub", referenceBean.getStub()); + Assert.assertEquals("failover", referenceBean.getCluster()); + Assert.assertEquals(Integer.valueOf(1), referenceBean.getConnections()); + Assert.assertEquals(Integer.valueOf(1), referenceBean.getCallbacks()); + Assert.assertEquals("onconnect", referenceBean.getOnconnect()); + Assert.assertEquals("ondisconnect", referenceBean.getOndisconnect()); + Assert.assertEquals("owner", referenceBean.getOwner()); + Assert.assertEquals("layer", referenceBean.getLayer()); + Assert.assertEquals(Integer.valueOf(2), referenceBean.getRetries()); + Assert.assertEquals("random", referenceBean.getLoadbalance()); + Assert.assertEquals(true, referenceBean.isAsync()); + Assert.assertEquals(Integer.valueOf(1), referenceBean.getActives()); + Assert.assertEquals(true, referenceBean.getSent()); + Assert.assertEquals("mock", referenceBean.getMock()); + Assert.assertEquals("validation", referenceBean.getValidation()); + Assert.assertEquals(Integer.valueOf(2), referenceBean.getTimeout()); + Assert.assertEquals("cache", referenceBean.getCache()); + Assert.assertEquals("default,default", referenceBean.getFilter()); + Assert.assertEquals("default,default", referenceBean.getListener()); + + Map data = new LinkedHashMap(); + data.put("key1", "value1"); + + Assert.assertEquals(data, referenceBean.getParameters()); + // Bean compare + Assert.assertEquals(null, referenceBean.getApplication()); + Assert.assertEquals(null, referenceBean.getModule()); + Assert.assertEquals(null, referenceBean.getConsumer()); + Assert.assertEquals(null, referenceBean.getMonitor()); + Assert.assertEquals(null, referenceBean.getRegistry()); + + } + + private static class TestBean { + + @Reference( + interfaceClass = DemoService.class, interfaceName = "com.alibaba.dubbo.config.spring.api.DemoService", version = "${version}", group = "group", + url = "${url} ", client = "client", generic = true, injvm = true, + check = false, init = true, lazy = true, stubevent = true, + reconnect = "reconnect", sticky = true, proxy = "javassist", stub = "stub", + cluster = "failover", connections = 1, callbacks = 1, onconnect = "onconnect", + ondisconnect = "ondisconnect", owner = "owner", layer = "layer", retries = 2, + loadbalance = "random", async = true, actives = 1, sent = true, + mock = "mock", validation = "validation", timeout = 2, cache = "cache", + filter = {"default", "default"}, listener = {"default", "default"}, parameters = {"key1", "value1"}, application = "application", + module = "module", consumer = "consumer", monitor = "monitor", registry = {"registry1", "registry2"} + ) + private DemoService demoService; + + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessorTest.java new file mode 100644 index 00000000000..05a49807d4e --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessorTest.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.spring.context.properties.DefaultDubboConfigBinder; +import com.alibaba.dubbo.config.spring.context.properties.DubboConfigBinder; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; + +/** + * {@link DubboConfigBindingBeanPostProcessor} + */ +@PropertySource({"classpath:/META-INF/config.properties"}) +@Configuration +public class DubboConfigBindingBeanPostProcessorTest { + + @Bean("applicationBean") + public ApplicationConfig applicationConfig() { + return new ApplicationConfig(); + } + + @Bean + public DubboConfigBinder dubboConfigBinder() { + return new DefaultDubboConfigBinder(); + } + + @Test + public void test() { + + final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); + + applicationContext.register(getClass()); + + Class processorClass = DubboConfigBindingBeanPostProcessor.class; + + applicationContext.registerBeanDefinition("DubboConfigBindingBeanPostProcessor", rootBeanDefinition(processorClass).addConstructorArgValue("dubbo.application").addConstructorArgValue("applicationBean").getBeanDefinition()); + + applicationContext.refresh(); + + ApplicationConfig applicationConfig = applicationContext.getBean(ApplicationConfig.class); + + Assert.assertEquals("dubbo-demo-application", applicationConfig.getName()); + + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index 3f9a50e1af2..5f334914d3e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -20,16 +20,16 @@ import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.api.DemoService; import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ImportResource; -import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Collection; +import java.util.Map; import static com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor.BEAN_NAME; @@ -40,12 +40,27 @@ */ public class ReferenceAnnotationBeanPostProcessorTest { - private static final String PROVIDER_LOCATION = "META-INF/spring/dubbo-provider.xml"; + private ConfigurableApplicationContext providerApplicationContext; + + @BeforeClass + public static void prepare() { + System.setProperty("provider.version", "1.2"); + System.setProperty("package1", "com.alibaba.dubbo.config.spring.annotation.provider"); + System.setProperty("packagesToScan", "${package1}"); + System.setProperty("consumer.version", "1.2"); + System.setProperty("consumer.url", "dubbo://127.0.0.1:12345"); + } @Before - public void before() { + public void init() { // Starts Provider - new ClassPathXmlApplicationContext(PROVIDER_LOCATION); + providerApplicationContext = new AnnotationConfigApplicationContext(ServiceAnnotationBeanPostProcessorTest.TestConfiguration.class); + } + + @After + public void destroy() { + // Shutdowns Provider + providerApplicationContext.close(); } @Test @@ -95,6 +110,66 @@ public void testGetReferenceBeans() { } + @Test + public void testGetInjectedFieldReferenceBeanMap() { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); + + ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, + ReferenceAnnotationBeanPostProcessor.class); + + + Map> referenceBeanMap = + beanPostProcessor.getInjectedFieldReferenceBeanMap(); + + Assert.assertEquals(1, referenceBeanMap.size()); + + for (Map.Entry> entry : referenceBeanMap.entrySet()) { + + InjectionMetadata.InjectedElement injectedElement = entry.getKey(); + + Assert.assertEquals("com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor$ReferenceFieldElement", + injectedElement.getClass().getName()); + + ReferenceBean referenceBean = entry.getValue(); + + Assert.assertEquals("1.2", referenceBean.getVersion()); + Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); + + } + + } + + @Test + public void testGetInjectedMethodReferenceBeanMap() { + + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); + + ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, + ReferenceAnnotationBeanPostProcessor.class); + + + Map> referenceBeanMap = + beanPostProcessor.getInjectedMethodReferenceBeanMap(); + + Assert.assertEquals(2, referenceBeanMap.size()); + + for (Map.Entry> entry : referenceBeanMap.entrySet()) { + + InjectionMetadata.InjectedElement injectedElement = entry.getKey(); + + Assert.assertEquals("com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor$ReferenceMethodElement", + injectedElement.getClass().getName()); + + ReferenceBean referenceBean = entry.getValue(); + + Assert.assertEquals("1.2", referenceBean.getVersion()); + Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); + + } + + } + private static class AncestorBean { @@ -121,7 +196,7 @@ public ApplicationContext getApplicationContext() { private static class ParentBean extends AncestorBean { - @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345") + @Reference(version = "${consumer.version}", url = "${consumer.url}") private DemoService demoServiceFromParent; public DemoService getDemoServiceFromParent() { @@ -133,7 +208,7 @@ public DemoService getDemoServiceFromParent() { @ImportResource("META-INF/spring/dubbo-annotation-consumer.xml") @DubboComponentScan(basePackageClasses = ReferenceAnnotationBeanPostProcessorTest.class) - private static class TestBean extends ParentBean { + static class TestBean extends ParentBean { private DemoService demoService; @@ -150,4 +225,4 @@ public void setDemoService(DemoService demoService) { } } -} +} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java index e5714c7f254..c0964418144 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java @@ -44,7 +44,8 @@ classes = {ServiceAnnotationBeanPostProcessorTest.TestConfiguration.class}) @TestPropertySource(properties = { "package1 = com.alibaba.dubbo.config.spring.context.annotation", - "packagesToScan = ${package1}" + "packagesToScan = ${package1}", + "provider.version = 1.2" }) public class ServiceAnnotationBeanPostProcessorTest { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java new file mode 100644 index 00000000000..f0ec69f505b --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.context.properties; + + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ProtocolConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@TestPropertySource(locations = "classpath:/dubbo.properties") +@ContextConfiguration(classes = DefaultDubboConfigBinder.class) +public class DefaultDubboConfigBinderTest { + + @Autowired + private DubboConfigBinder dubboConfigBinder; + + @Test + public void testBinder() { + + ApplicationConfig applicationConfig = new ApplicationConfig(); + dubboConfigBinder.bind("dubbo.application", applicationConfig); + Assert.assertEquals("hello", applicationConfig.getName()); + Assert.assertEquals("world", applicationConfig.getOwner()); + + RegistryConfig registryConfig = new RegistryConfig(); + dubboConfigBinder.bind("dubbo.registry", registryConfig); + Assert.assertEquals("10.20.153.17", registryConfig.getAddress()); + + ProtocolConfig protocolConfig = new ProtocolConfig(); + dubboConfigBinder.bind("dubbo.protocol", protocolConfig); + Assert.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); + + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java new file mode 100644 index 00000000000..51be7c3f2f2 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.convert.converter; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * {@link StringArrayToMapConverter} Test + */ +public class StringArrayToMapConverterTest { + + @Test + public void testConvert() { + + StringArrayToMapConverter converter = new StringArrayToMapConverter(); + + Map value = converter.convert(new String[]{"Hello", "World"}); + + Map expected = new LinkedHashMap(); + + expected.put("Hello", "World"); + + Assert.assertEquals(expected, value); + + value = converter.convert(new String[]{}); + + Assert.assertNull(value); + + value = converter.convert(null); + + Assert.assertNull(value); + + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java new file mode 100644 index 00000000000..67e82479235 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.convert.converter; + +import org.junit.Assert; +import org.junit.Test; + +/** + * {@link StringArrayToStringConverter} Test + */ +public class StringArrayToStringConverterTest { + + @Test + public void testConvert() { + + StringArrayToStringConverter converter = new StringArrayToStringConverter(); + + String value = converter.convert(new String[]{"Hello", "World"}); + + Assert.assertEquals("Hello,World", value); + + value = converter.convert(new String[]{}); + + Assert.assertNull(value); + + value = converter.convert(null); + + Assert.assertNull(value); + + } + +} From 93591f056dafca5f910f8ae679820793561a5fd1 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 15 Apr 2018 14:32:46 +0800 Subject: [PATCH 03/18] Optimize imports --- .../context/annotation/DubboConfigBindingRegistrar.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java index 1fcaf38db69..6936787cc67 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java @@ -30,9 +30,6 @@ import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySources; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -43,8 +40,6 @@ import java.util.Map; import java.util.Set; -import java.util.TreeMap; - import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.normalizePrefix; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; From d57343e4a4f228cf02bbf0a3b8c33883082e1d98 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Sun, 15 Apr 2018 15:44:59 +0800 Subject: [PATCH 04/18] Optimize imports --- .../dubbo/config/spring/ReferenceBean.java | 1 - .../dubbo/config/spring/ServiceBean.java | 1 - .../DubboConfigBindingBeanPostProcessor.java | 9 ------- .../ReferenceAnnotationBeanPostProcessor.java | 7 ++++- .../ServiceAnnotationBeanPostProcessor.java | 27 +++++++++++++++---- .../dubbo/config/spring/ConfigTest.java | 15 +++++++++-- ...erenceAnnotationBeanPostProcessorTest.java | 6 ++++- .../annotation/EnableDubboConfigTest.java | 8 +++++- .../context/annotation/EnableDubboTest.java | 6 ++++- .../config/spring/filter/MockFilter.java | 7 ++++- 10 files changed, 64 insertions(+), 23 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java index f3aa9b02493..a9d5b3f58cb 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ReferenceBean.java @@ -25,7 +25,6 @@ import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; import com.alibaba.dubbo.config.support.Parameter; - import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index 2e614efdb69..c4eb0c28213 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -25,7 +25,6 @@ import com.alibaba.dubbo.config.ServiceConfig; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; - import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNameAware; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java index 6248ed32ffd..cbb5435d33f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/DubboConfigBindingBeanPostProcessor.java @@ -22,23 +22,14 @@ import com.alibaba.dubbo.config.spring.context.annotation.EnableDubboConfigBinding; import com.alibaba.dubbo.config.spring.context.properties.DefaultDubboConfigBinder; import com.alibaba.dubbo.config.spring.context.properties.DubboConfigBinder; -import com.alibaba.dubbo.config.spring.util.BeanFactoryUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; -import org.springframework.validation.DataBinder; - -import java.util.Arrays; /** * Dubbo Config Binding {@link BeanPostProcessor} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 31478f6cff7..cfd719668ae 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -42,7 +42,12 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 207b3f7d03d..af05aac1383 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -24,8 +24,17 @@ import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.config.*; -import org.springframework.beans.factory.support.*; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.config.SingletonBeanRegistry; +import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import org.springframework.beans.factory.support.BeanNameGenerator; +import org.springframework.beans.factory.support.ManagedList; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.AnnotationBeanNameGenerator; @@ -35,9 +44,17 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.*; - -import java.util.*; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.CollectionUtils; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; import static com.alibaba.dubbo.config.spring.util.ObjectUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index 3b54e9d8a5a..80de429007e 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -21,7 +21,13 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.config.*; +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ConsumerConfig; +import com.alibaba.dubbo.config.ProtocolConfig; +import com.alibaba.dubbo.config.ProviderConfig; +import com.alibaba.dubbo.config.ReferenceConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.ServiceConfig; import com.alibaba.dubbo.config.spring.action.DemoActionByAnnotation; import com.alibaba.dubbo.config.spring.action.DemoActionBySetter; import com.alibaba.dubbo.config.spring.annotation.consumer.AnnotationAction; @@ -49,7 +55,12 @@ import java.util.Collection; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.containsString; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index 5f334914d3e..01dbc5317d0 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -20,7 +20,11 @@ import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.api.DemoService; import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan; -import org.junit.*; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.context.ApplicationContext; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java index 13f733da9b8..1673be10ce7 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java @@ -16,7 +16,13 @@ */ package com.alibaba.dubbo.config.spring.context.annotation; -import com.alibaba.dubbo.config.*; +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ConsumerConfig; +import com.alibaba.dubbo.config.ModuleConfig; +import com.alibaba.dubbo.config.MonitorConfig; +import com.alibaba.dubbo.config.ProtocolConfig; +import com.alibaba.dubbo.config.ProviderConfig; +import com.alibaba.dubbo.config.RegistryConfig; import org.junit.Assert; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java index 2020bed667e..c5018da2522 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -24,7 +24,11 @@ import org.junit.Assert; import org.junit.Test; import org.springframework.aop.support.AopUtils; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/filter/MockFilter.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/filter/MockFilter.java index de192b92e1f..e4fc142a7c9 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/filter/MockFilter.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/filter/MockFilter.java @@ -16,7 +16,12 @@ */ package com.alibaba.dubbo.config.spring.filter; -import com.alibaba.dubbo.rpc.*; +import com.alibaba.dubbo.rpc.Filter; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Protocol; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.cluster.LoadBalance; /** From d428f5fba767fbe6b7e62278eb27ae01407db9b6 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 23 Apr 2018 10:14:13 +0800 Subject: [PATCH 05/18] Remove invalid JavaDoc --- .../config/spring/context/properties/DubboConfigBinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java index c19fadce278..6ebb86296d5 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java @@ -49,7 +49,7 @@ public interface DubboConfigBinder extends EnvironmentAware { void setIgnoreInvalidFields(boolean ignoreInvalidFields); /** - * Bind the properties to {@link C Dubbo Config} Object under specified prefix. + * Bind the properties to Dubbo Config Object under specified prefix. * * @param prefix * @param dubboConfig From 5d72ddf8eccf48b35cdd9956811a8aeb2986c7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=A9=AC=E5=93=A5?= Date: Mon, 23 Apr 2018 10:16:47 +0800 Subject: [PATCH 06/18] Update DubboConfigBinder.java Remove invalid JavaDoc --- .../config/spring/context/properties/DubboConfigBinder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java index c19fadce278..6ebb86296d5 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DubboConfigBinder.java @@ -49,7 +49,7 @@ public interface DubboConfigBinder extends EnvironmentAware { void setIgnoreInvalidFields(boolean ignoreInvalidFields); /** - * Bind the properties to {@link C Dubbo Config} Object under specified prefix. + * Bind the properties to Dubbo Config Object under specified prefix. * * @param prefix * @param dubboConfig From 5bab1417d85ae63485ee6656baa3fef3a52e1f33 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 23 Apr 2018 21:44:01 +0800 Subject: [PATCH 07/18] Fix apache/incubator-dubbo#1653 --- .../ServiceAnnotationBeanPostProcessor.java | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 6e7fe03b1a4..35604650906 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -71,6 +71,8 @@ public class ServiceAnnotationBeanPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, ResourceLoaderAware, BeanClassLoaderAware { + private static final String SEPARATOR = ":"; + private final Logger logger = LoggerFactory.getLogger(getClass()); private final Set packagesToScan; @@ -254,7 +256,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean buildServiceBeanDefinition(service, interfaceClass, annotatedServiceBeanName); // ServiceBean Bean name - String beanName = generateServiceBeanName(interfaceClass, annotatedServiceBeanName); + String beanName = generateServiceBeanName(service, interfaceClass, annotatedServiceBeanName); if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean registry.registerBeanDefinition(beanName, serviceBeanDefinition); @@ -279,14 +281,35 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean /** * Generates the bean name of {@link ServiceBean} * + * @param service * @param interfaceClass the class of interface annotated {@link Service} * @param annotatedServiceBeanName the bean name of annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.5.9 */ - private String generateServiceBeanName(Class interfaceClass, String annotatedServiceBeanName) { + private String generateServiceBeanName(Service service, Class interfaceClass, String annotatedServiceBeanName) { + + StringBuilder beanNameBuilder = new StringBuilder(ServiceBean.class.getSimpleName()); + + beanNameBuilder.append(SEPARATOR).append(annotatedServiceBeanName); + + String interfaceClassName = interfaceClass.getName(); + + beanNameBuilder.append(SEPARATOR).append(interfaceClassName); + + String version = service.version(); + + if (StringUtils.hasText(version)) { + beanNameBuilder.append(SEPARATOR).append(version); + } + + String group = service.group(); + + if (StringUtils.hasText(group)) { + beanNameBuilder.append(SEPARATOR).append(group); + } - return "ServiceBean@" + interfaceClass.getName() + "#" + annotatedServiceBeanName; + return beanNameBuilder.toString(); } @@ -477,4 +500,4 @@ public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } -} +} \ No newline at end of file From 31acca8845dce62ba611afde15fc20b75a41a0a3 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Thu, 10 May 2018 17:32:50 +0800 Subject: [PATCH 08/18] Fixed apache/incubator-dubbo#1772 --- .../config/spring/util/PropertySourcesUtils.java | 6 ++++-- .../config/spring/util/PropertySourcesUtilsTest.java | 12 +++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java index 5b183e1f2f7..a84e18ac819 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java @@ -51,8 +51,10 @@ public static Map getSubProperties(Iterable> p for (String name : ((EnumerablePropertySource) source).getPropertyNames()) { if (name.startsWith(normalizedPrefix)) { String subName = name.substring(normalizedPrefix.length()); - Object value = source.getProperty(name); - subProperties.put(subName, String.valueOf(value)); + if (!subProperties.containsKey(subName)) { + Object value = source.getProperty(name); + subProperties.put(subName, String.valueOf(value)); + } } } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java index 5dd526f7bcf..dddb6583a0b 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java @@ -55,9 +55,19 @@ public void testGetSubProperties() { source.put(KEY_PREFIX + "." + KEY_AGE, 31); Map expected = new HashMap(); - expected.put(KEY_NAME, "Mercy"); + expected.put(KEY_NAME, "mercyblitz"); expected.put(KEY_AGE, "31"); + + Map source2 = new HashMap(); + + source2.put("user.name", "mercyblitz"); + + MapPropertySource propertySource2 = new MapPropertySource("test2", source2); + + propertySources.addFirst(propertySource2); + + result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX); Assert.assertEquals(expected, result); From 185545efe506542124cdf0144b160bdd8b1407bd Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 13 Aug 2018 10:08:04 +0800 Subject: [PATCH 09/18] Reactor ReferenceAnnotationBeanPostProcessor --- dependencies-bom/pom.xml | 18 +- dubbo-config/dubbo-config-spring/pom.xml | 4 + .../AbstractAnnotationConfigBeanBuilder.java | 3 +- .../ReferenceAnnotationBeanPostProcessor.java | 466 +++--------------- ...erenceAnnotationBeanPostProcessorTest.java | 11 +- 5 files changed, 108 insertions(+), 394 deletions(-) diff --git a/dependencies-bom/pom.xml b/dependencies-bom/pom.xml index e9a3f80b2c5..a6742b71d27 100644 --- a/dependencies-bom/pom.xml +++ b/dependencies-bom/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 @@ -29,8 +30,8 @@ https://github.com/apache/incubator-dubbo scm:git:https://github.com/apache/incubator-dubbo.git scm:git:https://github.com/apache/incubator-dubbo.git - HEAD - + HEAD + Development List @@ -101,6 +102,9 @@ 2.0 3.0.19.Final 8.5.31 + + + 1.0.1-SNAPSHOT 1.7.25 1.2 @@ -300,6 +304,14 @@ tomcat-embed-logging-juli ${tomcat_embed_version} + + + + com.alibaba.spring + spring-context-support + ${alibaba_spring_context_support_version} + + org.slf4j diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index a186182c49a..ff528b05195 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -56,6 +56,10 @@ javax.servlet-api provided + + com.alibaba.spring + spring-context-support + com.alibaba dubbo-registry-default diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java index fc8d3f46105..2f58a6ec3b7 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationConfigBeanBuilder.java @@ -34,6 +34,7 @@ /** * Abstract Configurable {@link Annotation} Bean Builder + * * @since 2.5.7 */ abstract class AbstractAnnotationConfigBeanBuilder { @@ -76,7 +77,7 @@ public final B build() throws Exception { configureBean(bean); if (logger.isInfoEnabled()) { - logger.info(bean + " has been built."); + logger.info("The bean[type:" + bean.getClass().getSimpleName() + "] has been built."); } return bean; diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index cfd719668ae..8c8824f13f3 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -18,247 +18,55 @@ import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeanUtils; +import com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor; import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyValues; -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.InjectionMetadata; -import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; -import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; -import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.core.PriorityOrdered; -import org.springframework.core.env.Environment; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; -import java.beans.PropertyDescriptor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.lang.reflect.Proxy; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import static org.springframework.core.BridgeMethodResolver.findBridgedMethod; -import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair; -import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; -import static org.springframework.core.annotation.AnnotationUtils.getAnnotation; - /** * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation * that Consumer service {@link Reference} annotated fields * * @since 2.5.7 */ -public class ReferenceAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter - implements MergedBeanDefinitionPostProcessor, PriorityOrdered, ApplicationContextAware, BeanClassLoaderAware, - DisposableBean { +public class ReferenceAnnotationBeanPostProcessor extends CustomizedAnnotationBeanPostProcessor + implements ApplicationContextAware, ApplicationListener { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} */ public static final String BEAN_NAME = "referenceAnnotationBeanPostProcessor"; - private final Log logger = LogFactory.getLog(getClass()); - private ApplicationContext applicationContext; - private ClassLoader classLoader; - - private final ConcurrentMap injectionMetadataCache = - new ConcurrentHashMap(256); - - private final ConcurrentMap> referenceBeansCache = - new ConcurrentHashMap>(); - - @Override - public PropertyValues postProcessPropertyValues( - PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { - - InjectionMetadata metadata = findReferenceMetadata(beanName, bean.getClass(), pvs); - try { - metadata.inject(bean, beanName, pvs); - } catch (BeanCreationException ex) { - throw ex; - } catch (Throwable ex) { - throw new BeanCreationException(beanName, "Injection of @Reference dependencies failed", ex); - } - return pvs; - } - - - /** - * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link Reference @Reference} fields - * - * @param beanClass The {@link Class} of Bean - * @return non-null {@link List} - */ - private List findFieldReferenceMetadata(final Class beanClass) { - - final List elements = new LinkedList(); - - ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - - Reference reference = getAnnotation(field, Reference.class); - - if (reference != null) { - - if (Modifier.isStatic(field.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@Reference annotation is not supported on static fields: " + field); - } - return; - } - - elements.add(new ReferenceFieldElement(field, reference)); - } - - } - }); - - return elements; - - } + private final List> referenceBeans = new LinkedList>(); - /** - * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link Reference @Reference} methods - * - * @param beanClass The {@link Class} of Bean - * @return non-null {@link List} - */ - private List findMethodReferenceMetadata(final Class beanClass) { - - final List elements = new LinkedList(); - - ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - - Method bridgedMethod = findBridgedMethod(method); - - if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { - return; - } - - Reference reference = findAnnotation(bridgedMethod, Reference.class); - - if (reference != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) { - if (Modifier.isStatic(method.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@Reference annotation is not supported on static methods: " + method); - } - return; - } - if (method.getParameterTypes().length == 0) { - if (logger.isWarnEnabled()) { - logger.warn("@Reference annotation should only be used on methods with parameters: " + - method); - } - } - PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); - elements.add(new ReferenceMethodElement(method, pd, reference)); - } - } - }); - - return elements; + private final List referenceBeanInvocationHandlers = + new LinkedList(); - } + private final ConcurrentMap> injectedFieldReferenceBeanMap = + new ConcurrentHashMap>(); + private final ConcurrentMap> injectedMethodReferenceBeanMap = + new ConcurrentHashMap>(); - /** - * @param beanClass - * @return - */ - private ReferenceInjectionMetadata buildReferenceMetadata(final Class beanClass) { - Collection fieldElements = findFieldReferenceMetadata(beanClass); - Collection methodElements = findMethodReferenceMetadata(beanClass); - return new ReferenceInjectionMetadata(beanClass, fieldElements, methodElements); - - } - - private InjectionMetadata findReferenceMetadata(String beanName, Class clazz, PropertyValues pvs) { - // Fall back to class name as cache key, for backwards compatibility with custom callers. - String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); - // Quick check on the concurrent map first, with minimal locking. - ReferenceInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); - if (InjectionMetadata.needsRefresh(metadata, clazz)) { - synchronized (this.injectionMetadataCache) { - metadata = this.injectionMetadataCache.get(cacheKey); - if (InjectionMetadata.needsRefresh(metadata, clazz)) { - if (metadata != null) { - metadata.clear(pvs); - } - try { - metadata = buildReferenceMetadata(clazz); - this.injectionMetadataCache.put(cacheKey, metadata); - } catch (NoClassDefFoundError err) { - throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() + - "] for reference metadata: could not find class that it depends on", err); - } - } - } - } - return metadata; - } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - @Override - public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { - if (beanType != null) { - InjectionMetadata metadata = findReferenceMetadata(beanName, beanType, null); - metadata.checkConfigMembers(beanDefinition); - } - } - - @Override - public int getOrder() { - return LOWEST_PRECEDENCE; - } - - @Override - public void destroy() throws Exception { - - for (ReferenceBean referenceBean : referenceBeansCache.values()) { - if (logger.isInfoEnabled()) { - logger.info(referenceBean + " was destroying!"); - } - referenceBean.destroy(); - } - - injectionMetadataCache.clear(); - referenceBeansCache.clear(); - - if (logger.isInfoEnabled()) { - logger.info(getClass() + " was destroying!"); - } - - } - - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; - } - - /** * Gets all beans of {@link ReferenceBean} * @@ -266,154 +74,7 @@ public void setBeanClassLoader(ClassLoader classLoader) { * @since 2.5.9 */ public Collection> getReferenceBeans() { - return this.referenceBeansCache.values(); - } - - - /** - * {@link Reference} {@link InjectionMetadata} implementation - * - * @since 2.5.11 - */ - private static class ReferenceInjectionMetadata extends InjectionMetadata { - - private final Collection fieldElements; - - private final Collection methodElements; - - - public ReferenceInjectionMetadata(Class targetClass, Collection fieldElements, - Collection methodElements) { - super(targetClass, combine(fieldElements, methodElements)); - this.fieldElements = fieldElements; - this.methodElements = methodElements; - } - - private static Collection combine(Collection... elements) { - List allElements = new ArrayList(); - for (Collection e : elements) { - allElements.addAll(e); - } - return allElements; - } - - public Collection getFieldElements() { - return fieldElements; - } - - public Collection getMethodElements() { - return methodElements; - } - } - - /** - * {@link Reference} {@link Method} {@link InjectionMetadata.InjectedElement} - */ - private class ReferenceMethodElement extends InjectionMetadata.InjectedElement { - - private final Method method; - - private final Reference reference; - - private volatile ReferenceBean referenceBean; - - protected ReferenceMethodElement(Method method, PropertyDescriptor pd, Reference reference) { - super(method, pd); - this.method = method; - this.reference = reference; - } - - @Override - protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { - - Class referenceClass = pd.getPropertyType(); - - referenceBean = buildReferenceBean(reference, referenceClass); - - ReflectionUtils.makeAccessible(method); - - method.invoke(bean, referenceBean.getObject()); - - } - - } - - /** - * {@link Reference} {@link Field} {@link InjectionMetadata.InjectedElement} - */ - private class ReferenceFieldElement extends InjectionMetadata.InjectedElement { - - private final Field field; - - private final Reference reference; - - private volatile ReferenceBean referenceBean; - - protected ReferenceFieldElement(Field field, Reference reference) { - super(field, null); - this.field = field; - this.reference = reference; - } - - @Override - protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { - - Class referenceClass = field.getType(); - - referenceBean = buildReferenceBean(reference, referenceClass); - - ReflectionUtils.makeAccessible(field); - - field.set(bean, referenceBean.getObject()); - - } - - } - - private ReferenceBean buildReferenceBean(Reference reference, Class referenceClass) throws Exception { - - String referenceBeanCacheKey = generateReferenceBeanCacheKey(reference, referenceClass); - - ReferenceBean referenceBean = referenceBeansCache.get(referenceBeanCacheKey); - - if (referenceBean == null) { - - ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder - .create(reference, classLoader, applicationContext) - .interfaceClass(referenceClass); - - referenceBean = beanBuilder.build(); - - referenceBeansCache.putIfAbsent(referenceBeanCacheKey, referenceBean); - - } - - return referenceBean; - - } - - - /** - * Generate a cache key of {@link ReferenceBean} - * - * @param reference {@link Reference} - * @param beanClass {@link Class} - * @return - */ - private String generateReferenceBeanCacheKey(Reference reference, Class beanClass) { - - String interfaceName = resolveInterfaceName(reference, beanClass); - - String key = reference.url() + "/" + interfaceName + - "/" + reference.version() + - "/" + reference.group(); - - Environment environment = applicationContext.getEnvironment(); - - key = environment.resolvePlaceholders(key); - - return key; - + return Collections.unmodifiableCollection(referenceBeans); } private static String resolveInterfaceName(Reference reference, Class beanClass) @@ -444,24 +105,7 @@ private static String resolveInterfaceName(Reference reference, Class beanCla * @since 2.5.11 */ public Map> getInjectedFieldReferenceBeanMap() { - - Map> injectedElementReferenceBeanMap = - new LinkedHashMap>(); - - for (ReferenceInjectionMetadata metadata : injectionMetadataCache.values()) { - - Collection fieldElements = metadata.getFieldElements(); - - for (ReferenceFieldElement fieldElement : fieldElements) { - - injectedElementReferenceBeanMap.put(fieldElement, fieldElement.referenceBean); - - } - - } - - return injectedElementReferenceBeanMap; - + return Collections.unmodifiableMap(injectedFieldReferenceBeanMap); } /** @@ -471,35 +115,87 @@ public Map> getInjectedField * @since 2.5.11 */ public Map> getInjectedMethodReferenceBeanMap() { + return Collections.unmodifiableMap(injectedMethodReferenceBeanMap); + } - Map> injectedElementReferenceBeanMap = - new LinkedHashMap>(); + @Override + protected Object doGetInjectedBean(Reference reference, Object bean, String beanName, Class injectedType, + InjectionMetadata.InjectedElement injectedElement) throws Exception { + + ReferenceBean referenceBean = buildReferenceBean(reference, injectedType, getClassLoader(), injectedElement); - for (ReferenceInjectionMetadata metadata : injectionMetadataCache.values()) { + InvocationHandler handler = buildReferenceBeanInvocationHandler(referenceBean); - Collection methodElements = metadata.getMethodElements(); + Object proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler); - for (ReferenceMethodElement methodElement : methodElements) { + return proxy; + } + + private InvocationHandler buildReferenceBeanInvocationHandler(ReferenceBean referenceBean) { + ReferenceBeanInvocationHandler handler = new ReferenceBeanInvocationHandler(referenceBean); + referenceBeanInvocationHandlers.add(handler); + return handler; + } - injectedElementReferenceBeanMap.put(methodElement, methodElement.referenceBean); + private static class ReferenceBeanInvocationHandler implements InvocationHandler { - } + private final ReferenceBean referenceBean; + private ReferenceBeanInvocationHandler(ReferenceBean referenceBean) { + this.referenceBean = referenceBean; } - return injectedElementReferenceBeanMap; + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Object bean = referenceBean.get(); + return method.invoke(bean, args); + } + } + + @Override + protected String buildInjectedObjectCacheKey(Reference reference, Object bean, String beanName, Class injectedType) { + + String interfaceName = resolveInterfaceName(reference, injectedType); + + String key = reference.url() + "/" + interfaceName + + "/" + reference.version() + + "/" + reference.group(); + + key = getEnvironment().resolvePlaceholders(key); + return key; } - private T getFieldValue(Object object, String fieldName, Class fieldType) { + private ReferenceBean buildReferenceBean(Reference reference, Class referencedType, + ClassLoader classLoader, InjectionMetadata.InjectedElement injectedElement) throws Exception { + + ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder + .create(reference, classLoader, applicationContext) + .interfaceClass(referencedType); - Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType); + ReferenceBean referenceBean = beanBuilder.build(); - ReflectionUtils.makeAccessible(field); + referenceBeans.add(referenceBean); - return (T) ReflectionUtils.getField(field, object); + if (injectedElement.getMember() instanceof Field) { + injectedFieldReferenceBeanMap.put(injectedElement, referenceBean); + } else if (injectedElement.getMember() instanceof Method) { + injectedMethodReferenceBeanMap.put(injectedElement, referenceBean); + } + + return referenceBean; } + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + + if (referenceBeanInvocationHandlers.isEmpty()) { + return; + } + + // clear all + referenceBeanInvocationHandlers.clear(); + } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index a1b5807cbf9..32adb9c8cdf 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -16,6 +16,7 @@ */ package com.alibaba.dubbo.config.spring.beans.factory.annotation; +import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.api.DemoService; @@ -56,7 +57,7 @@ public static void prepare() { System.setProperty("package1", "com.alibaba.dubbo.config.spring.annotation.provider"); System.setProperty("packagesToScan", "${package1}"); System.setProperty("consumer.version", "1.2"); - System.setProperty("consumer.url", "dubbo://127.0.0.1:12345"); + System.setProperty("consumer.url", "dubbo://" + NetUtils.getLocalHost() + ":12345"); } @Before @@ -136,13 +137,13 @@ public void testGetInjectedFieldReferenceBeanMap() { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); - Assert.assertEquals("com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor$ReferenceFieldElement", + Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedFieldElement", injectedElement.getClass().getName()); ReferenceBean referenceBean = entry.getValue(); Assert.assertEquals("1.2", referenceBean.getVersion()); - Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); + Assert.assertEquals("dubbo://" + NetUtils.getLocalHost() + ":12345", referenceBean.getUrl()); } @@ -166,7 +167,7 @@ public void testGetInjectedMethodReferenceBeanMap() { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); - Assert.assertEquals("com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor$ReferenceMethodElement", + Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedMethodlement", injectedElement.getClass().getName()); ReferenceBean referenceBean = entry.getValue(); @@ -192,7 +193,7 @@ public void testModuleInfo() { for (Map.Entry> entry : referenceBeanMap.entrySet()) { ReferenceBean referenceBean = entry.getValue(); - assertThat(referenceBean.getModule().getName(),is("defaultModule")); + assertThat(referenceBean.getModule().getName(), is("defaultModule")); assertThat(referenceBean.getMonitor(), not(nullValue())); } } From 3f99fe126211e17d95e2eeb82bed58d786332930 Mon Sep 17 00:00:00 2001 From: "taogu.mxx" Date: Mon, 13 Aug 2018 15:18:50 +0800 Subject: [PATCH 10/18] Fixed incubator-dubbo-spring-boot-project#243 --- .../ReferenceAnnotationBeanPostProcessor.java | 151 +++++++++++++----- ...erenceAnnotationBeanPostProcessorTest.java | 30 ++-- 2 files changed, 117 insertions(+), 64 deletions(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 8c8824f13f3..aa2c602f211 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -30,7 +30,9 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -48,33 +50,35 @@ public class ReferenceAnnotationBeanPostProcessor extends CustomizedAnnotationBe */ public static final String BEAN_NAME = "referenceAnnotationBeanPostProcessor"; - private ApplicationContext applicationContext; + /** + * Cache size + */ + private static final int CACHE_SIZE = Integer.getInteger(BEAN_NAME + ".cache.size", 32); - private final List> referenceBeans = new LinkedList>(); + private final ConcurrentMap> referenceBeanCache = + new ConcurrentHashMap>(CACHE_SIZE); - private final List referenceBeanInvocationHandlers = - new LinkedList(); + private final ConcurrentHashMap proxyCache = new ConcurrentHashMap(CACHE_SIZE); - private final ConcurrentMap> injectedFieldReferenceBeanMap = - new ConcurrentHashMap>(); + private final ConcurrentHashMap referenceBeanInvocationHandlerCache = + new ConcurrentHashMap(CACHE_SIZE); - private final ConcurrentMap> injectedMethodReferenceBeanMap = - new ConcurrentHashMap>(); + private final ConcurrentMap> injectedFieldReferenceBeanCache = + new ConcurrentHashMap>(CACHE_SIZE); + private final ConcurrentMap> injectedMethodReferenceBeanCache = + new ConcurrentHashMap>(CACHE_SIZE); - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } + private ApplicationContext applicationContext; /** * Gets all beans of {@link ReferenceBean} * - * @return non-null {@link Collection} + * @return non-null read-only {@link Collection} * @since 2.5.9 */ public Collection> getReferenceBeans() { - return Collections.unmodifiableCollection(referenceBeans); + return referenceBeanCache.values(); } private static String resolveInterfaceName(Reference reference, Class beanClass) @@ -105,7 +109,7 @@ private static String resolveInterfaceName(Reference reference, Class beanCla * @since 2.5.11 */ public Map> getInjectedFieldReferenceBeanMap() { - return Collections.unmodifiableMap(injectedFieldReferenceBeanMap); + return Collections.unmodifiableMap(injectedFieldReferenceBeanCache); } /** @@ -115,25 +119,46 @@ public Map> getInjectedField * @since 2.5.11 */ public Map> getInjectedMethodReferenceBeanMap() { - return Collections.unmodifiableMap(injectedMethodReferenceBeanMap); + return Collections.unmodifiableMap(injectedMethodReferenceBeanCache); } @Override protected Object doGetInjectedBean(Reference reference, Object bean, String beanName, Class injectedType, InjectionMetadata.InjectedElement injectedElement) throws Exception { - ReferenceBean referenceBean = buildReferenceBean(reference, injectedType, getClassLoader(), injectedElement); + String referenceBeanCacheKey = buildReferenceBeanCacheKey(reference, injectedType); + + ReferenceBean referenceBean = buildReferenceBeanIfAbsent(referenceBeanCacheKey, reference, injectedType, getClassLoader()); - InvocationHandler handler = buildReferenceBeanInvocationHandler(referenceBean); + cacheInjectedReferenceBean(referenceBean, injectedElement); - Object proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler); + Object proxy = buildProxyIfAbsent(referenceBeanCacheKey, referenceBean, injectedType); return proxy; } - private InvocationHandler buildReferenceBeanInvocationHandler(ReferenceBean referenceBean) { - ReferenceBeanInvocationHandler handler = new ReferenceBeanInvocationHandler(referenceBean); - referenceBeanInvocationHandlers.add(handler); + private Object buildProxyIfAbsent(String referenceBeanCacheKey, ReferenceBean referenceBean, Class injectedType) { + + Object proxy = proxyCache.get(referenceBeanCacheKey); + + if (proxy == null) { + InvocationHandler handler = buildInvocationHandlerIfAbsent(referenceBeanCacheKey, referenceBean); + proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler); + proxyCache.put(referenceBeanCacheKey, proxy); + } + + return proxy; + } + + private InvocationHandler buildInvocationHandlerIfAbsent(String referenceBeanCacheKey, ReferenceBean referenceBean) { + + ReferenceBeanInvocationHandler handler = referenceBeanInvocationHandlerCache.get(referenceBeanCacheKey); + + if (handler == null) { + handler = new ReferenceBeanInvocationHandler(referenceBean); + referenceBeanInvocationHandlerCache.put(referenceBeanCacheKey, handler); + } + return handler; } @@ -141,61 +166,99 @@ private static class ReferenceBeanInvocationHandler implements InvocationHandler private final ReferenceBean referenceBean; + private Object bean; + private ReferenceBeanInvocationHandler(ReferenceBean referenceBean) { this.referenceBean = referenceBean; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Object bean = referenceBean.get(); return method.invoke(bean, args); } + + private void init() { + this.bean = referenceBean.get(); + } } @Override - protected String buildInjectedObjectCacheKey(Reference reference, Object bean, String beanName, Class injectedType) { + protected String buildInjectedObjectCacheKey(Reference reference, Object bean, String beanName, + Class injectedType, InjectionMetadata.InjectedElement injectedElement) { + + String key = buildReferenceBeanCacheKey(reference, injectedType) + + "?source=" + (injectedElement.getMember()); + + return key; + } + + private String buildReferenceBeanCacheKey(Reference reference, Class injectedType) { String interfaceName = resolveInterfaceName(reference, injectedType); - String key = reference.url() + "/" + interfaceName + + String key = reference.url() + + "/" + interfaceName + "/" + reference.version() + "/" + reference.group(); - key = getEnvironment().resolvePlaceholders(key); - - return key; + return getEnvironment().resolvePlaceholders(key); } - private ReferenceBean buildReferenceBean(Reference reference, Class referencedType, - ClassLoader classLoader, InjectionMetadata.InjectedElement injectedElement) throws Exception { + private ReferenceBean buildReferenceBeanIfAbsent(String referenceBeanCacheKey, Reference reference, + Class referencedType, ClassLoader classLoader) + throws Exception { - ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder - .create(reference, classLoader, applicationContext) - .interfaceClass(referencedType); + ReferenceBean referenceBean = referenceBeanCache.get(referenceBeanCacheKey); - ReferenceBean referenceBean = beanBuilder.build(); + if (referenceBean == null) { + ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder + .create(reference, classLoader, applicationContext) + .interfaceClass(referencedType); + referenceBean = beanBuilder.build(); + referenceBeanCache.put(referenceBeanCacheKey, referenceBean); + } - referenceBeans.add(referenceBean); + return referenceBean; + } + private void cacheInjectedReferenceBean(ReferenceBean referenceBean, + InjectionMetadata.InjectedElement injectedElement) { if (injectedElement.getMember() instanceof Field) { - injectedFieldReferenceBeanMap.put(injectedElement, referenceBean); + injectedFieldReferenceBeanCache.put(injectedElement, referenceBean); } else if (injectedElement.getMember() instanceof Method) { - injectedMethodReferenceBeanMap.put(injectedElement, referenceBean); + injectedMethodReferenceBeanCache.put(injectedElement, referenceBean); } - - return referenceBean; - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } @Override public void onApplicationEvent(ContextRefreshedEvent event) { - if (referenceBeanInvocationHandlers.isEmpty()) { + if (proxyCache.isEmpty() || referenceBeanCache.isEmpty() || referenceBeanInvocationHandlerCache.isEmpty()) { return; } - // clear all - referenceBeanInvocationHandlers.clear(); + // initialize all + for (ReferenceBeanInvocationHandler handler : referenceBeanInvocationHandlerCache.values()) { + handler.init(); + } + + // clear Proxies and Handlers + this.proxyCache.clear(); + this.referenceBeanInvocationHandlerCache.clear(); + } + + @Override + public void destroy() throws Exception { + super.destroy(); + this.proxyCache.clear(); + this.referenceBeanCache.clear(); + this.referenceBeanInvocationHandlerCache.clear(); + this.injectedFieldReferenceBeanCache.clear(); + this.injectedMethodReferenceBeanCache.clear(); } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index 32adb9c8cdf..005f1e33981 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -16,16 +16,11 @@ */ package com.alibaba.dubbo.config.spring.beans.factory.annotation; -import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.api.DemoService; import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.context.ApplicationContext; @@ -37,9 +32,7 @@ import java.util.Map; import static com.alibaba.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor.BEAN_NAME; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; /** @@ -57,7 +50,7 @@ public static void prepare() { System.setProperty("package1", "com.alibaba.dubbo.config.spring.annotation.provider"); System.setProperty("packagesToScan", "${package1}"); System.setProperty("consumer.version", "1.2"); - System.setProperty("consumer.url", "dubbo://" + NetUtils.getLocalHost() + ":12345"); + System.setProperty("consumer.url", "dubbo://127.0.0.1:12345"); } @Before @@ -79,15 +72,14 @@ public void test() throws Exception { TestBean testBean = context.getBean(TestBean.class); + DemoService demoService = testBean.getDemoService(); + + Assert.assertEquals("annotation:Mercy", demoService.sayName("Mercy")); + Assert.assertNotNull(testBean.getDemoServiceFromAncestor()); Assert.assertNotNull(testBean.getDemoServiceFromParent()); Assert.assertNotNull(testBean.getDemoService()); - Assert.assertEquals(testBean.getDemoServiceFromAncestor(), testBean.getDemoServiceFromParent()); - Assert.assertEquals(testBean.getDemoService(), testBean.getDemoServiceFromParent()); - - DemoService demoService = testBean.getDemoService(); - Assert.assertEquals("annotation:Mercy", demoService.sayName("Mercy")); context.close(); @@ -113,9 +105,7 @@ public void testGetReferenceBeans() { TestBean testBean = context.getBean(TestBean.class); - Assert.assertEquals(referenceBean.get(), testBean.getDemoServiceFromAncestor()); - Assert.assertEquals(referenceBean.get(), testBean.getDemoServiceFromParent()); - Assert.assertEquals(referenceBean.get(), testBean.getDemoService()); + Assert.assertNotNull(referenceBean.get()); } @@ -143,7 +133,7 @@ public void testGetInjectedFieldReferenceBeanMap() { ReferenceBean referenceBean = entry.getValue(); Assert.assertEquals("1.2", referenceBean.getVersion()); - Assert.assertEquals("dubbo://" + NetUtils.getLocalHost() + ":12345", referenceBean.getUrl()); + Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); } @@ -167,7 +157,7 @@ public void testGetInjectedMethodReferenceBeanMap() { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); - Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedMethodlement", + Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedMethodElement", injectedElement.getClass().getName()); ReferenceBean referenceBean = entry.getValue(); From b066ccfe4ac5448cbe430b7992c354cfd13fc9fe Mon Sep 17 00:00:00 2001 From: "taogu.mxx" Date: Mon, 13 Aug 2018 17:17:37 +0800 Subject: [PATCH 11/18] Add ServiceBeanNameBuilder --- .../annotation/ServiceBeanNameBuilder.java | 139 ++++++++++++++++++ .../ServiceBeanNameBuilderTest.java | 92 ++++++++++++ 2 files changed, 231 insertions(+) create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java new file mode 100644 index 00000000000..0020a57794d --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ModuleConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.annotation.Service; +import com.alibaba.dubbo.config.spring.ReferenceBean; +import com.alibaba.dubbo.config.spring.ServiceBean; +import org.springframework.util.StringUtils; + +/** + * Dubbo {@link Service @Service} Bean Builder + * + * @author Mercy + * @see Service + * @see Reference + * @see ServiceBean + * @see ReferenceBean + * @since 2.6.4 + */ +class ServiceBeanNameBuilder { + + private static final String SEPARATOR = ":"; + + private final Class interfaceClass; + + private final String version; + + private final String group; + + private String application; + + private String module; + + + private String[] registry; + + private ServiceBeanNameBuilder(Class interfaceClass, String version, String group) { + this.interfaceClass = interfaceClass; + this.version = version; + this.group = group; + } + + private ServiceBeanNameBuilder(Service service, Class interfaceClass) { + this(service.interfaceClass() == null ? interfaceClass : service.interfaceClass(), service.version(), service.group()); + application(service.application()); + module(service.module()); + registry(service.registry()); + } + + private ServiceBeanNameBuilder(Reference reference, Class interfaceClass) { + this(reference.interfaceClass() == null ? interfaceClass : reference.interfaceClass(), reference.version(), reference.group()); + application(reference.application()); + module(reference.module()); + registry(reference.registry()); + } + + public static ServiceBeanNameBuilder create(Class interfaceClass, String version, String group) { + return new ServiceBeanNameBuilder(interfaceClass, version, group); + } + + public static ServiceBeanNameBuilder create(Service service, Class interfaceClass) { + return new ServiceBeanNameBuilder(service, interfaceClass); + } + + public static ServiceBeanNameBuilder create(Reference reference, Class interfaceClass) { + return new ServiceBeanNameBuilder(reference, interfaceClass); + } + + private static void append(StringBuilder builder, String value) { + if (StringUtils.hasText(value)) { + builder.append(value).append(SEPARATOR); + } + } + + /** + * Set {@link ApplicationConfig application} bean name + * + * @param application {@link ApplicationConfig application} bean name + * @return {@link ServiceBeanNameBuilder} + */ + public ServiceBeanNameBuilder application(String application) { + this.application = application; + return this; + } + + /** + * Set {@link ModuleConfig module} bean name + * + * @param module {@link ModuleConfig module} bean name + * @return {@link ServiceBeanNameBuilder} + */ + public ServiceBeanNameBuilder module(String module) { + this.module = module; + return this; + } + + /** + * Set {@link RegistryConfig monitor} bean names + * + * @param registry {@link RegistryConfig monitor} bean name + * @return {@link ServiceBeanNameBuilder} + */ + public ServiceBeanNameBuilder registry(String... registry) { + this.registry = registry; + return this; + } + + public String build() { + StringBuilder beanNameBuilder = new StringBuilder(); + // Required + append(beanNameBuilder, interfaceClass.getName()); + append(beanNameBuilder, version); + append(beanNameBuilder, group); + // Optional + append(beanNameBuilder, application); + append(beanNameBuilder, module); + append(beanNameBuilder, StringUtils.arrayToCommaDelimitedString(registry)); + // Build and remove last ":" + return beanNameBuilder.substring(0, beanNameBuilder.length() - 1); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java new file mode 100644 index 00000000000..dcf1348ed9f --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.annotation.Service; +import com.alibaba.dubbo.config.spring.api.DemoService; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.ReflectionUtils; + +import static com.alibaba.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.GROUP; +import static com.alibaba.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.VERSION; + +/** + * {@link ServiceBeanNameBuilder} Test + * + * @author Mercy + * @see ServiceBeanNameBuilder + * @since 2.6.4 + */ +@Service(interfaceClass = DemoService.class, group = GROUP, version = VERSION, + application = "application", module = "module", registry = {"1", "2", "3"}) +public class ServiceBeanNameBuilderTest { + + @Reference(interfaceClass = DemoService.class, group = "DUBBO", version = "1.0.0", + application = "application", module = "module", registry = {"1", "2", "3"}) + static final Class INTERFACE_CLASS = DemoService.class; + + static final String GROUP = "DUBBO"; + + static final String VERSION = "1.0.0"; + + @Test + public void testRequiredAttributes() { + + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, VERSION, GROUP); + + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); + + } + + @Test + public void testServiceAnnotation() { + Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", + builder.build()); + } + + @Test + public void testReferenceAnnotation() { + Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", + builder.build()); + } + + @Test + public void testBuildAll() { + + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, VERSION, GROUP); + + builder.application("application"); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application", + builder.build()); + + builder.module("module"); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module", + builder.build()); + + builder.registry("1", "2", "3"); + Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", + builder.build()); + + } +} From 80b6277438127c0aca9fe36a1e5063a25d87f9bf Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Mon, 13 Aug 2018 17:19:38 +0800 Subject: [PATCH 12/18] Polish apache/incubator-dubbo/#2235 --- .../spring/beans/factory/annotation/ServiceBeanNameBuilder.java | 1 - 1 file changed, 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java index 0020a57794d..e6e0373bcb1 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -49,7 +49,6 @@ class ServiceBeanNameBuilder { private String module; - private String[] registry; private ServiceBeanNameBuilder(Class interfaceClass, String version, String group) { From cac7021bdb0fbd85cbbcec5f6a9a2513361b7071 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 14 Aug 2018 09:50:49 +0800 Subject: [PATCH 13/18] Polish incubator-dubbo#2251 --- .../dubbo/config/spring/ServiceBean.java | 56 ++++++-- .../ReferenceAnnotationBeanPostProcessor.java | 120 ++++++++---------- .../ServiceAnnotationBeanPostProcessor.java | 55 ++------ .../annotation/ServiceBeanNameBuilder.java | 102 ++++++--------- .../context/event/ServiceBeanExportEvent.java | 51 ++++++++ .../config/spring/util/AnnotationUtils.java | 42 ++++++ ...erenceAnnotationBeanPostProcessorTest.java | 113 ++++++++--------- ...erviceAnnotationBeanPostProcessorTest.java | 45 ++----- .../ServiceAnnotationTestConfiguration.java | 115 +++++++++++++++++ .../ServiceBeanNameBuilderTest.java | 38 ++---- .../context/annotation/EnableDubboTest.java | 38 +++--- .../annotation/provider/DemoServiceImpl.java | 2 +- 12 files changed, 450 insertions(+), 327 deletions(-) create mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index b38684b2c75..56665faed09 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -16,23 +16,16 @@ */ package com.alibaba.dubbo.config.spring; -import com.alibaba.dubbo.config.ApplicationConfig; -import com.alibaba.dubbo.config.ModuleConfig; -import com.alibaba.dubbo.config.MonitorConfig; -import com.alibaba.dubbo.config.ProtocolConfig; -import com.alibaba.dubbo.config.ProviderConfig; -import com.alibaba.dubbo.config.RegistryConfig; -import com.alibaba.dubbo.config.ServiceConfig; +import com.alibaba.dubbo.config.*; import com.alibaba.dubbo.config.annotation.Service; +import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportEvent; import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ApplicationListener; +import org.springframework.context.*; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.AbstractApplicationContext; @@ -46,7 +39,9 @@ * * @export */ -public class ServiceBean extends ServiceConfig implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware { +public class ServiceBean extends ServiceConfig implements InitializingBean, DisposableBean, + ApplicationContextAware, ApplicationListener, BeanNameAware, + ApplicationEventPublisherAware { private static final long serialVersionUID = 213195494150089726L; @@ -60,6 +55,8 @@ public class ServiceBean extends ServiceConfig implements InitializingBean private transient boolean supportedApplicationListener; + private ApplicationEventPublisher applicationEventPublisher; + public ServiceBean() { super(); this.service = null; @@ -265,6 +262,34 @@ && getInterface() != null && getInterface().length() > 0 } } + /** + * Get the name of {@link ServiceBean} + * + * @return {@link ServiceBean}'s name + * @since 2.6.4 + */ + public String getBeanName() { + return this.beanName; + } + + /** + * @since 2.6.4 + */ + @Override + public void export() { + super.export(); + // Publish ServiceBeanExportEvent + publishExportEvent(); + } + + /** + * @since 2.6.4 + */ + private void publishExportEvent() { + ServiceBeanExportEvent exportEvent = new ServiceBeanExportEvent(this); + applicationEventPublisher.publishEvent(exportEvent); + } + @Override public void destroy() throws Exception { // This will only be called for singleton scope bean, and expected to be called by spring shutdown hook when BeanFactory/ApplicationContext destroys. @@ -280,4 +305,13 @@ protected Class getServiceClass(T ref) { } return super.getServiceClass(ref); } + + /** + * @param applicationEventPublisher + * @since 2.6.4 + */ + @Override + public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index aa2c602f211..18b70554637 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -18,11 +18,14 @@ import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; -import com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor; +import com.alibaba.dubbo.config.spring.ServiceBean; +import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportEvent; +import com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; @@ -42,8 +45,8 @@ * * @since 2.5.7 */ -public class ReferenceAnnotationBeanPostProcessor extends CustomizedAnnotationBeanPostProcessor - implements ApplicationContextAware, ApplicationListener { +public class ReferenceAnnotationBeanPostProcessor extends AnnotationInjectedBeanPostProcessor + implements ApplicationContextAware, ApplicationListener { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} @@ -58,9 +61,7 @@ public class ReferenceAnnotationBeanPostProcessor extends CustomizedAnnotationBe private final ConcurrentMap> referenceBeanCache = new ConcurrentHashMap>(CACHE_SIZE); - private final ConcurrentHashMap proxyCache = new ConcurrentHashMap(CACHE_SIZE); - - private final ConcurrentHashMap referenceBeanInvocationHandlerCache = + private final ConcurrentHashMap localReferenceBeanInvocationHandlerCache = new ConcurrentHashMap(CACHE_SIZE); private final ConcurrentMap> injectedFieldReferenceBeanCache = @@ -81,27 +82,6 @@ public Collection> getReferenceBeans() { return referenceBeanCache.values(); } - private static String resolveInterfaceName(Reference reference, Class beanClass) - throws IllegalStateException { - - String interfaceName; - if (!"".equals(reference.interfaceName())) { - interfaceName = reference.interfaceName(); - } else if (!void.class.equals(reference.interfaceClass())) { - interfaceName = reference.interfaceClass().getName(); - } else if (beanClass.isInterface()) { - interfaceName = beanClass.getName(); - } else { - throw new IllegalStateException( - "The @Reference undefined interfaceClass or interfaceName, and the property type " - + beanClass.getName() + " is not a interface."); - } - - return interfaceName; - - } - - /** * Get {@link ReferenceBean} {@link Map} in injected field. * @@ -126,37 +106,37 @@ public Map> getInjectedMetho protected Object doGetInjectedBean(Reference reference, Object bean, String beanName, Class injectedType, InjectionMetadata.InjectedElement injectedElement) throws Exception { - String referenceBeanCacheKey = buildReferenceBeanCacheKey(reference, injectedType); + String referencedBeanName = buildReferencedBeanName(reference, injectedType); - ReferenceBean referenceBean = buildReferenceBeanIfAbsent(referenceBeanCacheKey, reference, injectedType, getClassLoader()); + ReferenceBean referenceBean = buildReferenceBeanIfAbsent(referencedBeanName, reference, injectedType, getClassLoader()); cacheInjectedReferenceBean(referenceBean, injectedElement); - Object proxy = buildProxyIfAbsent(referenceBeanCacheKey, referenceBean, injectedType); + Object proxy = buildProxy(referencedBeanName, referenceBean, injectedType); return proxy; } - private Object buildProxyIfAbsent(String referenceBeanCacheKey, ReferenceBean referenceBean, Class injectedType) { - - Object proxy = proxyCache.get(referenceBeanCacheKey); - - if (proxy == null) { - InvocationHandler handler = buildInvocationHandlerIfAbsent(referenceBeanCacheKey, referenceBean); - proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler); - proxyCache.put(referenceBeanCacheKey, proxy); - } - + private Object buildProxy(String referencedBeanName, ReferenceBean referenceBean, Class injectedType) { + InvocationHandler handler = buildInvocationHandler(referencedBeanName, referenceBean); + Object proxy = Proxy.newProxyInstance(getClassLoader(), new Class[]{injectedType}, handler); return proxy; } - private InvocationHandler buildInvocationHandlerIfAbsent(String referenceBeanCacheKey, ReferenceBean referenceBean) { + private InvocationHandler buildInvocationHandler(String referencedBeanName, ReferenceBean referenceBean) { - ReferenceBeanInvocationHandler handler = referenceBeanInvocationHandlerCache.get(referenceBeanCacheKey); + ReferenceBeanInvocationHandler handler = localReferenceBeanInvocationHandlerCache.get(referencedBeanName); if (handler == null) { handler = new ReferenceBeanInvocationHandler(referenceBean); - referenceBeanInvocationHandlerCache.put(referenceBeanCacheKey, handler); + } + + if (applicationContext.containsBean(referencedBeanName)) { // Is local @Service Bean or not ? + // ReferenceBeanInvocationHandler's initialization has to wait for current local @Service Bean has been exported. + localReferenceBeanInvocationHandlerCache.put(referencedBeanName, handler); + } else { + // Remote Reference Bean should initialize immediately + handler.init(); } return handler; @@ -186,36 +166,31 @@ private void init() { protected String buildInjectedObjectCacheKey(Reference reference, Object bean, String beanName, Class injectedType, InjectionMetadata.InjectedElement injectedElement) { - String key = buildReferenceBeanCacheKey(reference, injectedType) + - "?source=" + (injectedElement.getMember()); + String key = buildReferencedBeanName(reference, injectedType) + + "#source=" + (injectedElement.getMember()); return key; } - private String buildReferenceBeanCacheKey(Reference reference, Class injectedType) { - - String interfaceName = resolveInterfaceName(reference, injectedType); + private String buildReferencedBeanName(Reference reference, Class injectedType) { - String key = reference.url() + - "/" + interfaceName + - "/" + reference.version() + - "/" + reference.group(); + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, injectedType, getEnvironment()); - return getEnvironment().resolvePlaceholders(key); + return getEnvironment().resolvePlaceholders(builder.build()); } - private ReferenceBean buildReferenceBeanIfAbsent(String referenceBeanCacheKey, Reference reference, + private ReferenceBean buildReferenceBeanIfAbsent(String referencedBeanName, Reference reference, Class referencedType, ClassLoader classLoader) throws Exception { - ReferenceBean referenceBean = referenceBeanCache.get(referenceBeanCacheKey); + ReferenceBean referenceBean = referenceBeanCache.get(referencedBeanName); if (referenceBean == null) { ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder .create(reference, classLoader, applicationContext) .interfaceClass(referencedType); referenceBean = beanBuilder.build(); - referenceBeanCache.put(referenceBeanCacheKey, referenceBean); + referenceBeanCache.put(referencedBeanName, referenceBean); } return referenceBean; @@ -236,28 +211,39 @@ public void setApplicationContext(ApplicationContext applicationContext) throws } @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - - if (proxyCache.isEmpty() || referenceBeanCache.isEmpty() || referenceBeanInvocationHandlerCache.isEmpty()) { - return; + public void onApplicationEvent(ApplicationEvent event) { + if (event instanceof ServiceBeanExportEvent) { + onServiceBeanExportEvent((ServiceBeanExportEvent) event); + } else if (event instanceof ContextRefreshedEvent) { + onContextRefreshedEvent((ContextRefreshedEvent) event); } + } + + private void onServiceBeanExportEvent(ServiceBeanExportEvent event) { + ServiceBean serviceBean = event.getServiceBean(); + initReferenceBeanInvocationHandler(serviceBean); + } - // initialize all - for (ReferenceBeanInvocationHandler handler : referenceBeanInvocationHandlerCache.values()) { + private void initReferenceBeanInvocationHandler(ServiceBean serviceBean) { + String serviceBeanName = serviceBean.getBeanName(); + // Remove ServiceBean when it's exported + ReferenceBeanInvocationHandler handler = localReferenceBeanInvocationHandlerCache.remove(serviceBeanName); + // Initialize + if (handler != null) { handler.init(); } + } + + private void onContextRefreshedEvent(ContextRefreshedEvent event) { - // clear Proxies and Handlers - this.proxyCache.clear(); - this.referenceBeanInvocationHandlerCache.clear(); } + @Override public void destroy() throws Exception { super.destroy(); - this.proxyCache.clear(); this.referenceBeanCache.clear(); - this.referenceBeanInvocationHandlerCache.clear(); + this.localReferenceBeanInvocationHandlerCache.clear(); this.injectedFieldReferenceBeanCache.clear(); this.injectedMethodReferenceBeanCache.clear(); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java index 35604650906..f92173d6c1a 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessor.java @@ -24,17 +24,8 @@ import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.config.SingletonBeanRegistry; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.ManagedList; +import org.springframework.beans.factory.config.*; +import org.springframework.beans.factory.support.*; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.AnnotationBeanNameGenerator; @@ -44,17 +35,9 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import org.springframework.util.*; + +import java.util.*; import static com.alibaba.dubbo.config.spring.util.ObjectUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; @@ -71,8 +54,6 @@ public class ServiceAnnotationBeanPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, ResourceLoaderAware, BeanClassLoaderAware { - private static final String SEPARATOR = ":"; - private final Logger logger = LoggerFactory.getLogger(getClass()); private final Set packagesToScan; @@ -262,7 +243,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean registry.registerBeanDefinition(beanName, serviceBeanDefinition); if (logger.isInfoEnabled()) { - logger.warn("The BeanDefinition[" + serviceBeanDefinition + + logger.info("The BeanDefinition[" + serviceBeanDefinition + "] of ServiceBean has been registered with name : " + beanName); } @@ -271,7 +252,7 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean if (logger.isWarnEnabled()) { logger.warn("The Duplicated BeanDefinition[" + serviceBeanDefinition + "] of ServiceBean[ bean name : " + beanName + - "] was be found , Did @DubboComponentScan scan to same package in many times?"); + "] was be found!"); } } @@ -289,27 +270,9 @@ private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, Bean */ private String generateServiceBeanName(Service service, Class interfaceClass, String annotatedServiceBeanName) { - StringBuilder beanNameBuilder = new StringBuilder(ServiceBean.class.getSimpleName()); - - beanNameBuilder.append(SEPARATOR).append(annotatedServiceBeanName); - - String interfaceClassName = interfaceClass.getName(); - - beanNameBuilder.append(SEPARATOR).append(interfaceClassName); - - String version = service.version(); - - if (StringUtils.hasText(version)) { - beanNameBuilder.append(SEPARATOR).append(version); - } - - String group = service.group(); - - if (StringUtils.hasText(group)) { - beanNameBuilder.append(SEPARATOR).append(group); - } + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, interfaceClass, environment); - return beanNameBuilder.toString(); + return builder.build(); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java index e6e0373bcb1..14556eab140 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java @@ -16,15 +16,15 @@ */ package com.alibaba.dubbo.config.spring.beans.factory.annotation; -import com.alibaba.dubbo.config.ApplicationConfig; -import com.alibaba.dubbo.config.ModuleConfig; -import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.ServiceBean; +import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; +import static com.alibaba.dubbo.config.spring.util.AnnotationUtils.resolveInterfaceName; + /** * Dubbo {@link Service @Service} Bean Builder * @@ -39,48 +39,46 @@ class ServiceBeanNameBuilder { private static final String SEPARATOR = ":"; - private final Class interfaceClass; - - private final String version; + private final String interfaceClassName; - private final String group; + private final Environment environment; - private String application; + // Optional + private String version; - private String module; + private String group; - private String[] registry; + private ServiceBeanNameBuilder(String interfaceClassName, Environment environment) { + this.interfaceClassName = interfaceClassName; + this.environment = environment; + } - private ServiceBeanNameBuilder(Class interfaceClass, String version, String group) { - this.interfaceClass = interfaceClass; - this.version = version; - this.group = group; + private ServiceBeanNameBuilder(Class interfaceClass, Environment environment) { + this(interfaceClass.getName(), environment); } - private ServiceBeanNameBuilder(Service service, Class interfaceClass) { - this(service.interfaceClass() == null ? interfaceClass : service.interfaceClass(), service.version(), service.group()); - application(service.application()); - module(service.module()); - registry(service.registry()); + private ServiceBeanNameBuilder(Service service, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(service, interfaceClass), environment); + this.group(service.group()); + this.version(service.version()); } - private ServiceBeanNameBuilder(Reference reference, Class interfaceClass) { - this(reference.interfaceClass() == null ? interfaceClass : reference.interfaceClass(), reference.version(), reference.group()); - application(reference.application()); - module(reference.module()); - registry(reference.registry()); + private ServiceBeanNameBuilder(Reference reference, Class interfaceClass, Environment environment) { + this(resolveInterfaceName(reference, interfaceClass), environment); + this.group(reference.group()); + this.version(reference.version()); } - public static ServiceBeanNameBuilder create(Class interfaceClass, String version, String group) { - return new ServiceBeanNameBuilder(interfaceClass, version, group); + public static ServiceBeanNameBuilder create(Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(interfaceClass, environment); } - public static ServiceBeanNameBuilder create(Service service, Class interfaceClass) { - return new ServiceBeanNameBuilder(service, interfaceClass); + public static ServiceBeanNameBuilder create(Service service, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(service, interfaceClass, environment); } - public static ServiceBeanNameBuilder create(Reference reference, Class interfaceClass) { - return new ServiceBeanNameBuilder(reference, interfaceClass); + public static ServiceBeanNameBuilder create(Reference reference, Class interfaceClass, Environment environment) { + return new ServiceBeanNameBuilder(reference, interfaceClass, environment); } private static void append(StringBuilder builder, String value) { @@ -89,50 +87,26 @@ private static void append(StringBuilder builder, String value) { } } - /** - * Set {@link ApplicationConfig application} bean name - * - * @param application {@link ApplicationConfig application} bean name - * @return {@link ServiceBeanNameBuilder} - */ - public ServiceBeanNameBuilder application(String application) { - this.application = application; - return this; - } - - /** - * Set {@link ModuleConfig module} bean name - * - * @param module {@link ModuleConfig module} bean name - * @return {@link ServiceBeanNameBuilder} - */ - public ServiceBeanNameBuilder module(String module) { - this.module = module; + public ServiceBeanNameBuilder group(String group) { + this.group = group; return this; } - /** - * Set {@link RegistryConfig monitor} bean names - * - * @param registry {@link RegistryConfig monitor} bean name - * @return {@link ServiceBeanNameBuilder} - */ - public ServiceBeanNameBuilder registry(String... registry) { - this.registry = registry; + public ServiceBeanNameBuilder version(String version) { + this.version = version; return this; } public String build() { - StringBuilder beanNameBuilder = new StringBuilder(); + StringBuilder beanNameBuilder = new StringBuilder("ServiceBean").append(SEPARATOR); // Required - append(beanNameBuilder, interfaceClass.getName()); + append(beanNameBuilder, interfaceClassName); + // Optional append(beanNameBuilder, version); append(beanNameBuilder, group); - // Optional - append(beanNameBuilder, application); - append(beanNameBuilder, module); - append(beanNameBuilder, StringUtils.arrayToCommaDelimitedString(registry)); // Build and remove last ":" - return beanNameBuilder.substring(0, beanNameBuilder.length() - 1); + String rawBeanName = beanNameBuilder.substring(0, beanNameBuilder.length() - 1); + // Resolve placeholders + return environment.resolvePlaceholders(rawBeanName); } } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java new file mode 100644 index 00000000000..ac352e6fb38 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.context.event; + +import com.alibaba.dubbo.config.spring.ServiceBean; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; + +/** + * A {@link ApplicationEvent} after {@link ServiceBean} {@link ServiceBean#export() export} invocation + * + * @author Mercy + * @see ApplicationEvent + * @see ApplicationListener + * @see ServiceBean + * @since 2.6.4 + */ +public class ServiceBeanExportEvent extends ApplicationEvent { + + /** + * Create a new ApplicationEvent. + * + * @param serviceBean {@link ServiceBean} bean + */ + public ServiceBeanExportEvent(ServiceBean serviceBean) { + super(serviceBean); + } + + /** + * Get {@link ServiceBean} instance + * + * @return non-null + */ + public ServiceBean getServiceBean() { + return (ServiceBean) super.getSource(); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java index aa15e567eb0..87f82d3063d 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/AnnotationUtils.java @@ -16,6 +16,8 @@ */ package com.alibaba.dubbo.config.spring.util; +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.annotation.Service; import org.springframework.core.env.PropertyResolver; import java.lang.annotation.Annotation; @@ -86,4 +88,44 @@ public static Map getAttributes(Annotation annotation, PropertyR } + public static String resolveInterfaceName(Service service, Class defaultInterfaceClass) + throws IllegalStateException { + + String interfaceName; + if (!"".equals(service.interfaceName())) { + interfaceName = service.interfaceName(); + } else if (!void.class.equals(service.interfaceClass())) { + interfaceName = service.interfaceClass().getName(); + } else if (defaultInterfaceClass.isInterface()) { + interfaceName = defaultInterfaceClass.getName(); + } else { + throw new IllegalStateException( + "The @Service undefined interfaceClass or interfaceName, and the type " + + defaultInterfaceClass.getName() + " is not a interface."); + } + + return interfaceName; + + } + + public static String resolveInterfaceName(Reference reference, Class defaultInterfaceClass) + throws IllegalStateException { + + String interfaceName; + if (!"".equals(reference.interfaceName())) { + interfaceName = reference.interfaceName(); + } else if (!void.class.equals(reference.interfaceClass())) { + interfaceName = reference.interfaceClass().getName(); + } else if (defaultInterfaceClass.isInterface()) { + interfaceName = defaultInterfaceClass.getName(); + } else { + throw new IllegalStateException( + "The @Reference undefined interfaceClass or interfaceName, and the type " + + defaultInterfaceClass.getName() + " is not a interface."); + } + + return interfaceName; + + } + } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java index 005f1e33981..eba43b2a599 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.java @@ -19,14 +19,17 @@ import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.api.DemoService; -import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan; -import org.junit.*; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.ImportResource; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; import java.util.Collection; import java.util.Map; @@ -40,49 +43,48 @@ * * @since 2.5.7 */ +@RunWith(SpringRunner.class) +@ContextConfiguration( + classes = { + ServiceAnnotationTestConfiguration.class, + ReferenceAnnotationBeanPostProcessorTest.class + }) +@TestPropertySource(properties = { + "packagesToScan = com.alibaba.dubbo.config.spring.context.annotation.provider", + "consumer.version = ${demo.service.version}", + "consumer.url = dubbo://127.0.0.1:12345", +}) public class ReferenceAnnotationBeanPostProcessorTest { - private ConfigurableApplicationContext providerApplicationContext; - - @BeforeClass - public static void prepare() { - System.setProperty("provider.version", "1.2"); - System.setProperty("package1", "com.alibaba.dubbo.config.spring.annotation.provider"); - System.setProperty("packagesToScan", "${package1}"); - System.setProperty("consumer.version", "1.2"); - System.setProperty("consumer.url", "dubbo://127.0.0.1:12345"); + @Bean + public TestBean testBean() { + return new TestBean(); } - @Before - public void init() { - // Starts Provider - providerApplicationContext = new AnnotationConfigApplicationContext(ServiceAnnotationBeanPostProcessorTest.TestConfiguration.class); + @Bean(BEAN_NAME) + public ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor() { + return new ReferenceAnnotationBeanPostProcessor(); } - @After - public void destroy() { - // Shutdowns Provider - providerApplicationContext.close(); - } + @Autowired + private ConfigurableApplicationContext context; @Test public void test() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); - TestBean testBean = context.getBean(TestBean.class); DemoService demoService = testBean.getDemoService(); - Assert.assertEquals("annotation:Mercy", demoService.sayName("Mercy")); + Assert.assertEquals("Hello,Mercy", demoService.sayName("Mercy")); Assert.assertNotNull(testBean.getDemoServiceFromAncestor()); Assert.assertNotNull(testBean.getDemoServiceFromParent()); Assert.assertNotNull(testBean.getDemoService()); - Assert.assertEquals("annotation:Mercy", demoService.sayName("Mercy")); - - context.close(); + Assert.assertEquals("Hello,Mercy", testBean.getDemoServiceFromAncestor().sayName("Mercy")); + Assert.assertEquals("Hello,Mercy", testBean.getDemoServiceFromParent().sayName("Mercy")); + Assert.assertEquals("Hello,Mercy", testBean.getDemoService().sayName("Mercy")); } @@ -92,8 +94,6 @@ public void test() throws Exception { @Test public void testGetReferenceBeans() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); - ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); @@ -112,8 +112,6 @@ public void testGetReferenceBeans() { @Test public void testGetInjectedFieldReferenceBeanMap() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); - ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); @@ -127,12 +125,12 @@ public void testGetInjectedFieldReferenceBeanMap() { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); - Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedFieldElement", + Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor$AnnotatedFieldElement", injectedElement.getClass().getName()); ReferenceBean referenceBean = entry.getValue(); - Assert.assertEquals("1.2", referenceBean.getVersion()); + Assert.assertEquals("2.5.7", referenceBean.getVersion()); Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); } @@ -142,8 +140,6 @@ public void testGetInjectedFieldReferenceBeanMap() { @Test public void testGetInjectedMethodReferenceBeanMap() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); - ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); @@ -157,36 +153,35 @@ public void testGetInjectedMethodReferenceBeanMap() { InjectionMetadata.InjectedElement injectedElement = entry.getKey(); - Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.CustomizedAnnotationBeanPostProcessor$AnnotatedMethodElement", + Assert.assertEquals("com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor$AnnotatedMethodElement", injectedElement.getClass().getName()); ReferenceBean referenceBean = entry.getValue(); - Assert.assertEquals("1.2", referenceBean.getVersion()); + Assert.assertEquals("2.5.7", referenceBean.getVersion()); Assert.assertEquals("dubbo://127.0.0.1:12345", referenceBean.getUrl()); } } - @Test - public void testModuleInfo() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestBean.class); - - ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, - ReferenceAnnotationBeanPostProcessor.class); - - - Map> referenceBeanMap = - beanPostProcessor.getInjectedMethodReferenceBeanMap(); - - for (Map.Entry> entry : referenceBeanMap.entrySet()) { - ReferenceBean referenceBean = entry.getValue(); - - assertThat(referenceBean.getModule().getName(), is("defaultModule")); - assertThat(referenceBean.getMonitor(), not(nullValue())); - } - } +// @Test +// public void testModuleInfo() { +// +// ReferenceAnnotationBeanPostProcessor beanPostProcessor = context.getBean(BEAN_NAME, +// ReferenceAnnotationBeanPostProcessor.class); +// +// +// Map> referenceBeanMap = +// beanPostProcessor.getInjectedMethodReferenceBeanMap(); +// +// for (Map.Entry> entry : referenceBeanMap.entrySet()) { +// ReferenceBean referenceBean = entry.getValue(); +// +// assertThat(referenceBean.getModule().getName(), is("defaultModule")); +// assertThat(referenceBean.getMonitor(), not(nullValue())); +// } +// } private static class AncestorBean { @@ -200,7 +195,7 @@ public DemoService getDemoServiceFromAncestor() { return demoServiceFromAncestor; } - @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345") + @Reference(version = "2.5.7", url = "dubbo://127.0.0.1:12345") public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { this.demoServiceFromAncestor = demoServiceFromAncestor; } @@ -224,8 +219,6 @@ public DemoService getDemoServiceFromParent() { } - @ImportResource("META-INF/spring/dubbo-annotation-consumer.xml") - @DubboComponentScan(basePackageClasses = ReferenceAnnotationBeanPostProcessorTest.class) static class TestBean extends ParentBean { private DemoService demoService; @@ -237,7 +230,7 @@ public DemoService getDemoService() { return demoService; } - @Reference(version = "1.2", url = "dubbo://127.0.0.1:12345") + @Reference(version = "2.5.7", url = "dubbo://127.0.0.1:12345") public void setDemoService(DemoService demoService) { this.demoService = demoService; } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java index c0964418144..6133c48aaba 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationBeanPostProcessorTest.java @@ -25,9 +25,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ImportResource; -import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; @@ -41,17 +38,25 @@ */ @RunWith(SpringRunner.class) @ContextConfiguration( - classes = {ServiceAnnotationBeanPostProcessorTest.TestConfiguration.class}) + classes = { + ServiceAnnotationTestConfiguration.class, + ServiceAnnotationBeanPostProcessorTest.class + }) @TestPropertySource(properties = { - "package1 = com.alibaba.dubbo.config.spring.context.annotation", - "packagesToScan = ${package1}", - "provider.version = 1.2" + "provider.package = com.alibaba.dubbo.config.spring.context.annotation.provider", + "packagesToScan = ${provider.package}", }) public class ServiceAnnotationBeanPostProcessorTest { @Autowired private ConfigurableListableBeanFactory beanFactory; + @Bean + public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor2 + (@Value("${packagesToScan}") String... packagesToScan) { + return new ServiceAnnotationBeanPostProcessor(packagesToScan); + } + @Test public void test() { @@ -61,38 +66,16 @@ public void test() { Map serviceBeansMap = beanFactory.getBeansOfType(ServiceBean.class); - Assert.assertEquals(3, serviceBeansMap.size()); + Assert.assertEquals(2, serviceBeansMap.size()); Map beanPostProcessorsMap = beanFactory.getBeansOfType(ServiceAnnotationBeanPostProcessor.class); - Assert.assertEquals(4, beanPostProcessorsMap.size()); + Assert.assertEquals(2, beanPostProcessorsMap.size()); - Assert.assertTrue(beanPostProcessorsMap.containsKey("doubleServiceAnnotationBeanPostProcessor")); - Assert.assertTrue(beanPostProcessorsMap.containsKey("emptyServiceAnnotationBeanPostProcessor")); Assert.assertTrue(beanPostProcessorsMap.containsKey("serviceAnnotationBeanPostProcessor")); Assert.assertTrue(beanPostProcessorsMap.containsKey("serviceAnnotationBeanPostProcessor2")); } - @ImportResource("META-INF/spring/dubbo-annotation-provider.xml") - @PropertySource("META-INF/default.properties") - @ComponentScan("com.alibaba.dubbo.config.spring.context.annotation.provider") - public static class TestConfiguration { - - @Bean - public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor - (@Value("${packagesToScan}") String... packagesToScan) { - return new ServiceAnnotationBeanPostProcessor(packagesToScan); - } - - @Bean - public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor2 - (@Value("${packagesToScan}") String... packagesToScan) { - return new ServiceAnnotationBeanPostProcessor(packagesToScan); - } - - - } - } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java new file mode 100644 index 00000000000..c2f59239041 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ProtocolConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.annotation.Service; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.PropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.TransactionStatus; + +/** + * {@link Service} Bean + * + * @author Mercy + * @since 2.6.4 + */ +@PropertySource("META-INF/default.properties") +public class ServiceAnnotationTestConfiguration { + + /** + * Current application configuration, to replace XML config: + * + * <dubbo:application name="dubbo-annotation-provider"/> + * + * + * @return {@link ApplicationConfig} Bean + */ + @Bean("dubbo-annotation-provider") + public ApplicationConfig applicationConfig() { + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName("dubbo-annotation-provider"); + return applicationConfig; + } + + /** + * Current registry center configuration, to replace XML config: + * + * <dubbo:registry id="my-registry" address="N/A"/> + * + * + * @return {@link RegistryConfig} Bean + */ + @Bean("my-registry") + public RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress("N/A"); + return registryConfig; + } + + /** + * Current protocol configuration, to replace XML config: + * + * <dubbo:protocol name="dubbo" port="12345"/> + * + * + * @return {@link ProtocolConfig} Bean + */ + @Bean("dubbo") + public ProtocolConfig protocolConfig() { + ProtocolConfig protocolConfig = new ProtocolConfig(); + protocolConfig.setName("dubbo"); + protocolConfig.setPort(12345); + return protocolConfig; + } + + @Primary + @Bean + public PlatformTransactionManager platformTransactionManager() { + return new PlatformTransactionManager() { + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { + return null; + } + + @Override + public void commit(TransactionStatus status) throws TransactionException { + + } + + @Override + public void rollback(TransactionStatus status) throws TransactionException { + + } + }; + } + + @Bean + public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor + (@Value("${packagesToScan}") String... packagesToScan) { + return new ServiceAnnotationBeanPostProcessor(packagesToScan); + } + +} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java index dcf1348ed9f..83363691e45 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.java @@ -22,6 +22,7 @@ import org.junit.Assert; import org.junit.Test; import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.mock.env.MockEnvironment; import org.springframework.util.ReflectionUtils; import static com.alibaba.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.GROUP; @@ -46,47 +47,30 @@ public class ServiceBeanNameBuilderTest { static final String VERSION = "1.0.0"; - @Test - public void testRequiredAttributes() { + static final String BEAN_NAME = "ServiceBean:com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO"; - ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, VERSION, GROUP); - - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build()); + private MockEnvironment environment = new MockEnvironment(); + @Test + public void testRequiredAttributes() { + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, environment); + Assert.assertEquals("ServiceBean:com.alibaba.dubbo.config.spring.api.DemoService", builder.build()); } @Test public void testServiceAnnotation() { Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class); - ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS); - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS, environment); + Assert.assertEquals(BEAN_NAME, builder.build()); } @Test public void testReferenceAnnotation() { Reference reference = AnnotationUtils.getAnnotation(ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class); - ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS); - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", + ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS, environment); + Assert.assertEquals(BEAN_NAME, builder.build()); } - @Test - public void testBuildAll() { - - ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, VERSION, GROUP); - - builder.application("application"); - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application", - builder.build()); - - builder.module("module"); - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module", - builder.build()); - - builder.registry("1", "2", "3"); - Assert.assertEquals("com.alibaba.dubbo.config.spring.api.DemoService:1.0.0:DUBBO:application:module:1,2,3", - builder.build()); - - } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java index c5018da2522..4f71ce148fd 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/EnableDubboTest.java @@ -23,12 +23,14 @@ import com.alibaba.dubbo.config.spring.context.annotation.provider.DemoServiceImpl; import org.junit.Assert; import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.aop.support.AopUtils; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.PropertySource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.*; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; @@ -43,17 +45,21 @@ * * @since 2.5.8 */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {EnableDubboTest.class}) +@TestPropertySource(locations = "classpath:/META-INF/dubbb-provider.properties", + properties = "demo.service.version = 2.5.7") +@EnableDubbo(scanBasePackages = "com.alibaba.dubbo.config.spring.context.annotation.provider") +@ComponentScan(basePackages = "com.alibaba.dubbo.config.spring.context.annotation.provider") +@EnableTransactionManagement public class EnableDubboTest { + @Autowired + private ApplicationContext providerContext; + @Test public void test() { - AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext(); - - providerContext.register(TestProviderConfiguration.class); - - providerContext.refresh(); - DemoService demoService = providerContext.getBean(DemoService.class); String value = demoService.sayName("Mercy"); @@ -68,11 +74,7 @@ public void test() { // Test @Transactional is present or not Assert.assertNotNull(findAnnotation(beanClass, Transactional.class)); - AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); - - consumerContext.register(TestConsumerConfiguration.class); - - consumerContext.refresh(); + AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(TestConsumerConfiguration.class); TestConsumerConfiguration consumerConfiguration = consumerContext.getBean(TestConsumerConfiguration.class); @@ -127,10 +129,6 @@ public void test() { // Test multiple binding Assert.assertEquals("N/A", registryConfig.getAddress()); - providerContext.close(); - consumerContext.close(); - - } @EnableDubbo(scanBasePackages = "com.alibaba.dubbo.config.spring.context.annotation.provider") diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java index 9961aa27a85..96a6b1af737 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java @@ -28,7 +28,7 @@ * @since 2.5.8 */ @com.alibaba.dubbo.config.annotation.Service( - version = "2.5.7", + version = "${demo.service.version}", application = "${demo.service.application}", protocol = "${demo.service.protocol}", registry = "${demo.service.registry}" From a8f4f732ac1fdad3e99effa798568bdd3db35287 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 14 Aug 2018 10:12:23 +0800 Subject: [PATCH 14/18] Update spring-context-supprt version to be release --- dependencies-bom/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies-bom/pom.xml b/dependencies-bom/pom.xml index a6742b71d27..6f06c22a7a5 100644 --- a/dependencies-bom/pom.xml +++ b/dependencies-bom/pom.xml @@ -104,7 +104,7 @@ 8.5.31 - 1.0.1-SNAPSHOT + 1.0.1 1.7.25 1.2 From 593ce643221e2b02d56dcd9b43aa0d62ed7e6fcf Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 14 Aug 2018 10:25:04 +0800 Subject: [PATCH 15/18] Rename ServiceBeanExportEvent to be ServiceBeanExportedEvent --- .../java/com/alibaba/dubbo/config/spring/ServiceBean.java | 6 +++--- .../annotation/ReferenceAnnotationBeanPostProcessor.java | 8 ++++---- ...BeanExportEvent.java => ServiceBeanExportedEvent.java} | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) rename dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/{ServiceBeanExportEvent.java => ServiceBeanExportedEvent.java} (92%) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java index 56665faed09..d03f4c1a31b 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java @@ -18,7 +18,7 @@ import com.alibaba.dubbo.config.*; import com.alibaba.dubbo.config.annotation.Service; -import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportEvent; +import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportedEvent; import com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanFactoryUtils; @@ -278,7 +278,7 @@ public String getBeanName() { @Override public void export() { super.export(); - // Publish ServiceBeanExportEvent + // Publish ServiceBeanExportedEvent publishExportEvent(); } @@ -286,7 +286,7 @@ public void export() { * @since 2.6.4 */ private void publishExportEvent() { - ServiceBeanExportEvent exportEvent = new ServiceBeanExportEvent(this); + ServiceBeanExportedEvent exportEvent = new ServiceBeanExportedEvent(this); applicationEventPublisher.publishEvent(exportEvent); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java index 18b70554637..37debea5e19 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.ServiceBean; -import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportEvent; +import com.alibaba.dubbo.config.spring.context.event.ServiceBeanExportedEvent; import com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.InjectionMetadata; @@ -212,14 +212,14 @@ public void setApplicationContext(ApplicationContext applicationContext) throws @Override public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ServiceBeanExportEvent) { - onServiceBeanExportEvent((ServiceBeanExportEvent) event); + if (event instanceof ServiceBeanExportedEvent) { + onServiceBeanExportEvent((ServiceBeanExportedEvent) event); } else if (event instanceof ContextRefreshedEvent) { onContextRefreshedEvent((ContextRefreshedEvent) event); } } - private void onServiceBeanExportEvent(ServiceBeanExportEvent event) { + private void onServiceBeanExportEvent(ServiceBeanExportedEvent event) { ServiceBean serviceBean = event.getServiceBean(); initReferenceBeanInvocationHandler(serviceBean); } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportedEvent.java similarity index 92% rename from dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java rename to dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportedEvent.java index ac352e6fb38..3642fd16966 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportEvent.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/event/ServiceBeanExportedEvent.java @@ -29,14 +29,14 @@ * @see ServiceBean * @since 2.6.4 */ -public class ServiceBeanExportEvent extends ApplicationEvent { +public class ServiceBeanExportedEvent extends ApplicationEvent { /** * Create a new ApplicationEvent. * * @param serviceBean {@link ServiceBean} bean */ - public ServiceBeanExportEvent(ServiceBean serviceBean) { + public ServiceBeanExportedEvent(ServiceBean serviceBean) { super(serviceBean); } From c0928d880579b66b90379bb9afd18db86b502f34 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Tue, 14 Aug 2018 18:46:47 +0800 Subject: [PATCH 16/18] Poblish apache/incubator-dubbo#2297 --- .../DubboConfigBindingRegistrar.java | 12 +-- .../properties/DefaultDubboConfigBinder.java | 4 +- .../spring/util/PropertySourcesUtils.java | 77 ----------------- .../spring/util/PropertySourcesUtilsTest.java | 84 ------------------- 4 files changed, 8 insertions(+), 169 deletions(-) delete mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java delete mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java index 6936787cc67..354a6c33d0f 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/annotation/DubboConfigBindingRegistrar.java @@ -40,8 +40,8 @@ import java.util.Map; import java.util.Set; -import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; -import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.normalizePrefix; +import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; +import static com.alibaba.spring.util.PropertySourcesUtils.normalizePrefix; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.registerWithGeneratedName; @@ -85,7 +85,7 @@ private void registerDubboConfigBeans(String prefix, boolean multiple, BeanDefinitionRegistry registry) { - Map properties = getSubProperties(environment.getPropertySources(), prefix); + Map properties = getSubProperties(environment.getPropertySources(), prefix); if (CollectionUtils.isEmpty(properties)) { if (log.isDebugEnabled()) { @@ -157,7 +157,7 @@ public void setEnvironment(Environment environment) { } - private Set resolveMultipleBeanNames(Map properties) { + private Set resolveMultipleBeanNames(Map properties) { Set beanNames = new LinkedHashSet(); @@ -178,10 +178,10 @@ private Set resolveMultipleBeanNames(Map properties) { } - private String resolveSingleBeanName(Map properties, Class configClass, + private String resolveSingleBeanName(Map properties, Class configClass, BeanDefinitionRegistry registry) { - String beanName = properties.get("id"); + String beanName = (String) properties.get("id"); if (!StringUtils.hasText(beanName)) { BeanDefinitionBuilder builder = rootBeanDefinition(configClass); diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java index 52cc87ca4f5..129d1730ef2 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java @@ -22,7 +22,7 @@ import java.util.Map; -import static com.alibaba.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; +import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties; /** * Default {@link DubboConfigBinder} implementation based on Spring {@link DataBinder} @@ -36,7 +36,7 @@ public void bind(String prefix, C dubboConfig) { dataBinder.setIgnoreInvalidFields(isIgnoreInvalidFields()); dataBinder.setIgnoreUnknownFields(isIgnoreUnknownFields()); // Get properties under specified prefix from PropertySources - Map properties = getSubProperties(getPropertySources(), prefix); + Map properties = getSubProperties(getPropertySources(), prefix); // Convert Map to MutablePropertyValues MutablePropertyValues propertyValues = new MutablePropertyValues(properties); // Bind diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java deleted file mode 100644 index a84e18ac819..00000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.util; - -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.core.env.PropertySources; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - -/** - * {@link PropertySources} Utilities - * - * @see PropertySources - * @since 2.5.8 - */ -public abstract class PropertySourcesUtils { - - /** - * Get Sub {@link Properties} - * - * @param propertySources {@link PropertySource} Iterable - * @param prefix the prefix of property name - * @return Map - * @see Properties - */ - public static Map getSubProperties(Iterable> propertySources, String prefix) { - - Map subProperties = new LinkedHashMap(); - - String normalizedPrefix = normalizePrefix(prefix); - - for (PropertySource source : propertySources) { - if (source instanceof EnumerablePropertySource) { - for (String name : ((EnumerablePropertySource) source).getPropertyNames()) { - if (name.startsWith(normalizedPrefix)) { - String subName = name.substring(normalizedPrefix.length()); - if (!subProperties.containsKey(subName)) { - Object value = source.getProperty(name); - subProperties.put(subName, String.valueOf(value)); - } - } - } - } - } - - return subProperties; - - } - - /** - * Normalize the prefix - * - * @param prefix the prefix - * @return the prefix - */ - public static String normalizePrefix(String prefix) { - return prefix.endsWith(".") ? prefix : prefix + "."; - } - -} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java deleted file mode 100644 index dddb6583a0b..00000000000 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/util/PropertySourcesUtilsTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.util; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.MutablePropertySources; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * {@link PropertySourcesUtils} Test - * - * @see PropertySourcesUtils - * @since 2.5.8 - */ -public class PropertySourcesUtilsTest { - - @Test - public void testGetSubProperties() { - - MutablePropertySources propertySources = new MutablePropertySources(); - - Map source = new HashMap(); - - MapPropertySource propertySource = new MapPropertySource("test", source); - - propertySources.addFirst(propertySource); - - String KEY_PREFIX = "user"; - String KEY_NAME = "name"; - String KEY_AGE = "age"; - Map result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX); - - Assert.assertEquals(Collections.emptyMap(), result); - - source.put(KEY_PREFIX + "." + KEY_NAME, "Mercy"); - source.put(KEY_PREFIX + "." + KEY_AGE, 31); - - Map expected = new HashMap(); - expected.put(KEY_NAME, "mercyblitz"); - expected.put(KEY_AGE, "31"); - - - Map source2 = new HashMap(); - - source2.put("user.name", "mercyblitz"); - - MapPropertySource propertySource2 = new MapPropertySource("test2", source2); - - propertySources.addFirst(propertySource2); - - - result = PropertySourcesUtils.getSubProperties(propertySources, KEY_PREFIX); - Assert.assertEquals(expected, result); - - result = PropertySourcesUtils.getSubProperties(propertySources, ""); - - Assert.assertEquals(Collections.emptyMap(), result); - - result = PropertySourcesUtils.getSubProperties(propertySources, "no-exists"); - - Assert.assertEquals(Collections.emptyMap(), result); - - } - -} From cba31b927220b98c3b44c58f066c209818b3a9cb Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Wed, 15 Aug 2018 08:57:54 +0800 Subject: [PATCH 17/18] Polish apache/incubator-dubbo#2301 --- .../annotation/ReferenceBeanBuilder.java | 46 ++++--- .../converter/StringArrayToMapConverter.java | 38 ------ .../StringArrayToStringConverter.java | 37 ------ .../annotation/ReferenceBeanBuilderTest.java | 124 ++++++++++++++++++ .../StringArrayToMapConverterTest.java | 52 -------- .../StringArrayToStringConverterTest.java | 46 ------- 6 files changed, 154 insertions(+), 189 deletions(-) delete mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java delete mode 100644 dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java delete mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java delete mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java index 5d9418fbc8a..883a56a1879 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilder.java @@ -16,21 +16,23 @@ */ package com.alibaba.dubbo.config.spring.beans.factory.annotation; +import com.alibaba.dubbo.common.utils.CollectionUtils; import com.alibaba.dubbo.config.ConsumerConfig; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.dubbo.config.spring.ReferenceBean; -import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToMapConverter; -import com.alibaba.dubbo.config.spring.convert.converter.StringArrayToStringConverter; +import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.context.ApplicationContext; -import org.springframework.core.convert.ConversionService; -import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.validation.DataBinder; +import java.beans.PropertyEditorSupport; +import java.util.Map; + import static com.alibaba.dubbo.config.spring.util.BeanFactoryUtils.getOptionalBean; import static com.alibaba.dubbo.config.spring.util.ObjectUtils.of; +import static org.springframework.util.StringUtils.commaDelimitedListToStringArray; /** * {@link ReferenceBean} Builder @@ -39,6 +41,8 @@ */ class ReferenceBeanBuilder extends AbstractAnnotationConfigBeanBuilder { + // Ignore those fields + static final String[] IGNORE_FIELD_NAMES = of("application", "module", "consumer", "monitor", "registry"); private ReferenceBeanBuilder(Reference annotation, ClassLoader classLoader, ApplicationContext applicationContext) { super(annotation, classLoader, applicationContext); @@ -93,20 +97,30 @@ protected ReferenceBean doBuild() { protected void preConfigureBean(Reference reference, ReferenceBean referenceBean) { Assert.notNull(interfaceClass, "The interface class must set first!"); DataBinder dataBinder = new DataBinder(referenceBean); - // Set ConversionService - dataBinder.setConversionService(getConversionService()); - // Ignore those fields - String[] ignoreAttributeNames = of("application", "module", "consumer", "monitor", "registry"); -// dataBinder.setDisallowedFields(ignoreAttributeNames); + // Register CustomEditors for special fields + dataBinder.registerCustomEditor(String.class, "filter", new StringTrimmerEditor(true)); + dataBinder.registerCustomEditor(String.class, "listener", new StringTrimmerEditor(true)); + dataBinder.registerCustomEditor(Map.class, "parameters", new PropertyEditorSupport() { + + public void setAsText(String text) throws java.lang.IllegalArgumentException { + // Trim all whitespace + String content = StringUtils.trimAllWhitespace(text); + if (!StringUtils.hasText(content)) { // No content , ignore directly + return; + } + // replace "=" to "," + content = StringUtils.replace(content, "=", ","); + // replace ":" to "," + content = StringUtils.replace(content, ":", ","); + // String[] to Map + Map parameters = CollectionUtils.toStringMap(commaDelimitedListToStringArray(content)); + setValue(parameters); + } + }); + // Bind annotation attributes - dataBinder.bind(new AnnotationPropertyValuesAdapter(reference, applicationContext.getEnvironment(), ignoreAttributeNames)); - } + dataBinder.bind(new AnnotationPropertyValuesAdapter(reference, applicationContext.getEnvironment(), IGNORE_FIELD_NAMES)); - private ConversionService getConversionService() { - DefaultConversionService conversionService = new DefaultConversionService(); - conversionService.addConverter(new StringArrayToStringConverter()); - conversionService.addConverter(new StringArrayToMapConverter()); - return conversionService; } diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java deleted file mode 100644 index 56c6d4c4ccd..00000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.convert.converter; - -import com.alibaba.dubbo.common.utils.CollectionUtils; -import org.springframework.core.convert.converter.Converter; -import org.springframework.util.ObjectUtils; - -import java.util.Map; - -/** - * {@link String}[] to {@link Map} {@link Converter} - * - * @see CollectionUtils#toStringMap(String[]) - * @since 2.5.11 - */ -public class StringArrayToMapConverter implements Converter> { - - @Override - public Map convert(String[] source) { - return ObjectUtils.isEmpty(source) ? null : CollectionUtils.toStringMap(source); - } - -} diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java deleted file mode 100644 index 23e948b0644..00000000000 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.convert.converter; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; - - -/** - * String[] to String {@ConditionalGenericConverter} - * - * @see StringUtils#arrayToCommaDelimitedString(Object[]) - * @since 2.5.11 - */ -public class StringArrayToStringConverter implements Converter { - - @Override - public String convert(String[] source) { - return ObjectUtils.isEmpty(source) ? null : StringUtils.arrayToCommaDelimitedString(source); - } - -} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java new file mode 100644 index 00000000000..54b1b9741ea --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/beans/factory/annotation/ReferenceBeanBuilderTest.java @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.beans.factory.annotation; + +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.config.spring.ReferenceBean; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; +import static org.springframework.util.ReflectionUtils.findField; + +/** + * {@link ReferenceBeanBuilder} Test + * + * @author Mercy + * @see ReferenceBeanBuilder + * @see Reference + * @since 2.6.4 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ReferenceBeanBuilderTest.class) +public class ReferenceBeanBuilderTest { + + @Reference( + interfaceClass = CharSequence.class, + interfaceName = "java.lang.CharSequence", + version = "1.0.0", group = "TEST_GROUP", url = "dubbo://localhost:12345", + client = "client", generic = true, injvm = true, + check = false, init = false, lazy = true, + stubevent = true, reconnect = "reconnect", sticky = true, + proxy = "javassist", stub = "java.lang.CharSequence", cluster = "failover", + connections = 3, callbacks = 1, onconnect = "onconnect", ondisconnect = "ondisconnect", + owner = "owner", layer = "layer", retries = 1, + loadbalance = "random", async = true, actives = 3, + sent = true, mock = "mock", validation = "validation", + timeout = 3, cache = "cache", filter = {"echo", "generic", "accesslog"}, + listener = {"deprecated"}, parameters = {"n1=v1 ", "n2 = v2 ", " n3 = v3 "}, + application = "application", + module = "module", consumer = "consumer", monitor = "monitor", registry = {"registry"} + ) + private static final Object TEST_FIELD = new Object(); + + @Autowired + private ApplicationContext context; + + @Test + public void testBuild() throws Exception { + Reference reference = findAnnotation(findField(getClass(), "TEST_FIELD"), Reference.class); + ReferenceBeanBuilder beanBuilder = ReferenceBeanBuilder.create(reference, context.getClassLoader(), context); + beanBuilder.interfaceClass(CharSequence.class); + ReferenceBean referenceBean = beanBuilder.build(); + Assert.assertEquals(CharSequence.class, referenceBean.getInterfaceClass()); + Assert.assertEquals("1.0.0", referenceBean.getVersion()); + Assert.assertEquals("TEST_GROUP", referenceBean.getGroup()); + Assert.assertEquals("dubbo://localhost:12345", referenceBean.getUrl()); + Assert.assertEquals("client", referenceBean.getClient()); + Assert.assertEquals(true, referenceBean.isGeneric()); + Assert.assertEquals(true, referenceBean.isInjvm()); + Assert.assertEquals(false, referenceBean.isCheck()); + Assert.assertEquals(null, referenceBean.isInit()); + Assert.assertEquals(true, referenceBean.getLazy()); + Assert.assertEquals(true, referenceBean.getStubevent()); + Assert.assertEquals("reconnect", referenceBean.getReconnect()); + Assert.assertEquals(true, referenceBean.getSticky()); + Assert.assertEquals("javassist", referenceBean.getProxy()); + Assert.assertEquals("java.lang.CharSequence", referenceBean.getStub()); + Assert.assertEquals("failover", referenceBean.getCluster()); + Assert.assertEquals(Integer.valueOf(3), referenceBean.getConnections()); + Assert.assertEquals(Integer.valueOf(1), referenceBean.getCallbacks()); + Assert.assertEquals("onconnect", referenceBean.getOnconnect()); + Assert.assertEquals("ondisconnect", referenceBean.getOndisconnect()); + Assert.assertEquals("owner", referenceBean.getOwner()); + Assert.assertEquals("layer", referenceBean.getLayer()); + Assert.assertEquals(Integer.valueOf(1), referenceBean.getRetries()); + Assert.assertEquals("random", referenceBean.getLoadbalance()); + Assert.assertEquals(true, referenceBean.isAsync()); + Assert.assertEquals(Integer.valueOf(3), referenceBean.getActives()); + Assert.assertEquals(true, referenceBean.getSent()); + Assert.assertEquals("mock", referenceBean.getMock()); + Assert.assertEquals("validation", referenceBean.getValidation()); + Assert.assertEquals(Integer.valueOf(3), referenceBean.getTimeout()); + Assert.assertEquals("cache", referenceBean.getCache()); + Assert.assertEquals("echo,generic,accesslog", referenceBean.getFilter()); + Assert.assertEquals("deprecated", referenceBean.getListener()); + + // parameters + Map parameters = new HashMap(); + parameters.put("n1", "v1"); + parameters.put("n2", "v2"); + parameters.put("n3", "v3"); + Assert.assertEquals(parameters, referenceBean.getParameters()); + + // Asserts Null fields + Assert.assertNull(referenceBean.getApplication()); + Assert.assertNull(referenceBean.getModule()); + Assert.assertNull(referenceBean.getConsumer()); + Assert.assertNull(referenceBean.getMonitor()); + Assert.assertEquals(Collections.emptyList(), referenceBean.getRegistries()); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java deleted file mode 100644 index 51be7c3f2f2..00000000000 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToMapConverterTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.convert.converter; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * {@link StringArrayToMapConverter} Test - */ -public class StringArrayToMapConverterTest { - - @Test - public void testConvert() { - - StringArrayToMapConverter converter = new StringArrayToMapConverter(); - - Map value = converter.convert(new String[]{"Hello", "World"}); - - Map expected = new LinkedHashMap(); - - expected.put("Hello", "World"); - - Assert.assertEquals(expected, value); - - value = converter.convert(new String[]{}); - - Assert.assertNull(value); - - value = converter.convert(null); - - Assert.assertNull(value); - - } -} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java deleted file mode 100644 index 67e82479235..00000000000 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/convert/converter/StringArrayToStringConverterTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.config.spring.convert.converter; - -import org.junit.Assert; -import org.junit.Test; - -/** - * {@link StringArrayToStringConverter} Test - */ -public class StringArrayToStringConverterTest { - - @Test - public void testConvert() { - - StringArrayToStringConverter converter = new StringArrayToStringConverter(); - - String value = converter.convert(new String[]{"Hello", "World"}); - - Assert.assertEquals("Hello,World", value); - - value = converter.convert(new String[]{}); - - Assert.assertNull(value); - - value = converter.convert(null); - - Assert.assertNull(value); - - } - -} From 9d7fe246f7d2e2017dd48c13cfd74ba51e407145 Mon Sep 17 00:00:00 2001 From: mercyblitz Date: Fri, 17 Aug 2018 16:57:55 +0800 Subject: [PATCH 18/18] Polish apache/incubator-dubbo#2315 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 69aa46ede32..43a160c9b80 100644 --- a/pom.xml +++ b/pom.xml @@ -115,7 +115,7 @@ 2.8.2 3.6.0 3.0.1 - 3.0.0 + 3.0.1 6.1.26 3.0.0 0.8.1