repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceCreator.java | /*
* 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 org.apache.dubbo.config.spring.reference;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.spring.beans.factory.annotation.AnnotationPropertyValuesAdapter;
import org.apache.dubbo.config.spring.util.AnnotationUtils;
import org.apache.dubbo.config.spring.util.DubboAnnotationUtils;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.spring.util.ObjectUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.DataBinder;
/**
* {@link ReferenceConfig} Creator for @{@link DubboReference}
*
* @since 3.0
*/
public class ReferenceCreator {
// Ignore those fields
static final String[] IGNORE_FIELD_NAMES =
ObjectUtils.of("application", "module", "consumer", "monitor", "registry", "interfaceClass");
private static final String ONRETURN = "onreturn";
private static final String ONTHROW = "onthrow";
private static final String ONINVOKE = "oninvoke";
private static final String ISRETURN = "isReturn";
private static final String METHOD = "Method";
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final Map<String, Object> attributes;
protected final ApplicationContext applicationContext;
protected final ClassLoader classLoader;
protected Class<?> defaultInterfaceClass;
private final ModuleModel moduleModel;
private ReferenceCreator(Map<String, Object> attributes, ApplicationContext applicationContext) {
Assert.notNull(attributes, "The Annotation attributes must not be null!");
Assert.notNull(applicationContext, "The ApplicationContext must not be null!");
this.attributes = attributes;
this.applicationContext = applicationContext;
this.classLoader = applicationContext.getClassLoader() != null
? applicationContext.getClassLoader()
: Thread.currentThread().getContextClassLoader();
moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
Assert.notNull(moduleModel, "ModuleModel not found in Spring ApplicationContext");
}
public final ReferenceConfig build() throws Exception {
ReferenceConfig configBean = new ReferenceConfig();
configureBean(configBean);
if (logger.isInfoEnabled()) {
logger.info("The configBean[type:" + configBean.getClass().getSimpleName() + "<"
+ defaultInterfaceClass.getTypeName() + ">" + "] has been built.");
}
return configBean;
}
protected void configureBean(ReferenceConfig referenceConfig) throws Exception {
populateBean(referenceConfig);
configureMonitorConfig(referenceConfig);
configureModuleConfig(referenceConfig);
configureConsumerConfig(referenceConfig);
}
private void configureMonitorConfig(ReferenceConfig configBean) {
String monitorConfigId = AnnotationUtils.getAttribute(attributes, "monitor");
if (StringUtils.hasText(monitorConfigId)) {
MonitorConfig monitorConfig = getConfig(monitorConfigId, MonitorConfig.class);
configBean.setMonitor(monitorConfig);
}
}
private void configureModuleConfig(ReferenceConfig configBean) {
String moduleConfigId = AnnotationUtils.getAttribute(attributes, "module");
if (StringUtils.hasText(moduleConfigId)) {
ModuleConfig moduleConfig = getConfig(moduleConfigId, ModuleConfig.class);
configBean.setModule(moduleConfig);
}
}
private void configureConsumerConfig(ReferenceConfig<?> referenceBean) {
ConsumerConfig consumerConfig = null;
Object consumer = AnnotationUtils.getAttribute(attributes, "consumer");
if (consumer != null) {
if (consumer instanceof String) {
consumerConfig = getConfig((String) consumer, ConsumerConfig.class);
} else if (consumer instanceof ConsumerConfig) {
consumerConfig = (ConsumerConfig) consumer;
} else {
throw new IllegalArgumentException("Unexpected 'consumer' attribute value: " + consumer);
}
referenceBean.setConsumer(consumerConfig);
}
}
private <T extends AbstractConfig> T getConfig(String configIdOrName, Class<T> configType) {
// 1. find in ModuleConfigManager
T config = moduleModel
.getConfigManager()
.getConfig(configType, configIdOrName)
.orElse(null);
if (config == null) {
// 2. find in Spring ApplicationContext
if (applicationContext.containsBean(configIdOrName)) {
config = applicationContext.getBean(configIdOrName, configType);
}
}
if (config == null) {
throw new IllegalArgumentException(configType.getSimpleName() + " not found: " + configIdOrName);
}
return config;
}
protected void populateBean(ReferenceConfig referenceConfig) {
Assert.notNull(defaultInterfaceClass, "The default interface class cannot be empty!");
// convert attributes, e.g. interface, registry
ReferenceBeanSupport.convertReferenceProps(attributes, defaultInterfaceClass);
DataBinder dataBinder = new DataBinder(referenceConfig);
// Register CustomEditors for special fields
dataBinder.registerCustomEditor(String.class, "filter", new StringTrimmerEditor(true));
dataBinder.registerCustomEditor(String.class, "listener", new StringTrimmerEditor(true));
DefaultConversionService conversionService = new DefaultConversionService();
// convert String[] to Map (such as @Method.parameters())
conversionService.addConverter(String[].class, Map.class, DubboAnnotationUtils::convertParameters);
// convert Map to MethodConfig
conversionService.addConverter(
Map.class, MethodConfig.class, source -> createMethodConfig(source, conversionService));
// convert @Method to MethodConfig
conversionService.addConverter(Method.class, MethodConfig.class, source -> {
Map<String, Object> methodAttributes = AnnotationUtils.getAnnotationAttributes(source, true);
return createMethodConfig(methodAttributes, conversionService);
});
// convert Map to ArgumentConfig
conversionService.addConverter(Map.class, ArgumentConfig.class, source -> {
ArgumentConfig argumentConfig = new ArgumentConfig();
DataBinder argDataBinder = new DataBinder(argumentConfig);
argDataBinder.setConversionService(conversionService);
argDataBinder.bind(new AnnotationPropertyValuesAdapter(source, applicationContext.getEnvironment()));
return argumentConfig;
});
// convert @Argument to ArgumentConfig
conversionService.addConverter(Argument.class, ArgumentConfig.class, source -> {
ArgumentConfig argumentConfig = new ArgumentConfig();
DataBinder argDataBinder = new DataBinder(argumentConfig);
argDataBinder.setConversionService(conversionService);
argDataBinder.bind(new AnnotationPropertyValuesAdapter(source, applicationContext.getEnvironment()));
return argumentConfig;
});
// Bind annotation attributes
dataBinder.setConversionService(conversionService);
dataBinder.bind(new AnnotationPropertyValuesAdapter(
attributes, applicationContext.getEnvironment(), IGNORE_FIELD_NAMES));
}
private MethodConfig createMethodConfig(
Map<String, Object> methodAttributes, DefaultConversionService conversionService) {
String[] callbacks = new String[] {ONINVOKE, ONRETURN, ONTHROW};
for (String callbackName : callbacks) {
Object value = methodAttributes.get(callbackName);
if (value instanceof String) {
// parse callback: beanName.methodName
String strValue = (String) value;
int index = strValue.lastIndexOf(".");
if (index != -1) {
String beanName = strValue.substring(0, index);
String methodName = strValue.substring(index + 1);
methodAttributes.put(callbackName, applicationContext.getBean(beanName));
methodAttributes.put(callbackName + METHOD, methodName);
} else {
methodAttributes.put(callbackName, applicationContext.getBean(strValue));
}
}
}
MethodConfig methodConfig = new MethodConfig();
DataBinder mcDataBinder = new DataBinder(methodConfig);
methodConfig.setReturn((Boolean) methodAttributes.get(ISRETURN));
mcDataBinder.setConversionService(conversionService);
AnnotationPropertyValuesAdapter propertyValues =
new AnnotationPropertyValuesAdapter(methodAttributes, applicationContext.getEnvironment());
mcDataBinder.bind(propertyValues);
return methodConfig;
}
public static ReferenceCreator create(Map<String, Object> attributes, ApplicationContext applicationContext) {
return new ReferenceCreator(attributes, applicationContext);
}
public ReferenceCreator defaultInterfaceClass(Class<?> interfaceClass) {
this.defaultInterfaceClass = interfaceClass;
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanBuilder.java | /*
* 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 org.apache.dubbo.config.spring.reference;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.ReferenceBean;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* Builder for ReferenceBean, used to return ReferenceBean instance in Java-config @Bean method,
* equivalent to {@link DubboReference} annotation.
* </p>
*
* <p>
* <b>It is recommended to use {@link DubboReference} on the @Bean method in the Java-config class.</b>
* </p>
*
* Step 1: Register ReferenceBean in Java-config class:
* <pre class="code">
* @Configuration
* public class ReferenceConfiguration {
*
* @Bean
* public ReferenceBean<HelloService> helloService() {
* return new ReferenceBeanBuilder()
* .setGroup("demo")
* .build();
* }
*
* @Bean
* public ReferenceBean<HelloService> helloService2() {
* return new ReferenceBean();
* }
*
* @Bean
* public ReferenceBean<GenericService> genericHelloService() {
* return new ReferenceBeanBuilder()
* .setGroup("demo")
* .setInterface(HelloService.class)
* .build();
* }
*
* }
* </pre>
*
* Step 2: Inject ReferenceBean by @Autowired
* <pre class="code">
* public class FooController {
* @Autowired
* private HelloService helloService;
*
* @Autowired
* private GenericService genericHelloService;
* }
* </pre>
*
* @see org.apache.dubbo.config.annotation.DubboReference
* @see org.apache.dubbo.config.spring.ReferenceBean
*/
public class ReferenceBeanBuilder {
private Map<String, Object> attributes = new HashMap<>();
public <T> ReferenceBean<T> build() {
return new ReferenceBean(attributes);
}
public ReferenceBeanBuilder setServices(String services) {
attributes.put(ReferenceAttributes.SERVICES, services);
return this;
}
public ReferenceBeanBuilder setInterface(String interfaceName) {
attributes.put(ReferenceAttributes.INTERFACE_NAME, interfaceName);
return this;
}
public ReferenceBeanBuilder setInterface(Class interfaceClass) {
attributes.put(ReferenceAttributes.INTERFACE_CLASS, interfaceClass);
return this;
}
public ReferenceBeanBuilder setClient(String client) {
attributes.put(ReferenceAttributes.CLIENT, client);
return this;
}
public ReferenceBeanBuilder setUrl(String url) {
attributes.put(ReferenceAttributes.URL, url);
return this;
}
public ReferenceBeanBuilder setConsumer(ConsumerConfig consumer) {
attributes.put(ReferenceAttributes.CONSUMER, consumer);
return this;
}
public ReferenceBeanBuilder setConsumer(String consumer) {
attributes.put(ReferenceAttributes.CONSUMER, consumer);
return this;
}
public ReferenceBeanBuilder setProtocol(String protocol) {
attributes.put(ReferenceAttributes.PROTOCOL, protocol);
return this;
}
public ReferenceBeanBuilder setCheck(Boolean check) {
attributes.put(ReferenceAttributes.CHECK, check);
return this;
}
public ReferenceBeanBuilder setInit(Boolean init) {
attributes.put(ReferenceAttributes.INIT, init);
return this;
}
// @Deprecated
public ReferenceBeanBuilder setGeneric(Boolean generic) {
attributes.put(ReferenceAttributes.GENERIC, generic);
return this;
}
/**
* @param injvm
* @deprecated instead, use the parameter <b>scope</b> to judge if it's in jvm, scope=local
*/
@Deprecated
public ReferenceBeanBuilder setInjvm(Boolean injvm) {
attributes.put(ReferenceAttributes.INJVM, injvm);
return this;
}
public ReferenceBeanBuilder setListener(String listener) {
attributes.put(ReferenceAttributes.LISTENER, listener);
return this;
}
public ReferenceBeanBuilder setLazy(Boolean lazy) {
attributes.put(ReferenceAttributes.LAZY, lazy);
return this;
}
public ReferenceBeanBuilder setOnconnect(String onconnect) {
attributes.put(ReferenceAttributes.ONCONNECT, onconnect);
return this;
}
public ReferenceBeanBuilder setOndisconnect(String ondisconnect) {
attributes.put(ReferenceAttributes.ONDISCONNECT, ondisconnect);
return this;
}
public ReferenceBeanBuilder setReconnect(String reconnect) {
attributes.put(ReferenceAttributes.RECONNECT, reconnect);
return this;
}
public ReferenceBeanBuilder setSticky(Boolean sticky) {
attributes.put(ReferenceAttributes.STICKY, sticky);
return this;
}
public ReferenceBeanBuilder setVersion(String version) {
attributes.put(ReferenceAttributes.VERSION, version);
return this;
}
public ReferenceBeanBuilder setGroup(String group) {
attributes.put(ReferenceAttributes.GROUP, group);
return this;
}
public ReferenceBeanBuilder setProvidedBy(String providedBy) {
attributes.put(ReferenceAttributes.PROVIDED_BY, providedBy);
return this;
}
public ReferenceBeanBuilder setProviderPort(Integer providerPort) {
attributes.put(ReferenceAttributes.PROVIDER_PORT, providerPort);
return this;
}
// public ReferenceBeanBuilder setRouter(String router) {
// attributes.put(ReferenceAttributes.ROUTER, router);
// return this;
// }
public ReferenceBeanBuilder setStub(String stub) {
attributes.put(ReferenceAttributes.STUB, stub);
return this;
}
public ReferenceBeanBuilder setCluster(String cluster) {
attributes.put(ReferenceAttributes.CLUSTER, cluster);
return this;
}
public ReferenceBeanBuilder setProxy(String proxy) {
attributes.put(ReferenceAttributes.PROXY, proxy);
return this;
}
public ReferenceBeanBuilder setConnections(Integer connections) {
attributes.put(ReferenceAttributes.CONNECTIONS, connections);
return this;
}
public ReferenceBeanBuilder setFilter(String filter) {
attributes.put(ReferenceAttributes.FILTER, filter);
return this;
}
public ReferenceBeanBuilder setLayer(String layer) {
attributes.put(ReferenceAttributes.LAYER, layer);
return this;
}
// @Deprecated
// public ReferenceBeanBuilder setApplication(ApplicationConfig application) {
// attributes.put(ReferenceAttributes.APPLICATION, application);
// return this;
// }
// @Deprecated
// public ReferenceBeanBuilder setModule(ModuleConfig module) {
// attributes.put(ReferenceAttributes.MODULE, module);
// return this;
// }
public ReferenceBeanBuilder setRegistry(String[] registryIds) {
attributes.put(ReferenceAttributes.REGISTRY, registryIds);
return this;
}
public ReferenceBeanBuilder setRegistry(RegistryConfig registry) {
setRegistries(Arrays.asList(registry));
return this;
}
public ReferenceBeanBuilder setRegistries(List<? extends RegistryConfig> registries) {
attributes.put(ReferenceAttributes.REGISTRIES, registries);
return this;
}
public ReferenceBeanBuilder setMethods(List<? extends MethodConfig> methods) {
attributes.put(ReferenceAttributes.METHODS, methods);
return this;
}
@Deprecated
public ReferenceBeanBuilder setMonitor(MonitorConfig monitor) {
attributes.put(ReferenceAttributes.MONITOR, monitor);
return this;
}
@Deprecated
public ReferenceBeanBuilder setMonitor(String monitor) {
attributes.put(ReferenceAttributes.MONITOR, monitor);
return this;
}
public ReferenceBeanBuilder setOwner(String owner) {
attributes.put(ReferenceAttributes.OWNER, owner);
return this;
}
public ReferenceBeanBuilder setCallbacks(Integer callbacks) {
attributes.put(ReferenceAttributes.CALLBACKS, callbacks);
return this;
}
public ReferenceBeanBuilder setScope(String scope) {
attributes.put(ReferenceAttributes.SCOPE, scope);
return this;
}
public ReferenceBeanBuilder setTag(String tag) {
attributes.put(ReferenceAttributes.TAG, tag);
return this;
}
public ReferenceBeanBuilder setTimeout(Integer timeout) {
attributes.put(ReferenceAttributes.TIMEOUT, timeout);
return this;
}
public ReferenceBeanBuilder setRetries(Integer retries) {
attributes.put(ReferenceAttributes.RETRIES, retries);
return this;
}
public ReferenceBeanBuilder setLoadBalance(String loadbalance) {
attributes.put(ReferenceAttributes.LOAD_BALANCE, loadbalance);
return this;
}
public ReferenceBeanBuilder setAsync(Boolean async) {
attributes.put(ReferenceAttributes.ASYNC, async);
return this;
}
public ReferenceBeanBuilder setActives(Integer actives) {
attributes.put(ReferenceAttributes.ACTIVES, actives);
return this;
}
public ReferenceBeanBuilder setSent(Boolean sent) {
attributes.put(ReferenceAttributes.SENT, sent);
return this;
}
public ReferenceBeanBuilder setMock(String mock) {
attributes.put(ReferenceAttributes.MOCK, mock);
return this;
}
public ReferenceBeanBuilder setMerger(String merger) {
attributes.put(ReferenceAttributes.MERGER, merger);
return this;
}
public ReferenceBeanBuilder setCache(String cache) {
attributes.put(ReferenceAttributes.CACHE, cache);
return this;
}
public ReferenceBeanBuilder setValidation(String validation) {
attributes.put(ReferenceAttributes.VALIDATION, validation);
return this;
}
public ReferenceBeanBuilder setParameters(Map<String, String> parameters) {
attributes.put(ReferenceAttributes.PARAMETERS, parameters);
return this;
}
// public ReferenceBeanBuilder setAuth(Boolean auth) {
// attributes.put(ReferenceAttributes.AUTH, auth);
// return this;
// }
//
// public ReferenceBeanBuilder setForks(Integer forks) {
// attributes.put(ReferenceAttributes.FORKS, forks);
// return this;
// }
//
// @Deprecated
// public ReferenceBeanBuilder setConfigCenter(ConfigCenterConfig configCenter) {
// attributes.put(ReferenceAttributes.CONFIG_CENTER, configCenter);
// return this;
// }
//
// @Deprecated
// public ReferenceBeanBuilder setMetadataReportConfig(MetadataReportConfig metadataReportConfig) {
// attributes.put(ReferenceAttributes.METADATA_REPORT_CONFIG, metadataReportConfig);
// return this;
// }
//
// @Deprecated
// public ReferenceBeanBuilder setMetrics(MetricsConfig metrics) {
// attributes.put(ReferenceAttributes.METRICS, metrics);
// return this;
// }
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/aot/AotWithSpringDetector.java | /*
* 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 org.apache.dubbo.config.spring.aot;
import org.apache.dubbo.common.aot.NativeDetector;
import org.springframework.core.SpringProperties;
public abstract class AotWithSpringDetector {
/**
* System property that indicates the application should run with AOT
* generated artifacts. If such optimizations are not available, it is
* recommended to throw an exception rather than fall back to the regular
* runtime behavior.
*/
public static final String AOT_ENABLED = "spring.aot.enabled";
private static final String AOT_PROCESSING = "spring.aot.processing";
/**
* Determine whether AOT optimizations must be considered at runtime. This
* is mandatory in a native image but can be triggered on the JVM using
* the {@value #AOT_ENABLED} Spring property.
*
* @return whether AOT optimizations must be considered
*/
public static boolean useGeneratedArtifacts() {
return (NativeDetector.inNativeImage() || SpringProperties.getFlag(AOT_ENABLED));
}
public static boolean isAotProcessing() {
return (NativeDetector.inNativeImage() || SpringProperties.getFlag(AOT_PROCESSING));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.java | /*
* 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 org.apache.dubbo.config.spring.status;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Method;
import org.springframework.context.ApplicationContext;
import org.springframework.context.Lifecycle;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER;
@Activate
public class SpringStatusChecker implements StatusChecker {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SpringStatusChecker.class);
private ApplicationModel applicationModel;
private ApplicationContext applicationContext;
public SpringStatusChecker(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public SpringStatusChecker(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Status check() {
if (applicationContext == null && applicationModel != null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
return new Status(Status.Level.UNKNOWN);
}
Status.Level level;
if (applicationContext instanceof Lifecycle) {
if (((Lifecycle) applicationContext).isRunning()) {
level = Status.Level.OK;
} else {
level = Status.Level.ERROR;
}
} else {
level = Status.Level.UNKNOWN;
}
StringBuilder buf = new StringBuilder();
try {
Class<?> cls = applicationContext.getClass();
Method method = null;
while (cls != null && method == null) {
try {
method = cls.getDeclaredMethod("getConfigLocations", new Class<?>[0]);
} catch (NoSuchMethodException t) {
cls = cls.getSuperclass();
}
}
if (method != null) {
if (!method.isAccessible()) {
method.setAccessible(true);
}
String[] configs = (String[]) method.invoke(applicationContext, new Object[0]);
if (configs != null && configs.length > 0) {
for (String config : configs) {
if (buf.length() > 0) {
buf.append(',');
}
buf.append(config);
}
}
}
} catch (Throwable t) {
if (t.getCause() instanceof UnsupportedOperationException) {
logger.debug(t.getMessage(), t);
} else {
logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", t.getMessage(), t);
}
}
return new Status(level, buf.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.java | /*
* 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 org.apache.dubbo.config.spring.status;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER;
@Activate
public class DataSourceStatusChecker implements StatusChecker {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DataSourceStatusChecker.class);
private ApplicationModel applicationModel;
private ApplicationContext applicationContext;
public DataSourceStatusChecker(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public DataSourceStatusChecker(ApplicationContext context) {
this.applicationContext = context;
}
@Override
public Status check() {
if (applicationContext == null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
return new Status(Status.Level.UNKNOWN);
}
Map<String, DataSource> dataSources = applicationContext.getBeansOfType(DataSource.class, false, false);
if (CollectionUtils.isEmptyMap(dataSources)) {
return new Status(Status.Level.UNKNOWN);
}
Status.Level level = Status.Level.OK;
StringBuilder buf = new StringBuilder();
for (Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
DataSource dataSource = entry.getValue();
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(entry.getKey());
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet resultSet = metaData.getTypeInfo()) {
if (!resultSet.next()) {
level = Status.Level.ERROR;
}
}
buf.append(metaData.getURL());
buf.append('(');
buf.append(metaData.getDatabaseProductName());
buf.append('-');
buf.append(metaData.getDatabaseProductVersion());
buf.append(')');
} catch (Throwable e) {
logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", e.getMessage(), e);
return new Status(level, e.getMessage());
}
}
return new Status(level, buf.toString());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.java | /*
* 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 org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.config.spring.util.SpringCompatUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import static org.springframework.util.StringUtils.commaDelimitedListToStringArray;
import static org.springframework.util.StringUtils.trimArrayElements;
/**
* @link BeanDefinitionParser}
* @see ServiceAnnotationPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.5.9
*/
public class AnnotationBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
/**
* parse
* <prev>
* <dubbo:annotation package="" />
* </prev>
*
* @param element
* @param parserContext
* @param builder
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String packageToScan = element.getAttribute("package");
String[] packagesToScan = trimArrayElements(commaDelimitedListToStringArray(packageToScan));
builder.addConstructorArgValue(packagesToScan);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
/**
* @since 2.7.6 Register the common beans
* @since 2.7.8 comment this code line, and migrated to
* @see DubboNamespaceHandler#parse(Element, ParserContext)
* @see https://github.com/apache/dubbo/issues/6174
*/
// registerCommonBeans(parserContext.getRegistry());
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected Class<?> getBeanClass(Element element) {
return SpringCompatUtils.serviceAnnotationPostProcessor();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboBeanDefinitionParser.java | /*
* 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 org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.MethodUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractServiceConfig;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
import org.apache.dubbo.config.spring.Constants;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.reference.ReferenceAttributes;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static org.apache.dubbo.common.constants.CommonConstants.HIDE_KEY_PREFIX;
import static org.apache.dubbo.config.spring.util.SpringCompatUtils.getPropertyValue;
/**
* AbstractBeanDefinitionParser
*
* @export
*/
public class DubboBeanDefinitionParser implements BeanDefinitionParser {
private static final Logger logger = LoggerFactory.getLogger(DubboBeanDefinitionParser.class);
private static final Pattern GROUP_AND_VERSION = Pattern.compile("^[\\-.0-9_a-zA-Z]+(\\:[\\-.0-9_a-zA-Z]+)?$");
private static final String ONRETURN = "onreturn";
private static final String ONTHROW = "onthrow";
private static final String ONINVOKE = "oninvoke";
private static final String EXECUTOR = "executor";
private static final String METHOD = "Method";
private static final String BEAN_NAME = "BEAN_NAME";
private static boolean resolvePlaceholdersEnabled = true;
private final Class<?> beanClass;
private static Map<String, Map<String, Class>> beanPropsCache = new HashMap<>();
public DubboBeanDefinitionParser(Class<?> beanClass) {
this.beanClass = beanClass;
}
@SuppressWarnings("unchecked")
private static RootBeanDefinition parse(
Element element, ParserContext parserContext, Class<?> beanClass, boolean registered) {
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(beanClass);
beanDefinition.setLazyInit(false);
if (ServiceBean.class.equals(beanClass)) {
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
}
// config id
String configId = resolveAttribute(element, "id", parserContext);
if (StringUtils.isNotEmpty(configId)) {
beanDefinition.getPropertyValues().addPropertyValue("id", configId);
}
String configName = "";
// get configName from name
if (StringUtils.isEmpty(configId)) {
configName = resolveAttribute(element, "name", parserContext);
}
String beanName = configId;
if (StringUtils.isEmpty(beanName)) {
// generate bean name
String prefix = beanClass.getName();
int counter = 0;
beanName = prefix + (StringUtils.isEmpty(configName) ? "#" : ("#" + configName + "#")) + counter;
while (parserContext.getRegistry().containsBeanDefinition(beanName)) {
beanName = prefix + (StringUtils.isEmpty(configName) ? "#" : ("#" + configName + "#")) + (counter++);
}
}
beanDefinition.setAttribute(BEAN_NAME, beanName);
if (ProtocolConfig.class.equals(beanClass)) {
// for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
// BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
// PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
// if (property != null) {
// Object value = property.getValue();
// if (value instanceof ProtocolConfig && beanName.equals(((ProtocolConfig)
// value).getName())) {
// definition.getPropertyValues().addPropertyValue("protocol", new
// RuntimeBeanReference(beanName));
// }
// }
// }
} else if (ServiceBean.class.equals(beanClass)) {
String className = resolveAttribute(element, "class", parserContext);
if (StringUtils.isNotEmpty(className)) {
RootBeanDefinition classDefinition = new RootBeanDefinition();
classDefinition.setBeanClass(ReflectUtils.forName(className));
classDefinition.setLazyInit(false);
parseProperties(element.getChildNodes(), classDefinition, parserContext);
beanDefinition
.getPropertyValues()
.addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, beanName + "Impl"));
}
}
Map<String, Class> beanPropTypeMap = beanPropsCache.get(beanClass.getName());
if (beanPropTypeMap == null) {
beanPropTypeMap = new HashMap<>();
beanPropsCache.put(beanClass.getName(), beanPropTypeMap);
if (ReferenceBean.class.equals(beanClass)) {
// extract bean props from ReferenceConfig
getPropertyMap(ReferenceConfig.class, beanPropTypeMap);
} else {
getPropertyMap(beanClass, beanPropTypeMap);
}
}
ManagedMap parameters = null;
Set<String> processedProps = new HashSet<>();
for (Map.Entry<String, Class> entry : beanPropTypeMap.entrySet()) {
String beanProperty = entry.getKey();
Class type = entry.getValue();
String property = StringUtils.camelToSplitName(beanProperty, "-");
processedProps.add(property);
if ("parameters".equals(property)) {
parameters = parseParameters(element.getChildNodes(), beanDefinition, parserContext);
} else if ("methods".equals(property)) {
parseMethods(beanName, element.getChildNodes(), beanDefinition, parserContext);
} else if ("arguments".equals(property)) {
parseArguments(beanName, element.getChildNodes(), beanDefinition, parserContext);
} else {
String value = resolveAttribute(element, property, parserContext);
if (StringUtils.isNotBlank(value)) {
value = value.trim();
if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
// see AbstractInterfaceConfig#registries, It will be invoker setRegistries method when
// BeanDefinition is registered,
beanDefinition.getPropertyValues().addPropertyValue("registries", registryConfig);
// If registry is N/A, don't init it until the reference is invoked
beanDefinition.setLazyInit(true);
} else if ("provider".equals(property)
|| "registry".equals(property)
|| ("protocol".equals(property)
&& AbstractServiceConfig.class.isAssignableFrom(beanClass))) {
/**
* For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds'
* The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases:
* 1. Spring, check existing bean by id, see{@link ServiceBean#afterPropertiesSet()}; then try to use id to find configs defined in remote Config Center
* 2. API, directly use id to find configs defined in remote Config Center; if all config instances are defined locally, please use {@link org.apache.dubbo.config.ServiceConfig#setRegistries(List)}
*/
beanDefinition.getPropertyValues().addPropertyValue(beanProperty + "Ids", value);
} else {
Object reference;
if (isPrimitive(type)) {
value = getCompatibleDefaultValue(property, value);
reference = value;
} else if (ONRETURN.equals(property) || ONTHROW.equals(property) || ONINVOKE.equals(property)) {
int index = value.lastIndexOf(".");
String ref = value.substring(0, index);
String method = value.substring(index + 1);
reference = new RuntimeBeanReference(ref);
beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method);
} else if (EXECUTOR.equals(property)) {
reference = new RuntimeBeanReference(value);
} else {
if ("ref".equals(property)
&& parserContext.getRegistry().containsBeanDefinition(value)) {
BeanDefinition refBean =
parserContext.getRegistry().getBeanDefinition(value);
if (!refBean.isSingleton()) {
throw new IllegalStateException(
"The exported service ref " + value + " must be singleton! Please set the "
+ value + " bean scope to singleton, eg: <bean id=\"" + value
+ "\" scope=\"singleton\" ...>");
}
}
reference = new RuntimeBeanReference(value);
}
if (reference != null) {
beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference);
}
}
}
}
}
NamedNodeMap attributes = element.getAttributes();
int len = attributes.getLength();
for (int i = 0; i < len; i++) {
Node node = attributes.item(i);
String name = node.getLocalName();
if (!processedProps.contains(name)) {
if (parameters == null) {
parameters = new ManagedMap();
}
String value = node.getNodeValue();
parameters.put(name, new TypedStringValue(value, String.class));
}
}
if (parameters != null) {
beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
}
// post-process after parse attributes
if (ProviderConfig.class.equals(beanClass)) {
parseNested(
element, parserContext, ServiceBean.class, true, "service", "provider", beanName, beanDefinition);
} else if (ConsumerConfig.class.equals(beanClass)) {
parseNested(
element,
parserContext,
ReferenceBean.class,
true,
"reference",
"consumer",
beanName,
beanDefinition);
} else if (ReferenceBean.class.equals(beanClass)) {
configReferenceBean(element, parserContext, beanDefinition, null);
} else if (MetricsConfig.class.equals(beanClass)) {
parseMetrics(element, parserContext, beanDefinition);
}
// register bean definition
if (parserContext.getRegistry().containsBeanDefinition(beanName)) {
throw new IllegalStateException("Duplicate spring bean name: " + beanName);
}
if (registered) {
parserContext.getRegistry().registerBeanDefinition(beanName, beanDefinition);
}
return beanDefinition;
}
private static void parseMetrics(Element element, ParserContext parserContext, RootBeanDefinition beanDefinition) {
NodeList childNodes = element.getChildNodes();
PrometheusConfig prometheus = null;
for (int i = 0; i < childNodes.getLength(); i++) {
if (!(childNodes.item(i) instanceof Element)) {
continue;
}
Element child = (Element) childNodes.item(i);
if ("aggregation".equals(child.getNodeName()) || "aggregation".equals(child.getLocalName())) {
AggregationConfig aggregation = new AggregationConfig();
assignProperties(aggregation, child, parserContext);
beanDefinition.getPropertyValues().addPropertyValue("aggregation", aggregation);
} else if ("histogram".equals(child.getNodeName()) || "histogram".equals(child.getLocalName())) {
HistogramConfig histogram = new HistogramConfig();
assignProperties(histogram, child, parserContext);
beanDefinition.getPropertyValues().addPropertyValue("histogram", histogram);
} else if ("prometheus-exporter".equals(child.getNodeName())
|| "prometheus-exporter".equals(child.getLocalName())) {
if (prometheus == null) {
prometheus = new PrometheusConfig();
}
PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter();
assignProperties(exporter, child, parserContext);
prometheus.setExporter(exporter);
} else if ("prometheus-pushgateway".equals(child.getNodeName())
|| "prometheus-pushgateway".equals(child.getLocalName())) {
if (prometheus == null) {
prometheus = new PrometheusConfig();
}
PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway();
assignProperties(pushgateway, child, parserContext);
prometheus.setPushgateway(pushgateway);
}
}
if (prometheus != null) {
beanDefinition.getPropertyValues().addPropertyValue("prometheus", prometheus);
}
}
private static void assignProperties(Object obj, Element ele, ParserContext parserContext) {
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
if (MethodUtils.isSetter(method)) {
String beanProperty = method.getName().substring(3, 4).toLowerCase()
+ method.getName().substring(4);
String property = StringUtils.camelToSplitName(beanProperty, "-");
String value = resolveAttribute(ele, property, parserContext);
if (StringUtils.isNotEmpty(value)) {
try {
Object v = ClassUtils.convertPrimitive(method.getParameterTypes()[0], value);
method.invoke(obj, v);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
}
}
}
private static void configReferenceBean(
Element element,
ParserContext parserContext,
RootBeanDefinition beanDefinition,
BeanDefinition consumerDefinition) {
// process interface class
String interfaceName = resolveAttribute(element, ReferenceAttributes.INTERFACE, parserContext);
String generic = resolveAttribute(element, ReferenceAttributes.GENERIC, parserContext);
if (StringUtils.isBlank(generic) && consumerDefinition != null) {
// get generic from consumerConfig
generic = getPropertyValue(consumerDefinition.getPropertyValues(), ReferenceAttributes.GENERIC);
}
if (generic != null) {
generic = resolvePlaceholders(generic, parserContext);
beanDefinition.getPropertyValues().add(ReferenceAttributes.GENERIC, generic);
}
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, interfaceName);
Class interfaceClass = ReferenceConfig.determineInterfaceClass(generic, interfaceName);
beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, interfaceClass);
// TODO Only register one reference bean for same (group, interface, version)
// create decorated definition for reference bean, Avoid being instantiated when getting the beanType of
// ReferenceBean
// see org.springframework.beans.factory.support.AbstractBeanFactory#getTypeForFactoryBean()
GenericBeanDefinition targetDefinition = new GenericBeanDefinition();
targetDefinition.setBeanClass(interfaceClass);
String beanName = (String) beanDefinition.getAttribute(BEAN_NAME);
beanDefinition.setDecoratedDefinition(new BeanDefinitionHolder(targetDefinition, beanName + "_decorated"));
// signal object type since Spring 5.2
beanDefinition.setAttribute(Constants.OBJECT_TYPE_ATTRIBUTE, interfaceClass);
// mark property value as optional
List<PropertyValue> propertyValues = beanDefinition.getPropertyValues().getPropertyValueList();
for (PropertyValue propertyValue : propertyValues) {
propertyValue.setOptional(true);
}
}
private static void getPropertyMap(Class<?> beanClass, Map<String, Class> beanPropsMap) {
for (Method setter : beanClass.getMethods()) {
String name = setter.getName();
if (name.length() > 3
&& name.startsWith("set")
&& Modifier.isPublic(setter.getModifiers())
&& setter.getParameterTypes().length == 1) {
Class<?> type = setter.getParameterTypes()[0];
String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4);
// check the setter/getter whether match
Method getter = null;
try {
getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e) {
try {
getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e2) {
// ignore, there is no need any log here since some class implement the interface:
// EnvironmentAware,
// ApplicationAware, etc. They only have setter method, otherwise will cause the error log
// during application start up.
}
}
if (getter == null
|| !Modifier.isPublic(getter.getModifiers())
|| !type.equals(getter.getReturnType())) {
continue;
}
beanPropsMap.put(beanProperty, type);
}
}
}
private static String getCompatibleDefaultValue(String property, String value) {
if ("async".equals(property) && "false".equals(value)
|| "timeout".equals(property) && "0".equals(value)
|| "delay".equals(property) && "0".equals(value)
|| "version".equals(property) && "0.0.0".equals(value)
|| "stat".equals(property) && "-1".equals(value)
|| "reliable".equals(property) && "false".equals(value)) {
// backward compatibility for the default value in old version's xsd
value = null;
}
return value;
}
private static boolean isPrimitive(Class<?> cls) {
return cls.isPrimitive()
|| cls == Boolean.class
|| cls == Byte.class
|| cls == Character.class
|| cls == Short.class
|| cls == Integer.class
|| cls == Long.class
|| cls == Float.class
|| cls == Double.class
|| cls == String.class
|| cls == Date.class
|| cls == Class.class;
}
private static void parseNested(
Element element,
ParserContext parserContext,
Class<?> beanClass,
boolean registered,
String tag,
String property,
String ref,
BeanDefinition beanDefinition) {
NodeList nodeList = element.getChildNodes();
if (nodeList == null) {
return;
}
boolean first = true;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (!(node instanceof Element)) {
continue;
}
if (tag.equals(node.getNodeName()) || tag.equals(node.getLocalName())) {
if (first) {
first = false;
String isDefault = resolveAttribute(element, "default", parserContext);
if (StringUtils.isEmpty(isDefault)) {
beanDefinition.getPropertyValues().addPropertyValue("default", "false");
}
}
RootBeanDefinition subDefinition = parse((Element) node, parserContext, beanClass, registered);
if (subDefinition != null) {
if (StringUtils.isNotEmpty(ref)) {
subDefinition.getPropertyValues().addPropertyValue(property, new RuntimeBeanReference(ref));
}
if (ReferenceBean.class.equals(beanClass)) {
configReferenceBean((Element) node, parserContext, subDefinition, beanDefinition);
}
}
}
}
}
private static void parseProperties(
NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) {
if (nodeList == null) {
return;
}
for (int i = 0; i < nodeList.getLength(); i++) {
if (!(nodeList.item(i) instanceof Element)) {
continue;
}
Element element = (Element) nodeList.item(i);
if ("property".equals(element.getNodeName()) || "property".equals(element.getLocalName())) {
String name = resolveAttribute(element, "name", parserContext);
if (StringUtils.isNotEmpty(name)) {
String value = resolveAttribute(element, "value", parserContext);
String ref = resolveAttribute(element, "ref", parserContext);
if (StringUtils.isNotEmpty(value)) {
beanDefinition.getPropertyValues().addPropertyValue(name, value);
} else if (StringUtils.isNotEmpty(ref)) {
beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref));
} else {
throw new UnsupportedOperationException("Unsupported <property name=\"" + name
+ "\"> sub tag, Only supported <property name=\"" + name
+ "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />");
}
}
}
}
}
@SuppressWarnings("unchecked")
private static ManagedMap parseParameters(
NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) {
if (nodeList == null) {
return null;
}
ManagedMap parameters = null;
for (int i = 0; i < nodeList.getLength(); i++) {
if (!(nodeList.item(i) instanceof Element)) {
continue;
}
Element element = (Element) nodeList.item(i);
if ("parameter".equals(element.getNodeName()) || "parameter".equals(element.getLocalName())) {
if (parameters == null) {
parameters = new ManagedMap();
}
String key = resolveAttribute(element, "key", parserContext);
String value = resolveAttribute(element, "value", parserContext);
boolean hide = "true".equals(resolveAttribute(element, "hide", parserContext));
if (hide) {
key = HIDE_KEY_PREFIX + key;
}
parameters.put(key, new TypedStringValue(value, String.class));
}
}
return parameters;
}
@SuppressWarnings("unchecked")
private static void parseMethods(
String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) {
if (nodeList == null) {
return;
}
ManagedList methods = null;
for (int i = 0; i < nodeList.getLength(); i++) {
if (!(nodeList.item(i) instanceof Element)) {
continue;
}
Element element = (Element) nodeList.item(i);
if ("method".equals(element.getNodeName()) || "method".equals(element.getLocalName())) {
String methodName = resolveAttribute(element, "name", parserContext);
if (StringUtils.isEmpty(methodName)) {
throw new IllegalStateException("<dubbo:method> name attribute == null");
}
if (methods == null) {
methods = new ManagedList();
}
RootBeanDefinition methodBeanDefinition = parse(element, parserContext, MethodConfig.class, false);
String beanName = id + "." + methodName;
// If the PropertyValue named "id" can't be found,
// bean name will be taken as the "id" PropertyValue for MethodConfig
if (!hasPropertyValue(methodBeanDefinition, "id")) {
addPropertyValue(methodBeanDefinition, "id", beanName);
}
BeanDefinitionHolder methodBeanDefinitionHolder =
new BeanDefinitionHolder(methodBeanDefinition, beanName);
methods.add(methodBeanDefinitionHolder);
}
}
if (methods != null) {
beanDefinition.getPropertyValues().addPropertyValue("methods", methods);
}
}
private static boolean hasPropertyValue(AbstractBeanDefinition beanDefinition, String propertyName) {
return beanDefinition.getPropertyValues().contains(propertyName);
}
private static void addPropertyValue(
AbstractBeanDefinition beanDefinition, String propertyName, String propertyValue) {
if (StringUtils.isBlank(propertyName) || StringUtils.isBlank(propertyValue)) {
return;
}
beanDefinition.getPropertyValues().addPropertyValue(propertyName, propertyValue);
}
@SuppressWarnings("unchecked")
private static void parseArguments(
String id, NodeList nodeList, RootBeanDefinition beanDefinition, ParserContext parserContext) {
if (nodeList == null) {
return;
}
ManagedList arguments = null;
for (int i = 0; i < nodeList.getLength(); i++) {
if (!(nodeList.item(i) instanceof Element)) {
continue;
}
Element element = (Element) nodeList.item(i);
if ("argument".equals(element.getNodeName()) || "argument".equals(element.getLocalName())) {
String argumentIndex = resolveAttribute(element, "index", parserContext);
if (arguments == null) {
arguments = new ManagedList();
}
BeanDefinition argumentBeanDefinition = parse(element, parserContext, ArgumentConfig.class, false);
String name = id + "." + argumentIndex;
BeanDefinitionHolder argumentBeanDefinitionHolder =
new BeanDefinitionHolder(argumentBeanDefinition, name);
arguments.add(argumentBeanDefinitionHolder);
}
}
if (arguments != null) {
beanDefinition.getPropertyValues().addPropertyValue("arguments", arguments);
}
}
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
return parse(element, parserContext, beanClass, true);
}
private static String resolveAttribute(Element element, String attributeName, ParserContext parserContext) {
String attributeValue = element.getAttribute(attributeName);
// Early resolve place holder may be wrong ( Before
// PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer )
// https://github.com/apache/dubbo/pull/6079
// https://github.com/apache/dubbo/issues/6035
// Environment environment = parserContext.getReaderContext().getEnvironment();
// return environment.resolvePlaceholders(attributeValue);
return attributeValue;
}
private static String resolvePlaceholders(String str, ParserContext parserContext) {
if (resolvePlaceholdersEnabled) {
try {
return parserContext.getReaderContext().getEnvironment().resolveRequiredPlaceholders(str);
} catch (NoSuchMethodError e) {
resolvePlaceholdersEnabled = false;
}
}
return str;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandler.java | /*
* 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 org.apache.dubbo.config.spring.schema;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.aot.AotWithSpringDetector;
import org.apache.dubbo.config.spring.beans.factory.config.ConfigurableSourceBeanMetadataElement;
import org.apache.dubbo.config.spring.context.DubboSpringInitializer;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.w3c.dom.Element;
/**
* DubboNamespaceHandler
*
* @export
*/
public class DubboNamespaceHandler extends NamespaceHandlerSupport implements ConfigurableSourceBeanMetadataElement {
@Override
public void init() {
registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class));
registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class));
registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class));
registerBeanDefinitionParser("config-center", new DubboBeanDefinitionParser(ConfigCenterBean.class));
registerBeanDefinitionParser("metadata-report", new DubboBeanDefinitionParser(MetadataReportConfig.class));
registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class));
registerBeanDefinitionParser("metrics", new DubboBeanDefinitionParser(MetricsConfig.class));
registerBeanDefinitionParser("tracing", new DubboBeanDefinitionParser(TracingConfig.class));
registerBeanDefinitionParser("ssl", new DubboBeanDefinitionParser(SslConfig.class));
registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class));
registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class));
registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class));
registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class));
registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class));
registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
}
/**
* Override {@link NamespaceHandlerSupport#parse(Element, ParserContext)} method
*
* @param element {@link Element}
* @param parserContext {@link ParserContext}
* @return
* @since 2.7.5
*/
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
registerAnnotationConfigProcessors(registry);
// initialize dubbo beans
DubboSpringInitializer.initialize(parserContext.getRegistry());
BeanDefinition beanDefinition = super.parse(element, parserContext);
setSource(beanDefinition);
return beanDefinition;
}
/**
* Register the processors for the Spring Annotation-Driven features
*
* @param registry {@link BeanDefinitionRegistry}
* @see AnnotationConfigUtils
* @since 2.7.5
*/
private void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
if (!AotWithSpringDetector.useGeneratedArtifacts()) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(registry);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.AbstractConfigManager;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
*
* Dubbo config bean initializer.
*
* NOTE: Dubbo config beans MUST be initialized after registering all BeanPostProcessors,
* that is after the AbstractApplicationContext#registerBeanPostProcessors() method.
*/
public class DubboConfigBeanInitializer implements BeanFactoryAware, InitializingBean {
public static String BEAN_NAME = "dubboConfigBeanInitializer";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final AtomicBoolean initialized = new AtomicBoolean(false);
private ConfigurableListableBeanFactory beanFactory;
private ReferenceBeanManager referenceBeanManager;
private ConfigManager configManager;
private ModuleModel moduleModel;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
@Override
public void afterPropertiesSet() throws Exception {
init();
}
private void init() {
if (initialized.compareAndSet(false, true)) {
referenceBeanManager = beanFactory.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
configManager = DubboBeanUtils.getConfigManager(beanFactory);
moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
try {
prepareDubboConfigBeans();
referenceBeanManager.prepareReferenceBeans();
} catch (Throwable e) {
throw new FatalBeanException("Initialization dubbo config beans failed", e);
}
}
}
/**
* Initializes there Dubbo's Config Beans before @Reference bean autowiring
*/
private void prepareDubboConfigBeans() {
logger.info("loading dubbo config beans ...");
// Make sure all these config beans are initialed and registered to ConfigManager
// load application config beans
loadConfigBeansOfType(ApplicationConfig.class, configManager);
loadConfigBeansOfType(RegistryConfig.class, configManager);
loadConfigBeansOfType(ProtocolConfig.class, configManager);
loadConfigBeansOfType(MonitorConfig.class, configManager);
loadConfigBeansOfType(ConfigCenterBean.class, configManager);
loadConfigBeansOfType(MetadataReportConfig.class, configManager);
loadConfigBeansOfType(MetricsConfig.class, configManager);
loadConfigBeansOfType(TracingConfig.class, configManager);
loadConfigBeansOfType(SslConfig.class, configManager);
// load module config beans
loadConfigBeansOfType(ModuleConfig.class, moduleModel.getConfigManager());
loadConfigBeansOfType(ProviderConfig.class, moduleModel.getConfigManager());
loadConfigBeansOfType(ConsumerConfig.class, moduleModel.getConfigManager());
// load ConfigCenterBean from properties, fix https://github.com/apache/dubbo/issues/9207
List<ConfigCenterBean> configCenterBeans = configManager.loadConfigsOfTypeFromProps(ConfigCenterBean.class);
for (ConfigCenterBean configCenterBean : configCenterBeans) {
String beanName = configCenterBean.getId() != null ? configCenterBean.getId() : "configCenterBean";
beanFactory.initializeBean(configCenterBean, beanName);
}
logger.info("dubbo config beans are loaded.");
}
private void loadConfigBeansOfType(
Class<? extends AbstractConfig> configClass, AbstractConfigManager configManager) {
String[] beanNames = beanFactory.getBeanNamesForType(configClass, true, false);
for (String beanName : beanNames) {
AbstractConfig configBean = beanFactory.getBean(beanName, configClass);
// Register config bean here, avoid relying on unreliable @PostConstruct init method
configManager.addConfig(configBean);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK;
/**
* Custom dubbo spring initialization
*/
@SPI(scope = FRAMEWORK)
public interface DubboSpringInitCustomizer {
/**
* <p>Customize dubbo spring initialization on bean registry processing phase.</p>
* <p>You can register a {@link BeanFactoryPostProcessor} or {@link BeanPostProcessor} for custom processing.</p>
* <p>Or change the bind module model via {@link DubboSpringInitContext#setModuleModel(ModuleModel)}.</p>
*
* <p><b>Note:</b></p>
* <p>1. The bean factory may be not ready yet when triggered by parsing dubbo xml definition.</p>
* <p>2. Some bean definitions may be not registered at this moment. If you plan to process all bean definitions,
* it is recommended to register a custom {@link BeanFactoryPostProcessor} to do so.</p>
*
* @param context
*/
void customize(DubboSpringInitContext context);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
/**
* Register some infrastructure beans if not exists.
* This post-processor MUST impl BeanDefinitionRegistryPostProcessor,
* in order to enable the registered BeanFactoryPostProcessor bean to be loaded and executed.
*
* @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(
*org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
*/
public class DubboInfraBeanRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {
/**
* The bean name of {@link ReferenceAnnotationBeanPostProcessor}
*/
public static final String BEAN_NAME = "dubboInfraBeanRegisterPostProcessor";
private BeanDefinitionRegistry registry;
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
this.registry = registry;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// In Spring 3.2.x, registry may be null because do not call postProcessBeanDefinitionRegistry method before
// postProcessBeanFactory
if (registry != null) {
// register ReferenceAnnotationBeanPostProcessor early before
// PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer
// for processing early init ReferenceBean
ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = beanFactory.getBean(
ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);
beanFactory.addBeanPostProcessor(referenceAnnotationBeanPostProcessor);
// register PropertySourcesPlaceholderConfigurer bean if not exits
DubboBeanUtils.registerPlaceholderConfigurerBeanIfNotExists(beanFactory, registry);
}
// fix https://github.com/apache/dubbo/issues/10278
if (registry != null) {
registry.removeBeanDefinition(BEAN_NAME);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.deploy.DeployListenerAdapter;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.config.spring.context.event.DubboApplicationStateEvent;
import org.apache.dubbo.config.spring.context.event.DubboModuleStateEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.spring.util.LockUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModelConstants;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.Future;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* An ApplicationListener to control Dubbo application.
*/
public class DubboDeployApplicationListener
implements ApplicationListener<ApplicationContextEvent>, ApplicationContextAware, Ordered {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DubboDeployApplicationListener.class);
private ApplicationContext applicationContext;
private ApplicationModel applicationModel;
private ModuleModel moduleModel;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.applicationModel = DubboBeanUtils.getApplicationModel(applicationContext);
this.moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
// listen deploy events and publish DubboApplicationStateEvent
applicationModel.getDeployer().addDeployListener(new DeployListenerAdapter<ApplicationModel>() {
@Override
public void onStarting(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STARTING);
}
@Override
public void onStarted(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STARTED);
}
@Override
public void onCompletion(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.COMPLETION);
}
@Override
public void onStopping(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STOPPING);
}
@Override
public void onStopped(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STOPPED);
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
publishApplicationEvent(DeployState.FAILED, cause);
}
});
moduleModel.getDeployer().addDeployListener(new DeployListenerAdapter<ModuleModel>() {
@Override
public void onStarting(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STARTING);
}
@Override
public void onStarted(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STARTED);
}
@Override
public void onCompletion(ModuleModel scopeModel) {
publishModuleEvent(DeployState.COMPLETION);
}
@Override
public void onStopping(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STOPPING);
}
@Override
public void onStopped(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STOPPED);
}
@Override
public void onFailure(ModuleModel scopeModel, Throwable cause) {
publishModuleEvent(DeployState.FAILED, cause);
}
});
}
private void publishApplicationEvent(DeployState state) {
applicationContext.publishEvent(new DubboApplicationStateEvent(applicationModel, state));
}
private void publishApplicationEvent(DeployState state, Throwable cause) {
applicationContext.publishEvent(new DubboApplicationStateEvent(applicationModel, state, cause));
}
private void publishModuleEvent(DeployState state) {
applicationContext.publishEvent(new DubboModuleStateEvent(moduleModel, state));
}
private void publishModuleEvent(DeployState state, Throwable cause) {
applicationContext.publishEvent(new DubboModuleStateEvent(moduleModel, state, cause));
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
if (nullSafeEquals(applicationContext, event.getSource())) {
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
}
private void onContextRefreshedEvent(ContextRefreshedEvent event) {
ModuleDeployer deployer = moduleModel.getDeployer();
Assert.notNull(deployer, "Module deployer is null");
Object singletonMutex = LockUtils.getSingletonMutex(applicationContext);
// start module
Future future = null;
synchronized (singletonMutex) {
future = deployer.start();
}
// if the module does not start in background, await finish
if (!deployer.isBackground()) {
try {
future.get();
} catch (InterruptedException e) {
logger.warn(
CONFIG_FAILED_START_MODEL,
"",
"",
"Interrupted while waiting for dubbo module start: " + e.getMessage());
} catch (Exception e) {
logger.warn(
CONFIG_FAILED_START_MODEL,
"",
"",
"An error occurred while waiting for dubbo module start: " + e.getMessage(),
e);
}
}
}
private void onContextClosedEvent(ContextClosedEvent event) {
try {
Object value = moduleModel.getAttribute(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED);
if (value == null) {
value = ConfigurationUtils.getProperty(moduleModel, ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED_KEY);
}
boolean keepRunningOnClosed = Boolean.parseBoolean(String.valueOf(value));
if (!keepRunningOnClosed && !moduleModel.isDestroyed()) {
moduleModel.destroy();
}
} catch (Exception e) {
logger.error(
CONFIG_STOP_DUBBO_ERROR,
"",
"",
"Unexpected error occurred when stop dubbo module: " + e.getMessage(),
e);
}
// remove context bind cache
DubboSpringInitializer.remove(event.getApplicationContext());
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboContextPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.context.annotation.DubboConfigConfigurationRegistrar;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.spring.util.EnvironmentUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.SortedMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
public class DubboContextPostProcessor
implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, EnvironmentAware {
/**
* The bean name of {@link DubboConfigConfigurationRegistrar}
*/
public static final String BEAN_NAME = "dubboContextPostProcessor";
private ApplicationContext applicationContext;
private ConfigurableEnvironment environment;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(beanFactory);
ModuleModel moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
// Initialize SpringExtensionInjector
SpringExtensionInjector.get(applicationModel).init(applicationContext);
SpringExtensionInjector.get(moduleModel).init(applicationContext);
DubboBeanUtils.getInitializationContext(beanFactory).setApplicationContext(applicationContext);
// Initialize dubbo Environment before ConfigManager
// Extract dubbo props from Spring env and put them to app config
SortedMap<String, String> dubboProperties = EnvironmentUtils.filterDubboProperties(environment);
applicationModel.getModelEnvironment().getAppConfigMap().putAll(dubboProperties);
// register ConfigManager singleton
beanFactory.registerSingleton(ConfigManager.BEAN_NAME, applicationModel.getApplicationConfigManager());
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
DubboSpringInitializer.initialize(beanDefinitionRegistry);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = (ConfigurableEnvironment) environment;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapStartStopListenerSpringAdapter.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapStartStopListenerSpringAdapter.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.bootstrap.DubboBootstrapStartStopListener;
import org.apache.dubbo.config.spring.context.event.DubboBootstrapStatedEvent;
import org.apache.dubbo.config.spring.context.event.DubboBootstrapStopedEvent;
import org.springframework.context.ApplicationContext;
/**
* convcert Dubbo bootstrap event to spring environment.
*
* @scene 2.7.9
*/
@Deprecated
public class DubboBootstrapStartStopListenerSpringAdapter implements DubboBootstrapStartStopListener {
static ApplicationContext applicationContext;
@Override
public void onStart(DubboBootstrap bootstrap) {
if (applicationContext != null) {
applicationContext.publishEvent(new DubboBootstrapStatedEvent(bootstrap));
}
}
@Override
public void onStop(DubboBootstrap bootstrap) {
if (applicationContext != null) {
applicationContext.publishEvent(new DubboBootstrapStopedEvent(bootstrap));
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.bootstrap.BootstrapTakeoverMode;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.beans.BeansException;
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.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* The {@link ApplicationListener} for {@link DubboBootstrap}'s lifecycle when the {@link ContextRefreshedEvent}
* and {@link ContextClosedEvent} raised
*
* @since 2.7.5
*/
@Deprecated
public class DubboBootstrapApplicationListener implements ApplicationListener, ApplicationContextAware, Ordered {
/**
* The bean name of {@link DubboBootstrapApplicationListener}
*
* @since 2.7.6
*/
public static final String BEAN_NAME = "dubboBootstrapApplicationListener";
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ApplicationContext applicationContext;
private DubboBootstrap bootstrap;
private boolean shouldInitConfigBeans;
private ModuleModel moduleModel;
public DubboBootstrapApplicationListener() {}
public DubboBootstrapApplicationListener(boolean shouldInitConfigBeans) {
// maybe register DubboBootstrapApplicationListener manual during spring context starting
this.shouldInitConfigBeans = shouldInitConfigBeans;
}
private void setBootstrap(DubboBootstrap bootstrap) {
this.bootstrap = bootstrap;
if (bootstrap.getTakeoverMode() != BootstrapTakeoverMode.MANUAL) {
bootstrap.setTakeoverMode(BootstrapTakeoverMode.SPRING);
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (isOriginalEventSource(event)) {
if (event instanceof DubboConfigInitEvent) {
// This event will be notified at AbstractApplicationContext.registerListeners(),
// init dubbo config beans before spring singleton beans
initDubboConfigBeans();
} else if (event instanceof ApplicationContextEvent) {
this.onApplicationContextEvent((ApplicationContextEvent) event);
}
}
}
private void initDubboConfigBeans() {
// load DubboConfigBeanInitializer to init config beans
if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) {
applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class);
} else {
logger.warn(
CONFIG_DUBBO_BEAN_NOT_FOUND,
"",
"",
"Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found");
}
// All infrastructure config beans are loaded, initialize dubbo here
moduleModel.getDeployer().initialize();
}
private void onApplicationContextEvent(ApplicationContextEvent event) {
if (DubboBootstrapStartStopListenerSpringAdapter.applicationContext == null) {
DubboBootstrapStartStopListenerSpringAdapter.applicationContext = event.getApplicationContext();
}
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
private void onContextRefreshedEvent(ContextRefreshedEvent event) {
if (bootstrap.getTakeoverMode() == BootstrapTakeoverMode.SPRING) {
moduleModel.getDeployer().start();
}
}
private void onContextClosedEvent(ContextClosedEvent event) {
if (bootstrap.getTakeoverMode() == BootstrapTakeoverMode.SPRING) {
// will call dubboBootstrap.stop() through shutdown callback.
// bootstrap.getApplicationModel().getBeanFactory().getBean(DubboShutdownHook.class).run();
moduleModel.getDeployer().stop();
}
}
/**
* Is original {@link ApplicationContext} as the event source
*
* @param event {@link ApplicationEvent}
* @return if original, return <code>true</code>, or <code>false</code>
*/
private boolean isOriginalEventSource(ApplicationEvent event) {
boolean originalEventSource = nullSafeEquals(getApplicationContext(), event.getSource());
return originalEventSource;
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
this.setBootstrap(DubboBootstrap.getInstance(moduleModel.getApplicationModel()));
if (shouldInitConfigBeans) {
checkCallStackAndInit();
}
}
private void checkCallStackAndInit() {
// check call stack whether contains
// org.springframework.context.support.AbstractApplicationContext.registerListeners()
Exception exception = new Exception();
StackTraceElement[] stackTrace = exception.getStackTrace();
boolean found = false;
for (StackTraceElement frame : stackTrace) {
if (frame.getMethodName().equals("registerListeners")
&& frame.getClassName().endsWith("AbstractApplicationContext")) {
found = true;
break;
}
}
if (found) {
// init config beans here, compatible with spring 3.x/4.1.x
initDubboConfigBeans();
} else {
logger.warn(
CONFIG_DUBBO_BEAN_INITIALIZER,
"",
"",
"DubboBootstrapApplicationListener initialization is unexpected, "
+ "it should be created in AbstractApplicationContext.registerListeners() method",
exception);
}
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* An ApplicationListener to load config beans
*/
public class DubboConfigApplicationListener
implements ApplicationListener<DubboConfigInitEvent>, ApplicationContextAware {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DubboConfigApplicationListener.class);
private ApplicationContext applicationContext;
private ModuleModel moduleModel;
private final AtomicBoolean initialized = new AtomicBoolean();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
}
@Override
public void onApplicationEvent(DubboConfigInitEvent event) {
if (nullSafeEquals(applicationContext, event.getSource())) {
init();
}
}
public synchronized void init() {
// It's expected to be notified at
// org.springframework.context.support.AbstractApplicationContext.registerListeners(),
// before loading non-lazy singleton beans. At this moment, all BeanFactoryPostProcessor have been processed,
if (initialized.compareAndSet(false, true)) {
initDubboConfigBeans();
}
}
private void initDubboConfigBeans() {
// load DubboConfigBeanInitializer to init config beans
if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) {
applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class);
} else {
logger.warn(
CONFIG_DUBBO_BEAN_NOT_FOUND,
"",
"",
"Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found");
}
// All infrastructure config beans are loaded, initialize dubbo here
moduleModel.getDeployer().prepare();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.java | /*
* 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 org.apache.dubbo.config.spring.context;
import java.util.HashSet;
import java.util.Set;
/**
* Hold a set of DubboSpringInitCustomizer, for register customizers by programming.
* <p>All customizers are store in thread local, and they will be clear after apply once.</p>
*
* <p>Usages:</p>
*<pre>
* DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {...});
* ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(..);
* ...
* DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {...});
* ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(..);
* </pre>
*/
public class DubboSpringInitCustomizerHolder {
private static final ThreadLocal<DubboSpringInitCustomizerHolder> holders =
ThreadLocal.withInitial(DubboSpringInitCustomizerHolder::new);
public static DubboSpringInitCustomizerHolder get() {
return holders.get();
}
private Set<DubboSpringInitCustomizer> customizers = new HashSet<>();
public void addCustomizer(DubboSpringInitCustomizer customizer) {
this.customizers.add(customizer);
}
public void clearCustomizers() {
this.customizers = new HashSet<>();
}
public Set<DubboSpringInitCustomizer> getCustomizers() {
return customizers;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModelConstants;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
/**
* Dubbo spring initialization context object
*/
public class DubboSpringInitContext {
private BeanDefinitionRegistry registry;
private ConfigurableListableBeanFactory beanFactory;
private ApplicationContext applicationContext;
private ModuleModel moduleModel;
private final Map<String, Object> moduleAttributes = new HashMap<>();
private volatile boolean bound;
public void markAsBound() {
bound = true;
}
public BeanDefinitionRegistry getRegistry() {
return registry;
}
void setRegistry(BeanDefinitionRegistry registry) {
this.registry = registry;
}
public ConfigurableListableBeanFactory getBeanFactory() {
return beanFactory;
}
void setBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public ApplicationModel getApplicationModel() {
return (moduleModel == null) ? null : moduleModel.getApplicationModel();
}
public ModuleModel getModuleModel() {
return moduleModel;
}
/**
* Change the binding ModuleModel, the ModuleModel and DubboBootstrap must be matched.
*
* @param moduleModel
*/
public void setModuleModel(ModuleModel moduleModel) {
if (bound) {
throw new IllegalStateException("Cannot change ModuleModel after bound context");
}
this.moduleModel = moduleModel;
}
public boolean isKeepRunningOnSpringClosed() {
return (boolean) moduleAttributes.get(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED);
}
/**
* Keep Dubbo running when spring is stopped
* @param keepRunningOnSpringClosed
*/
public void setKeepRunningOnSpringClosed(boolean keepRunningOnSpringClosed) {
this.setModuleAttribute(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED, keepRunningOnSpringClosed);
}
public Map<String, Object> getModuleAttributes() {
return moduleAttributes;
}
public void setModuleAttribute(String key, Object value) {
this.moduleAttributes.put(key, value);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.java | /*
* 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 org.apache.dubbo.config.spring.context;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.spring.aot.AotWithSpringDetector;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.util.ObjectUtils;
/**
* Dubbo spring initialization entry point
*/
public class DubboSpringInitializer {
private static final Logger logger = LoggerFactory.getLogger(DubboSpringInitializer.class);
private static final Map<BeanDefinitionRegistry, DubboSpringInitContext> REGISTRY_CONTEXT_MAP =
new ConcurrentHashMap<>();
public DubboSpringInitializer() {}
public static void initialize(BeanDefinitionRegistry registry) {
// prepare context and do customize
DubboSpringInitContext context = new DubboSpringInitContext();
// Spring ApplicationContext may not ready at this moment (e.g. load from xml), so use registry as key
if (REGISTRY_CONTEXT_MAP.putIfAbsent(registry, context) != null) {
return;
}
// find beanFactory
ConfigurableListableBeanFactory beanFactory = findBeanFactory(registry);
// init dubbo context
initContext(context, registry, beanFactory);
}
public static boolean remove(BeanDefinitionRegistry registry) {
return REGISTRY_CONTEXT_MAP.remove(registry) != null;
}
public static boolean remove(ApplicationContext springContext) {
AutowireCapableBeanFactory autowireCapableBeanFactory = springContext.getAutowireCapableBeanFactory();
for (Map.Entry<BeanDefinitionRegistry, DubboSpringInitContext> entry : REGISTRY_CONTEXT_MAP.entrySet()) {
DubboSpringInitContext initContext = entry.getValue();
if (initContext.getApplicationContext() == springContext
|| initContext.getBeanFactory() == autowireCapableBeanFactory
|| initContext.getRegistry() == autowireCapableBeanFactory) {
DubboSpringInitContext context = REGISTRY_CONTEXT_MAP.remove(entry.getKey());
logger.info("Unbind " + safeGetModelDesc(context.getModuleModel()) + " from spring container: "
+ ObjectUtils.identityToString(entry.getKey()));
return true;
}
}
return false;
}
static Map<BeanDefinitionRegistry, DubboSpringInitContext> getContextMap() {
return REGISTRY_CONTEXT_MAP;
}
static DubboSpringInitContext findBySpringContext(ApplicationContext applicationContext) {
for (DubboSpringInitContext initContext : REGISTRY_CONTEXT_MAP.values()) {
if (initContext.getApplicationContext() == applicationContext) {
return initContext;
}
}
return null;
}
private static void initContext(
DubboSpringInitContext context,
BeanDefinitionRegistry registry,
ConfigurableListableBeanFactory beanFactory) {
context.setRegistry(registry);
context.setBeanFactory(beanFactory);
// customize context, you can change the bind module model via DubboSpringInitCustomizer SPI
customize(context);
// init ModuleModel
ModuleModel moduleModel = context.getModuleModel();
if (moduleModel == null) {
ApplicationModel applicationModel;
if (findContextForApplication(ApplicationModel.defaultModel()) == null) {
// first spring context use default application instance
applicationModel = ApplicationModel.defaultModel();
logger.info("Use default application: " + applicationModel.getDesc());
} else {
// create a new application instance for later spring context
applicationModel = FrameworkModel.defaultModel().newApplication();
logger.info("Create new application: " + applicationModel.getDesc());
}
// init ModuleModel
moduleModel = applicationModel.getDefaultModule();
context.setModuleModel(moduleModel);
logger.info("Use default module model of target application: " + moduleModel.getDesc());
} else {
logger.info("Use module model from customizer: " + moduleModel.getDesc());
}
logger.info(
"Bind " + moduleModel.getDesc() + " to spring container: " + ObjectUtils.identityToString(registry));
// set module attributes
Map<String, Object> moduleAttributes = context.getModuleAttributes();
if (moduleAttributes.size() > 0) {
moduleModel.getAttributes().putAll(moduleAttributes);
}
// bind dubbo initialization context to spring context
registerContextBeans(beanFactory, context);
// mark context as bound
context.markAsBound();
moduleModel.setLifeCycleManagedExternally(true);
if (!AotWithSpringDetector.useGeneratedArtifacts()) {
// register common beans
DubboBeanUtils.registerCommonBeans(registry);
}
}
private static String safeGetModelDesc(ScopeModel scopeModel) {
return scopeModel != null ? scopeModel.getDesc() : null;
}
private static ConfigurableListableBeanFactory findBeanFactory(BeanDefinitionRegistry registry) {
ConfigurableListableBeanFactory beanFactory;
if (registry instanceof ConfigurableListableBeanFactory) {
beanFactory = (ConfigurableListableBeanFactory) registry;
} else if (registry instanceof GenericApplicationContext) {
GenericApplicationContext genericApplicationContext = (GenericApplicationContext) registry;
beanFactory = genericApplicationContext.getBeanFactory();
} else {
throw new IllegalStateException("Can not find Spring BeanFactory from registry: "
+ registry.getClass().getName());
}
return beanFactory;
}
private static void registerContextBeans(
ConfigurableListableBeanFactory beanFactory, DubboSpringInitContext context) {
// register singleton
if (!beanFactory.containsSingleton(DubboSpringInitContext.class.getName())) {
registerSingleton(beanFactory, context);
}
if (!beanFactory.containsSingleton(
context.getApplicationModel().getClass().getName())) {
registerSingleton(beanFactory, context.getApplicationModel());
}
if (!beanFactory.containsSingleton(context.getModuleModel().getClass().getName())) {
registerSingleton(beanFactory, context.getModuleModel());
}
}
private static void registerSingleton(ConfigurableListableBeanFactory beanFactory, Object bean) {
beanFactory.registerSingleton(bean.getClass().getName(), bean);
}
private static DubboSpringInitContext findContextForApplication(ApplicationModel applicationModel) {
for (DubboSpringInitContext initializationContext : REGISTRY_CONTEXT_MAP.values()) {
if (initializationContext.getApplicationModel() == applicationModel) {
return initializationContext;
}
}
return null;
}
private static void customize(DubboSpringInitContext context) {
// find initialization customizers
Set<DubboSpringInitCustomizer> customizers = FrameworkModel.defaultModel()
.getExtensionLoader(DubboSpringInitCustomizer.class)
.getSupportedExtensionInstances();
for (DubboSpringInitCustomizer customizer : customizers) {
customizer.customize(context);
}
// load customizers in thread local holder
DubboSpringInitCustomizerHolder customizerHolder = DubboSpringInitCustomizerHolder.get();
customizers = customizerHolder.getCustomizers();
for (DubboSpringInitCustomizer customizer : customizers) {
customizer.customize(context);
}
customizerHolder.clearCustomizers();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.java | /*
* 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 org.apache.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<PropertySource<?>> propertySources;
private boolean ignoreUnknownFields = true;
private boolean ignoreInvalidFields = false;
/**
* Get multiple {@link PropertySource propertySources}
*
* @return multiple {@link PropertySource propertySources}
*/
protected Iterable<PropertySource<?>> 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();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.java | /*
* 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 org.apache.dubbo.config.spring.context.properties;
import org.apache.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.
* <p>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).
* <p>Default is "false".
*
* @see #bind
*/
void setIgnoreInvalidFields(boolean ignoreInvalidFields);
/**
* Bind the properties to Dubbo Config Object under specified prefix.
*
* @param prefix
* @param dubboConfig
*/
<C extends AbstractConfig> void bind(String prefix, C dubboConfig);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.java | /*
* 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 org.apache.dubbo.config.spring.context.properties;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.util.PropertySourcesUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;
/**
* Default {@link DubboConfigBinder} implementation based on Spring {@link DataBinder}
*/
public class DefaultDubboConfigBinder extends AbstractDubboConfigBinder {
@Override
public <C extends AbstractConfig> 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<String, Object> properties = PropertySourcesUtils.getSubProperties(getPropertySources(), prefix);
// Convert Map to MutablePropertyValues
MutablePropertyValues propertyValues = new MutablePropertyValues(properties);
// Bind
dataBinder.bind(propertyValues);
BindingResult bindingResult = dataBinder.getBindingResult();
if (bindingResult.hasGlobalErrors()) {
throw new RuntimeException(
"Data bind global error, please check config. config: " + bindingResult.getGlobalError() + "");
}
if (bindingResult.hasFieldErrors()) {
throw new RuntimeException(buildErrorMsg(
bindingResult.getFieldErrors(),
prefix,
dubboConfig.getClass().getSimpleName()));
}
}
private String buildErrorMsg(List<FieldError> errors, String prefix, String config) {
StringBuilder builder = new StringBuilder("Data bind error, please check config. config: " + config
+ ", prefix: " + prefix + " , error fields: [" + errors.get(0).getField());
if (errors.size() > 1) {
IntStream.range(1, errors.size()).forEach(i -> {
builder.append(", " + errors.get(i).getField());
});
}
builder.append(']');
return builder.toString();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStatedEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStatedEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.springframework.context.ApplicationEvent;
/**
* A {@link org.springframework.context.ApplicationEvent} after {@link org.apache.dubbo.config.bootstrap.DubboBootstrap#start()} success
*
* @see org.springframework.context.ApplicationEvent
* @see org.springframework.context.ApplicationListener
* @see org.apache.dubbo.config.bootstrap.DubboBootstrap
* @since 2.7.9
*/
@Deprecated
public class DubboBootstrapStatedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param bootstrap {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} bootstrap
*/
public DubboBootstrapStatedEvent(DubboBootstrap bootstrap) {
super(bootstrap);
}
/**
* Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance
*
* @return non-null
*/
public DubboBootstrap getDubboBootstrap() {
return (DubboBootstrap) super.getSource();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboApplicationStateEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboApplicationStateEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.springframework.context.ApplicationEvent;
/**
* Dubbo's application state event on starting/started/stopping/stopped
*/
public class DubboApplicationStateEvent extends ApplicationEvent {
private final DeployState state;
private Throwable cause;
public DubboApplicationStateEvent(ApplicationModel applicationModel, DeployState state) {
super(applicationModel);
this.state = state;
}
public DubboApplicationStateEvent(ApplicationModel applicationModel, DeployState state, Throwable cause) {
super(applicationModel);
this.state = state;
this.cause = cause;
}
public ApplicationModel getApplicationModel() {
return (ApplicationModel) getSource();
}
public DeployState getState() {
return state;
}
public Throwable getCause() {
return cause;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStopedEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStopedEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.springframework.context.ApplicationEvent;
/**
* A {@link org.springframework.context.ApplicationEvent} after {@link org.apache.dubbo.config.bootstrap.DubboBootstrap#stop()} success
*
* @see org.springframework.context.ApplicationEvent
* @see org.springframework.context.ApplicationListener
* @see org.apache.dubbo.config.bootstrap.DubboBootstrap
* @since 2.7.9
*/
@Deprecated
public class DubboBootstrapStopedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param bootstrap {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} bootstrap
*/
public DubboBootstrapStopedEvent(DubboBootstrap bootstrap) {
super(bootstrap);
}
/**
* Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance
*
* @return non-null
*/
public DubboBootstrap getDubboBootstrap() {
return (DubboBootstrap) super.getSource();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
/**
* An {@link ApplicationEvent} to trigger init {@link DubboConfigBeanInitializer}.
*
*/
public class DubboConfigInitEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public DubboConfigInitEvent(ApplicationContext source) {
super(source);
}
/**
* Get the {@code ApplicationContext} that the event was raised for.
*/
public final ApplicationContext getApplicationContext() {
return (ApplicationContext) getSource();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboModuleStateEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboModuleStateEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.context.ApplicationEvent;
/**
* Dubbo's module state event on starting/started/stopping/stopped
*/
public class DubboModuleStateEvent extends ApplicationEvent {
private final DeployState state;
private Throwable cause;
public DubboModuleStateEvent(ModuleModel applicationModel, DeployState state) {
super(applicationModel);
this.state = state;
}
public DubboModuleStateEvent(ModuleModel applicationModel, DeployState state, Throwable cause) {
super(applicationModel);
this.state = state;
this.cause = cause;
}
public ModuleModel getModule() {
return (ModuleModel) getSource();
}
public DeployState getState() {
return state;
}
public Throwable getCause() {
return cause;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/ServiceBeanExportedEvent.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/ServiceBeanExportedEvent.java | /*
* 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 org.apache.dubbo.config.spring.context.event;
import org.apache.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
*
* @see ApplicationEvent
* @see ApplicationListener
* @see ServiceBean
* @since 2.6.5
*/
public class ServiceBeanExportedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param serviceBean {@link ServiceBean} bean
*/
public ServiceBeanExportedEvent(ServiceBean serviceBean) {
super(serviceBean);
}
/**
* Get {@link ServiceBean} instance
*
* @return non-null
*/
public ServiceBean getServiceBean() {
return (ServiceBean) super.getSource();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingsRegister.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingsRegister.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.Assert;
/**
* The {@link ImportBeanDefinitionRegistrar Registrar class} for {@link EnableConfigurationBeanBindings}
*
*/
public class ConfigurationBeanBindingsRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private ConfigurableEnvironment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
importingClassMetadata.getAnnotationAttributes(EnableConfigurationBeanBindings.class.getName()));
AnnotationAttributes[] annotationAttributes = attributes.getAnnotationArray("value");
ConfigurationBeanBindingRegistrar registrar = new ConfigurationBeanBindingRegistrar();
registrar.setEnvironment(environment);
for (AnnotationAttributes element : annotationAttributes) {
registrar.registerConfigurationBeanDefinitions(element, registry);
}
}
@Override
public void setEnvironment(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
this.environment = (ConfigurableEnvironment) environment;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* As a convenient and multiple {@link EnableConfigurationBeanBinding}
* in default behavior , is equal to single bean bindings with below convention prefixes of properties:
* <ul>
* <li>{@link ApplicationConfig} binding to property : "dubbo.application"</li>
* <li>{@link ModuleConfig} binding to property : "dubbo.module"</li>
* <li>{@link RegistryConfig} binding to property : "dubbo.registry"</li>
* <li>{@link ProtocolConfig} binding to property : "dubbo.protocol"</li>
* <li>{@link MonitorConfig} binding to property : "dubbo.monitor"</li>
* <li>{@link ProviderConfig} binding to property : "dubbo.provider"</li>
* <li>{@link ConsumerConfig} binding to property : "dubbo.consumer"</li>
* </ul>
* <p>
* In contrast, on multiple bean bindings that requires to set {@link #multiple()} to be <code>true</code> :
* <ul>
* <li>{@link ApplicationConfig} binding to property : "dubbo.applications"</li>
* <li>{@link ModuleConfig} binding to property : "dubbo.modules"</li>
* <li>{@link RegistryConfig} binding to property : "dubbo.registries"</li>
* <li>{@link ProtocolConfig} binding to property : "dubbo.protocols"</li>
* <li>{@link MonitorConfig} binding to property : "dubbo.monitors"</li>
* <li>{@link ProviderConfig} binding to property : "dubbo.providers"</li>
* <li>{@link ConsumerConfig} binding to property : "dubbo.consumers"</li>
* </ul>
*
* @see EnableConfigurationBeanBinding
* @see DubboConfigConfiguration
* @see DubboConfigConfigurationRegistrar
* @since 2.5.8
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Import(DubboConfigConfigurationRegistrar.class)
public @interface EnableDubboConfig {
/**
* It indicates whether binding to multiple Spring Beans.
*
* @return the default value is <code>true</code>
* @revised 2.5.9
*/
boolean multiple() default true;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableConfigurationBeanBinding.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableConfigurationBeanBinding.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.spring.context.config.ConfigurationBeanCustomizer;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.PropertySources;
/**
* Enables Spring's annotation-driven configuration bean from {@link PropertySources properties}.
*
* @see ConfigurationBeanBindingRegistrar
* @see ConfigurationBeanBindingPostProcessor
* @see ConfigurationBeanCustomizer
*/
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ConfigurationBeanBindingRegistrar.class)
public @interface EnableConfigurationBeanBinding {
/**
* The default value for {@link #multiple()}
*
* @since 1.0.6
*/
boolean DEFAULT_MULTIPLE = false;
/**
* The default value for {@link #ignoreUnknownFields()}
*
* @since 1.0.6
*/
boolean DEFAULT_IGNORE_UNKNOWN_FIELDS = true;
/**
* The default value for {@link #ignoreInvalidFields()}
*
* @since 1.0.6
*/
boolean DEFAULT_IGNORE_INVALID_FIELDS = true;
/**
* The name prefix of the properties that are valid to bind to the type of configuration.
*
* @return the name prefix of the properties to bind
*/
String prefix();
/**
* @return The binding type of configuration.
*/
Class<?> type();
/**
* It indicates whether {@link #prefix()} binding to multiple Spring Beans.
*
* @return the default value is <code>false</code>
* @see #DEFAULT_MULTIPLE
*/
boolean multiple() default DEFAULT_MULTIPLE;
/**
* Set whether to ignore unknown fields, that is, whether to ignore bind
* parameters that do not have corresponding fields in the target object.
* <p>Default is "true". Turn this off to enforce that all bind parameters
* must have a matching field in the target object.
*
* @return the default value is <code>true</code>
* @see #DEFAULT_IGNORE_UNKNOWN_FIELDS
*/
boolean ignoreUnknownFields() default DEFAULT_IGNORE_UNKNOWN_FIELDS;
/**
* 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).
* <p>Default is "true".
*
* @return the default value is <code>true</code>
* @see #DEFAULT_IGNORE_INVALID_FIELDS
*/
boolean ignoreInvalidFields() default DEFAULT_IGNORE_INVALID_FIELDS;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.context.DubboSpringInitializer;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.Ordered;
import org.springframework.core.type.AnnotationMetadata;
/**
* Dubbo {@link AbstractConfig Config} {@link ImportBeanDefinitionRegistrar register}, which order can be configured
*
* @see EnableDubboConfig
* @see DubboConfigConfiguration
* @see Ordered
* @since 2.5.8
*/
public class DubboConfigConfigurationRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// initialize dubbo beans
DubboSpringInitializer.initialize(registry);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor;
import org.apache.dubbo.config.spring.context.DubboSpringInitializer;
import org.apache.dubbo.config.spring.util.SpringCompatUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
* Dubbo {@link DubboComponentScan} Bean Registrar
*
* @see Service
* @see DubboComponentScan
* @see ImportBeanDefinitionRegistrar
* @see ServiceAnnotationPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.5.7
*/
public class DubboComponentScanRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// initialize dubbo beans
DubboSpringInitializer.initialize(registry);
Set<String> packagesToScan = getPackagesToScan(importingClassMetadata);
registerServiceAnnotationPostProcessor(packagesToScan, registry);
}
/**
* Registers {@link ServiceAnnotationPostProcessor}
*
* @param packagesToScan packages to scan without resolving placeholders
* @param registry {@link BeanDefinitionRegistry}
* @since 2.5.8
*/
private void registerServiceAnnotationPostProcessor(Set<String> packagesToScan, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder builder = rootBeanDefinition(SpringCompatUtils.serviceAnnotationPostProcessor());
builder.addConstructorArgValue(packagesToScan);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);
}
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
// get from @DubboComponentScan
Set<String> packagesToScan =
getPackagesToScan0(metadata, DubboComponentScan.class, "basePackages", "basePackageClasses");
// get from @EnableDubbo, compatible with spring 3.x
if (packagesToScan.isEmpty()) {
packagesToScan =
getPackagesToScan0(metadata, EnableDubbo.class, "scanBasePackages", "scanBasePackageClasses");
}
if (packagesToScan.isEmpty()) {
return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
}
return packagesToScan;
}
private Set<String> getPackagesToScan0(
AnnotationMetadata metadata,
Class annotationClass,
String basePackagesName,
String basePackageClassesName) {
AnnotationAttributes attributes =
AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClass.getName()));
if (attributes == null) {
return Collections.emptySet();
}
Set<String> packagesToScan = new LinkedHashSet<>();
// basePackages
String[] basePackages = attributes.getStringArray(basePackagesName);
packagesToScan.addAll(Arrays.asList(basePackages));
// basePackageClasses
Class<?>[] basePackageClasses = attributes.getClassArray(basePackageClassesName);
for (Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
}
// value
if (attributes.containsKey("value")) {
String[] value = attributes.getStringArray("value");
packagesToScan.addAll(Arrays.asList(value));
}
return packagesToScan;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* Dubbo Component Scan {@link Annotation},scans the classpath for annotated components that will be auto-registered as
* Spring beans. Dubbo-provided {@link Service} and {@link Reference}.
*
* @see Service
* @see Reference
* @since 2.5.7
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(DubboComponentScanRegistrar.class)
public @interface DubboComponentScan {
/**
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
* declarations e.g.: {@code @DubboComponentScan("org.my.pkg")} instead of
* {@code @DubboComponentScan(basePackages="org.my.pkg")}.
*
* @return the base packages to scan
*/
String[] value() default {};
/**
* Base packages to scan for annotated @Service classes. {@link #value()} is an
* alias for (and mutually exclusive with) this attribute.
* <p>
* Use {@link #basePackageClasses()} for a type-safe alternative to String-based
* package names.
*
* @return the base packages to scan
*/
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages()} for specifying the packages to
* scan for annotated @Service classes. The package of each class specified will be
* scanned.
*
* @return classes from the base packages to scan
*/
Class<?>[] basePackageClasses() default {};
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* Enables Dubbo components as Spring Beans, equals
* {@link DubboComponentScan} and {@link EnableDubboConfig} combination.
* <p>
* Note : {@link EnableDubbo} must base on Spring Framework 4.2 and above
*
* @see DubboComponentScan
* @see EnableDubboConfig
* @since 2.5.8
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@EnableDubboConfig
@DubboComponentScan
public @interface EnableDubbo {
/**
* Base packages to scan for annotated @Service classes.
* <p>
* Use {@link #scanBasePackageClasses()} for a type-safe alternative to String-based
* package names.
*
* @return the base packages to scan
* @see DubboComponentScan#basePackages()
*/
@AliasFor(annotation = DubboComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
/**
* Type-safe alternative to {@link #scanBasePackages()} for specifying the packages to
* scan for annotated @Service classes. The package of each class specified will be
* scanned.
*
* @return classes from the base packages to scan
* @see DubboComponentScan#basePackageClasses
*/
@AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
/**
* It indicates whether {@link AbstractConfig} binding to multiple Spring Beans.
*
* @return the default value is <code>true</code>
* @see EnableDubboConfig#multiple()
*/
@AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple")
boolean multipleConfig() default true;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingRegistrar.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingRegistrar.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
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.type.AnnotationMetadata;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static java.lang.Boolean.valueOf;
import static java.util.Collections.singleton;
import static org.apache.dubbo.config.spring.context.annotation.ConfigurationBeanBindingPostProcessor.initBeanMetadataAttributes;
import static org.apache.dubbo.config.spring.context.annotation.EnableConfigurationBeanBinding.DEFAULT_IGNORE_INVALID_FIELDS;
import static org.apache.dubbo.config.spring.context.annotation.EnableConfigurationBeanBinding.DEFAULT_IGNORE_UNKNOWN_FIELDS;
import static org.apache.dubbo.config.spring.context.annotation.EnableConfigurationBeanBinding.DEFAULT_MULTIPLE;
import static org.apache.dubbo.config.spring.util.AnnotationUtils.getAttribute;
import static org.apache.dubbo.config.spring.util.AnnotationUtils.getRequiredAttribute;
import static org.apache.dubbo.config.spring.util.DubboBeanUtils.registerInfrastructureBean;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.normalizePrefix;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
* The {@link ImportBeanDefinitionRegistrar} implementation for {@link EnableConfigurationBeanBinding @EnableConfigurationBinding}
*
*/
public class ConfigurationBeanBindingRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
static final Class ENABLE_CONFIGURATION_BINDING_CLASS = EnableConfigurationBeanBinding.class;
private static final String ENABLE_CONFIGURATION_BINDING_CLASS_NAME = ENABLE_CONFIGURATION_BINDING_CLASS.getName();
private final Log log = LogFactory.getLog(getClass());
private ConfigurableEnvironment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ENABLE_CONFIGURATION_BINDING_CLASS_NAME);
registerConfigurationBeanDefinitions(attributes, registry);
}
public void registerConfigurationBeanDefinitions(Map<String, Object> attributes, BeanDefinitionRegistry registry) {
String prefix = getRequiredAttribute(attributes, "prefix");
prefix = environment.resolvePlaceholders(prefix);
Class<?> configClass = getRequiredAttribute(attributes, "type");
boolean multiple = getAttribute(attributes, "multiple", valueOf(DEFAULT_MULTIPLE));
boolean ignoreUnknownFields =
getAttribute(attributes, "ignoreUnknownFields", valueOf(DEFAULT_IGNORE_UNKNOWN_FIELDS));
boolean ignoreInvalidFields =
getAttribute(attributes, "ignoreInvalidFields", valueOf(DEFAULT_IGNORE_INVALID_FIELDS));
registerConfigurationBeans(prefix, configClass, multiple, ignoreUnknownFields, ignoreInvalidFields, registry);
}
private void registerConfigurationBeans(
String prefix,
Class<?> configClass,
boolean multiple,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields,
BeanDefinitionRegistry registry) {
Map<String, Object> configurationProperties =
getSubProperties(environment.getPropertySources(), environment, prefix);
if (CollectionUtils.isEmpty(configurationProperties)) {
if (log.isDebugEnabled()) {
log.debug("There is no property for binding to configuration class [" + configClass.getName()
+ "] within prefix [" + prefix + "]");
}
return;
}
Set<String> beanNames = multiple
? resolveMultipleBeanNames(configurationProperties)
: singleton(resolveSingleBeanName(configurationProperties, configClass, registry));
for (String beanName : beanNames) {
registerConfigurationBean(
beanName,
configClass,
multiple,
ignoreUnknownFields,
ignoreInvalidFields,
configurationProperties,
registry);
}
registerConfigurationBindingBeanPostProcessor(registry);
}
private void registerConfigurationBean(
String beanName,
Class<?> configClass,
boolean multiple,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields,
Map<String, Object> configurationProperties,
BeanDefinitionRegistry registry) {
BeanDefinitionBuilder builder = rootBeanDefinition(configClass);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
setSource(beanDefinition);
Map<String, Object> subProperties = resolveSubProperties(multiple, beanName, configurationProperties);
initBeanMetadataAttributes(beanDefinition, subProperties, ignoreUnknownFields, ignoreInvalidFields);
registry.registerBeanDefinition(beanName, beanDefinition);
if (log.isInfoEnabled()) {
log.info("The configuration bean definition [name : " + beanName + ", content : " + beanDefinition
+ "] has been registered.");
}
}
private Map<String, Object> resolveSubProperties(
boolean multiple, String beanName, Map<String, Object> configurationProperties) {
if (!multiple) {
return configurationProperties;
}
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addLast(new MapPropertySource("_", configurationProperties));
return getSubProperties(propertySources, environment, normalizePrefix(beanName));
}
private void setSource(AbstractBeanDefinition beanDefinition) {
beanDefinition.setSource(ENABLE_CONFIGURATION_BINDING_CLASS);
}
private void registerConfigurationBindingBeanPostProcessor(BeanDefinitionRegistry registry) {
registerInfrastructureBean(
registry, ConfigurationBeanBindingPostProcessor.BEAN_NAME, ConfigurationBeanBindingPostProcessor.class);
}
@Override
public void setEnvironment(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
this.environment = (ConfigurableEnvironment) environment;
}
private Set<String> resolveMultipleBeanNames(Map<String, Object> properties) {
Set<String> beanNames = new LinkedHashSet<String>();
for (String propertyName : properties.keySet()) {
int index = propertyName.indexOf(".");
if (index > 0) {
String beanName = propertyName.substring(0, index);
beanNames.add(beanName);
}
}
return beanNames;
}
private String resolveSingleBeanName(
Map<String, Object> properties, Class<?> configClass, BeanDefinitionRegistry registry) {
String beanName = (String) properties.get("id");
if (!StringUtils.hasText(beanName)) {
BeanDefinitionBuilder builder = rootBeanDefinition(configClass);
beanName = BeanDefinitionReaderUtils.generateBeanName(builder.getRawBeanDefinition(), registry);
}
return beanName;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableConfigurationBeanBindings.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableConfigurationBeanBindings.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* The annotation composes the multiple {@link EnableConfigurationBeanBinding EnableConfigurationBeanBindings}
*
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ConfigurationBeanBindingsRegister.class)
public @interface EnableConfigurationBeanBindings {
/**
* @return the array of {@link EnableConfigurationBeanBinding EnableConfigurationBeanBindings}
*/
EnableConfigurationBeanBinding[] value();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingPostProcessor.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/ConfigurationBeanBindingPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.spring.context.config.ConfigurationBeanBinder;
import org.apache.dubbo.config.spring.context.config.ConfigurationBeanCustomizer;
import org.apache.dubbo.config.spring.context.config.DefaultConfigurationBeanBinder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.core.PriorityOrdered;
import static org.apache.dubbo.config.spring.context.annotation.ConfigurationBeanBindingRegistrar.ENABLE_CONFIGURATION_BINDING_CLASS;
import static org.apache.dubbo.config.spring.util.WrapperUtils.unwrap;
import static org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors;
import static org.springframework.core.annotation.AnnotationAwareOrderComparator.sort;
import static org.springframework.util.ClassUtils.getUserClass;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* The {@link BeanPostProcessor} class to bind the configuration bean
*
*/
@SuppressWarnings("unchecked")
public class ConfigurationBeanBindingPostProcessor implements BeanPostProcessor, BeanFactoryAware, PriorityOrdered {
/**
* The bean name of {@link ConfigurationBeanBindingPostProcessor}
*/
public static final String BEAN_NAME = "configurationBeanBindingPostProcessor";
static final String CONFIGURATION_PROPERTIES_ATTRIBUTE_NAME = "configurationProperties";
static final String IGNORE_UNKNOWN_FIELDS_ATTRIBUTE_NAME = "ignoreUnknownFields";
static final String IGNORE_INVALID_FIELDS_ATTRIBUTE_NAME = "ignoreInvalidFields";
private final Log log = LogFactory.getLog(getClass());
private ConfigurableListableBeanFactory beanFactory = null;
private ConfigurationBeanBinder configurationBeanBinder = null;
private List<ConfigurationBeanCustomizer> configurationBeanCustomizers = null;
private int order = LOWEST_PRECEDENCE;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
BeanDefinition beanDefinition = getNullableBeanDefinition(beanName);
if (isConfigurationBean(bean, beanDefinition)) {
bindConfigurationBean(bean, beanDefinition);
customize(beanName, bean);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* Set the order for current instance
*
* @param order the order
*/
public void setOrder(int order) {
this.order = order;
}
public ConfigurationBeanBinder getConfigurationBeanBinder() {
if (configurationBeanBinder == null) {
initConfigurationBeanBinder();
}
return configurationBeanBinder;
}
public void setConfigurationBeanBinder(ConfigurationBeanBinder configurationBeanBinder) {
this.configurationBeanBinder = configurationBeanBinder;
}
/**
* Get the {@link List} of {@link ConfigurationBeanCustomizer ConfigurationBeanCustomizers}
*
* @return non-null
*/
public List<ConfigurationBeanCustomizer> getConfigurationBeanCustomizers() {
if (configurationBeanCustomizers == null) {
initBindConfigurationBeanCustomizers();
}
return configurationBeanCustomizers;
}
public void setConfigurationBeanCustomizers(Collection<ConfigurationBeanCustomizer> configurationBeanCustomizers) {
List<ConfigurationBeanCustomizer> customizers =
new ArrayList<ConfigurationBeanCustomizer>(configurationBeanCustomizers);
sort(customizers);
this.configurationBeanCustomizers = Collections.unmodifiableList(customizers);
}
private BeanDefinition getNullableBeanDefinition(String beanName) {
return beanFactory.containsBeanDefinition(beanName) ? beanFactory.getBeanDefinition(beanName) : null;
}
private boolean isConfigurationBean(Object bean, BeanDefinition beanDefinition) {
return beanDefinition != null
&& ENABLE_CONFIGURATION_BINDING_CLASS.equals(beanDefinition.getSource())
&& nullSafeEquals(getBeanClassName(bean), beanDefinition.getBeanClassName());
}
private String getBeanClassName(Object bean) {
return getUserClass(bean.getClass()).getName();
}
private void bindConfigurationBean(Object configurationBean, BeanDefinition beanDefinition) {
Map<String, Object> configurationProperties = getConfigurationProperties(beanDefinition);
boolean ignoreUnknownFields = getIgnoreUnknownFields(beanDefinition);
boolean ignoreInvalidFields = getIgnoreInvalidFields(beanDefinition);
getConfigurationBeanBinder()
.bind(configurationProperties, ignoreUnknownFields, ignoreInvalidFields, configurationBean);
if (log.isInfoEnabled()) {
log.info("The configuration bean [" + configurationBean + "] have been binding by the "
+ "configuration properties [" + configurationProperties + "]");
}
}
private void initConfigurationBeanBinder() {
if (configurationBeanBinder == null) {
try {
configurationBeanBinder = beanFactory.getBean(ConfigurationBeanBinder.class);
} catch (BeansException ignored) {
if (log.isInfoEnabled()) {
log.info("configurationBeanBinder Bean can't be found in ApplicationContext.");
}
// Use Default implementation
configurationBeanBinder = defaultConfigurationBeanBinder();
}
}
}
private void initBindConfigurationBeanCustomizers() {
Collection<ConfigurationBeanCustomizer> customizers = beansOfTypeIncludingAncestors(
beanFactory, ConfigurationBeanCustomizer.class)
.values();
setConfigurationBeanCustomizers(customizers);
}
private void customize(String beanName, Object configurationBean) {
for (ConfigurationBeanCustomizer customizer : getConfigurationBeanCustomizers()) {
customizer.customize(beanName, configurationBean);
}
}
/**
* Create {@link ConfigurationBeanBinder} instance.
*
* @return {@link DefaultConfigurationBeanBinder}
*/
private ConfigurationBeanBinder defaultConfigurationBeanBinder() {
return new DefaultConfigurationBeanBinder();
}
static void initBeanMetadataAttributes(
AbstractBeanDefinition beanDefinition,
Map<String, Object> configurationProperties,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields) {
beanDefinition.setAttribute(CONFIGURATION_PROPERTIES_ATTRIBUTE_NAME, configurationProperties);
beanDefinition.setAttribute(IGNORE_UNKNOWN_FIELDS_ATTRIBUTE_NAME, ignoreUnknownFields);
beanDefinition.setAttribute(IGNORE_INVALID_FIELDS_ATTRIBUTE_NAME, ignoreInvalidFields);
}
private static <T> T getAttribute(BeanDefinition beanDefinition, String attributeName) {
return (T) beanDefinition.getAttribute(attributeName);
}
private static Map<String, Object> getConfigurationProperties(BeanDefinition beanDefinition) {
return getAttribute(beanDefinition, CONFIGURATION_PROPERTIES_ATTRIBUTE_NAME);
}
private static boolean getIgnoreUnknownFields(BeanDefinition beanDefinition) {
return getAttribute(beanDefinition, IGNORE_UNKNOWN_FIELDS_ATTRIBUTE_NAME);
}
private static boolean getIgnoreInvalidFields(BeanDefinition beanDefinition) {
return getAttribute(beanDefinition, IGNORE_INVALID_FIELDS_ATTRIBUTE_NAME);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = unwrap(beanFactory);
}
@Override
public int getOrder() {
return order;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.spring.aot.AotWithSpringDetector;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import static org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors;
/**
* Dubbo {@link ClassPathBeanDefinitionScanner} that exposes some methods to be public.
*
* @see #doScan(String...)
* @see #registerDefaultFilters()
* @since 2.5.7
*/
public class DubboClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {
/**
* key is package to scan, value is BeanDefinition
*/
private final ConcurrentMap<String, Set<BeanDefinition>> beanDefinitionMap = new ConcurrentHashMap<>();
public DubboClassPathBeanDefinitionScanner(
BeanDefinitionRegistry registry,
boolean useDefaultFilters,
Environment environment,
ResourceLoader resourceLoader) {
super(registry, useDefaultFilters);
setEnvironment(environment);
setResourceLoader(resourceLoader);
if (!AotWithSpringDetector.useGeneratedArtifacts()) {
registerAnnotationConfigProcessors(registry);
}
}
public DubboClassPathBeanDefinitionScanner(
BeanDefinitionRegistry registry, Environment environment, ResourceLoader resourceLoader) {
this(registry, false, environment, resourceLoader);
}
@Override
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
Set<BeanDefinition> beanDefinitions = beanDefinitionMap.get(basePackage);
// if beanDefinitions size is null => scan
if (Objects.isNull(beanDefinitions)) {
beanDefinitions = super.findCandidateComponents(basePackage);
beanDefinitionMap.put(basePackage, beanDefinitions);
}
return beanDefinitions;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.java | /*
* 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 org.apache.dubbo.config.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.springframework.context.annotation.Configuration;
/**
* Dubbo {@link AbstractConfig Config} {@link Configuration}
*
* @revised 2.7.5
* @see Configuration
* @see EnableConfigurationBeanBindings
* @see EnableConfigurationBeanBinding
* @see ApplicationConfig
* @see ModuleConfig
* @see RegistryConfig
* @see ProtocolConfig
* @see MonitorConfig
* @see ProviderConfig
* @see ConsumerConfig
* @see org.apache.dubbo.config.ConfigCenterConfig
* @since 2.5.8
*/
public class DubboConfigConfiguration {
/**
* Single Dubbo {@link AbstractConfig Config} Bean Binding
*/
@EnableConfigurationBeanBindings({
@EnableConfigurationBeanBinding(prefix = "dubbo.application", type = ApplicationConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.module", type = ModuleConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.registry", type = RegistryConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.protocol", type = ProtocolConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.monitor", type = MonitorConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.provider", type = ProviderConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.config-center", type = ConfigCenterBean.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.metadata-report", type = MetadataReportConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.metrics", type = MetricsConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.tracing", type = TracingConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.ssl", type = SslConfig.class)
})
public static class Single {}
/**
* Multiple Dubbo {@link AbstractConfig Config} Bean Binding
*/
@EnableConfigurationBeanBindings({
@EnableConfigurationBeanBinding(prefix = "dubbo.applications", type = ApplicationConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.modules", type = ModuleConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.registries", type = RegistryConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.protocols", type = ProtocolConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.monitors", type = MonitorConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.providers", type = ProviderConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.consumers", type = ConsumerConfig.class, multiple = true),
@EnableConfigurationBeanBinding(
prefix = "dubbo.config-centers",
type = ConfigCenterBean.class,
multiple = true),
@EnableConfigurationBeanBinding(
prefix = "dubbo.metadata-reports",
type = MetadataReportConfig.class,
multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.metricses", type = MetricsConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.tracings", type = TracingConfig.class, multiple = true)
})
public static class Multiple {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/DubboConfigBeanCustomizer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/DubboConfigBeanCustomizer.java | /*
* 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 org.apache.dubbo.config.spring.context.config;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
/**
* The Bean customizer for {@link AbstractConfig Dubbo Config}. Generally, The subclass will be registered as a Spring
* Bean that is used to {@link #customize(String, AbstractConfig) customize} {@link AbstractConfig Dubbo Config} bean
* after {@link DubboConfigBinder#bind(String, AbstractConfig) its binding}.
* <p>
* If There are multiple {@link DubboConfigBeanCustomizer} beans in the Spring {@link ApplicationContext context}, they
* are executed orderly, thus the subclass should be aware to implement the {@link #getOrder()} method.
*
* @see DubboConfigBinder#bind(String, AbstractConfig)
* @since 2.6.6
*/
public interface DubboConfigBeanCustomizer extends ConfigurationBeanCustomizer, Ordered {
/**
* Customize {@link AbstractConfig Dubbo Config Bean}
*
* @param beanName the name of {@link AbstractConfig Dubbo Config Bean}
* @param dubboConfigBean the instance of {@link AbstractConfig Dubbo Config Bean}
*/
void customize(String beanName, AbstractConfig dubboConfigBean);
@Override
default void customize(String beanName, Object configurationBean) {
if (configurationBean instanceof AbstractConfig) {
customize(beanName, (AbstractConfig) configurationBean);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/DefaultConfigurationBeanBinder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/DefaultConfigurationBeanBinder.java | /*
* 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 org.apache.dubbo.config.spring.context.config;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.DataBinder;
/**
* The default {@link ConfigurationBeanBinder} implementation
*
* @see ConfigurationBeanBinder
*/
public class DefaultConfigurationBeanBinder implements ConfigurationBeanBinder {
@Override
public void bind(
Map<String, Object> configurationProperties,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields,
Object configurationBean) {
DataBinder dataBinder = new DataBinder(configurationBean);
// Set ignored*
dataBinder.setIgnoreInvalidFields(ignoreUnknownFields);
dataBinder.setIgnoreUnknownFields(ignoreInvalidFields);
// Get properties under specified prefix from PropertySources
// Convert Map to MutablePropertyValues
MutablePropertyValues propertyValues = new MutablePropertyValues(configurationProperties);
// Bind
dataBinder.bind(propertyValues);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/ConfigurationBeanBinder.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/ConfigurationBeanBinder.java | /*
* 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 org.apache.dubbo.config.spring.context.config;
import org.apache.dubbo.config.spring.context.annotation.EnableConfigurationBeanBinding;
import java.util.Map;
import org.springframework.core.env.Environment;
/**
* The binder for the configuration bean
*
*/
public interface ConfigurationBeanBinder {
/**
* Bind the properties in the {@link Environment} to Configuration bean under specified prefix.
*
* @param configurationProperties The configuration properties
* @param ignoreUnknownFields whether to ignore unknown fields, the value is come
* from the attribute of {@link EnableConfigurationBeanBinding#ignoreUnknownFields()}
* @param ignoreInvalidFields whether to ignore invalid fields, the value is come
* from the attribute of {@link EnableConfigurationBeanBinding#ignoreInvalidFields()}
* @param configurationBean the bean of configuration
*/
void bind(
Map<String, Object> configurationProperties,
boolean ignoreUnknownFields,
boolean ignoreInvalidFields,
Object configurationBean);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.java | /*
* 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 org.apache.dubbo.config.spring.context.config;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.beans.factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor;
import org.apache.dubbo.config.spring.util.ObjectUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.util.ReflectionUtils;
import static org.springframework.beans.BeanUtils.getPropertyDescriptor;
/**
* {@link DubboConfigBeanCustomizer} for the default value for the "name" property that will be taken bean name
* if absent.
*
* @since 2.6.6
* @deprecated {@link DubboConfigDefaultPropertyValueBeanPostProcessor} instead
*/
@Deprecated
public class NamePropertyDefaultValueDubboConfigBeanCustomizer implements DubboConfigBeanCustomizer {
/**
* The bean name of {@link NamePropertyDefaultValueDubboConfigBeanCustomizer}
*
* @since 2.7.1
*/
public static final String BEAN_NAME = "namePropertyDefaultValueDubboConfigBeanCustomizer";
/**
* The name of property that is "name" maybe is absent in target class
*/
private static final String PROPERTY_NAME = "name";
@Override
public void customize(String beanName, AbstractConfig dubboConfigBean) {
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dubboConfigBean.getClass(), PROPERTY_NAME);
if (propertyDescriptor != null) { // "name" property is present
Method getNameMethod = propertyDescriptor.getReadMethod();
if (getNameMethod == null) { // if "getName" method is absent
return;
}
Object propertyValue = ReflectionUtils.invokeMethod(getNameMethod, dubboConfigBean);
if (propertyValue != null) { // If The return value of "getName" method is not null
return;
}
Method setNameMethod = propertyDescriptor.getWriteMethod();
if (setNameMethod != null) { // "setName" and "getName" methods are present
if (Arrays.equals(
ObjectUtils.of(String.class), setNameMethod.getParameterTypes())) { // the param type is String
// set bean name to the value of the "name" property
ReflectionUtils.invokeMethod(setNameMethod, dubboConfigBean, beanName);
}
}
}
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/ConfigurationBeanCustomizer.java | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/ConfigurationBeanCustomizer.java | /*
* 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 org.apache.dubbo.config.spring.context.config;
import org.apache.dubbo.config.spring.context.annotation.ConfigurationBeanBindingPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
/**
* The customizer for the configuration bean after {@link ConfigurationBeanBinder#bind its binding}.
* <p>
* If There are multiple {@link ConfigurationBeanCustomizer} beans in the Spring {@link ApplicationContext context},
* they are executed orderly, thus the subclass should be aware to implement the {@link #getOrder()} method.
*
* @see ConfigurationBeanBinder
* @see ConfigurationBeanBindingPostProcessor
*/
public interface ConfigurationBeanCustomizer extends Ordered {
/**
* Customize the configuration bean
*
* @param beanName the name of the configuration bean
* @param configurationBean the configuration bean
*/
void customize(String beanName, Object configurationBean);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoB.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoB.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class DemoB implements Serializable {
private DemoA a;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoA.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoA.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class DemoA implements Serializable {
private DemoB b;
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequestSuper.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class HelloRequestSuper implements Serializable {
private String su;
public HelloRequestSuper() {}
public HelloRequestSuper(String su) {
this.su = su;
}
public String getSu() {
return su;
}
public void setSu(String su) {
this.su = su;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/SexEnum.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/SexEnum.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
public enum SexEnum {
BOY("boy"),
GIRL("girl");
private final String desc;
SexEnum(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/Person.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/Person.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private SexEnum sex;
public Person(String name, SexEnum sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SexEnum getSex() {
return sex;
}
public void setSex(SexEnum sex) {
this.sex = sex;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/DemoService.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
public interface DemoService {
HelloResponse sayHello(HelloRequest request);
String sayHelloForSerializable(java.io.Serializable name);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloRequest.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class HelloRequest extends HelloRequestSuper implements Serializable {
private Person person;
public HelloRequest(Person person) {
this.person = person;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/AotUtilsTest.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.RuntimeHints;
public class AotUtilsTest {
@Test
void registerSerializationForServiceTest() {
RuntimeHints runtimeHints = new RuntimeHints();
AotUtils.registerSerializationForService(DemoService.class, runtimeHints);
AtomicBoolean containHelloRequest = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(HelloRequest.class.getName())) {
containHelloRequest.set(true);
}
});
AtomicBoolean containPerson = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(HelloRequest.class.getName())) {
containPerson.set(true);
}
});
AtomicBoolean containString = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(HelloRequest.class.getName())) {
containString.set(true);
}
});
AtomicBoolean containHelloRequestSuper = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(HelloRequest.class.getName())) {
containHelloRequestSuper.set(true);
}
});
AtomicBoolean containHelloResponse = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(HelloRequest.class.getName())) {
containHelloResponse.set(true);
}
});
Assertions.assertTrue(containHelloRequest.get());
Assertions.assertTrue(containPerson.get());
Assertions.assertTrue(containString.get());
Assertions.assertTrue(containHelloRequestSuper.get());
Assertions.assertTrue(containHelloResponse.get());
}
@Test
void registerSerializationForCircularDependencyFieldTest() {
RuntimeHints runtimeHints = new RuntimeHints();
AotUtils.registerSerializationForService(CircularDependencyDemoService.class, runtimeHints);
AtomicBoolean containDemoA = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(DemoA.class.getName())) {
containDemoA.set(true);
}
});
AtomicBoolean containDemoB = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(DemoB.class.getName())) {
containDemoB.set(true);
}
});
Assertions.assertTrue(containDemoA.get());
Assertions.assertTrue(containDemoB.get());
AotUtils.registerSerializationForService(DemoService.class, runtimeHints);
AtomicBoolean containSexEnum = new AtomicBoolean(false);
runtimeHints.serialization().javaSerializationHints().forEach(s -> {
if (s.getType().getName().equals(SexEnum.class.getName())) {
containSexEnum.set(true);
}
});
Assertions.assertTrue(containSexEnum.get());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/CircularDependencyDemoService.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/CircularDependencyDemoService.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
public interface CircularDependencyDemoService {
String sayHello(DemoA a);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java | dubbo-config/dubbo-config-spring6/src/test/java/org/apache/dubbo/config/spring6/utils/HelloResponse.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import java.io.Serializable;
public class HelloResponse implements Serializable {
private String response;
public HelloResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedFieldValueResolver.java | /*
* 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 org.apache.dubbo.config.spring6.beans.factory.aot;
import org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor;
import java.lang.reflect.Field;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.function.ThrowingConsumer;
/**
* Resolver used to support the autowiring of fields. Typically used in
* AOT-processed applications as a targeted alternative to the
* {@link ReferenceAnnotationWithAotBeanPostProcessor
* ReferenceAnnotationBeanPostProcessor}.
*
* <p>When resolving arguments in a native image, the {@link Field} being used must
* be marked with an {@link ExecutableMode#INTROSPECT introspection} hint so
* that field annotations can be read. Full {@link ExecutableMode#INVOKE
* invocation} hints are only required if the
* {@link #resolveAndSet(RegisteredBean, Object)} method of this class is being
* used (typically to support private fields).
*/
public final class ReferencedFieldValueResolver extends AutowiredElementResolver {
private final String fieldName;
private final boolean required;
@Nullable
private final String shortcut;
private ReferencedFieldValueResolver(String fieldName, boolean required, @Nullable String shortcut) {
Assert.hasText(fieldName, "'fieldName' must not be empty");
this.fieldName = fieldName;
this.required = required;
this.shortcut = shortcut;
}
/**
* Create a new {@link ReferencedFieldValueResolver} for the specified field
* where injection is optional.
*
* @param fieldName the field name
* @return a new {@link ReferencedFieldValueResolver} instance
*/
public static ReferencedFieldValueResolver forField(String fieldName) {
return new ReferencedFieldValueResolver(fieldName, false, null);
}
/**
* Create a new {@link ReferencedFieldValueResolver} for the specified field
* where injection is required.
*
* @param fieldName the field name
* @return a new {@link ReferencedFieldValueResolver} instance
*/
public static ReferencedFieldValueResolver forRequiredField(String fieldName) {
return new ReferencedFieldValueResolver(fieldName, true, null);
}
/**
* Return a new {@link ReferencedFieldValueResolver} instance that uses a
* direct bean name injection shortcut.
*
* @param beanName the bean name to use as a shortcut
* @return a new {@link ReferencedFieldValueResolver} instance that uses the
* shortcuts
*/
public ReferencedFieldValueResolver withShortcut(String beanName) {
return new ReferencedFieldValueResolver(this.fieldName, this.required, beanName);
}
/**
* Resolve the field for the specified registered bean and provide it to the
* given action.
*
* @param registeredBean the registered bean
* @param action the action to execute with the resolved field value
*/
public <T> void resolve(RegisteredBean registeredBean, ThrowingConsumer<T> action) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
Assert.notNull(action, "'action' must not be null");
T resolved = resolve(registeredBean);
if (resolved != null) {
action.accept(resolved);
}
}
/**
* Resolve the field value for the specified registered bean.
*
* @param registeredBean the registered bean
* @param requiredType the required type
* @return the resolved field value
*/
@Nullable
@SuppressWarnings("unchecked")
public <T> T resolve(RegisteredBean registeredBean, Class<T> requiredType) {
Object value = resolveObject(registeredBean);
Assert.isInstanceOf(requiredType, value);
return (T) value;
}
/**
* Resolve the field value for the specified registered bean.
*
* @param registeredBean the registered bean
* @return the resolved field value
*/
@Nullable
@SuppressWarnings("unchecked")
public <T> T resolve(RegisteredBean registeredBean) {
return (T) resolveObject(registeredBean);
}
/**
* Resolve the field value for the specified registered bean.
*
* @param registeredBean the registered bean
* @return the resolved field value
*/
@Nullable
public Object resolveObject(RegisteredBean registeredBean) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
return resolveValue(registeredBean, getField(registeredBean));
}
/**
* Resolve the field value for the specified registered bean and set it
* using reflection.
*
* @param registeredBean the registered bean
* @param instance the bean instance
*/
public void resolveAndSet(RegisteredBean registeredBean, Object instance) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
Assert.notNull(instance, "'instance' must not be null");
Field field = getField(registeredBean);
Object resolved = resolveValue(registeredBean, field);
if (resolved != null) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, instance, resolved);
}
}
@Nullable
private Object resolveValue(RegisteredBean registeredBean, Field field) {
String beanName = registeredBean.getBeanName();
Class<?> beanClass = registeredBean.getBeanClass();
ConfigurableBeanFactory beanFactory = registeredBean.getBeanFactory();
DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required);
descriptor.setContainingClass(beanClass);
if (this.shortcut != null) {
descriptor = new ShortcutDependencyDescriptor(descriptor, this.shortcut, field.getType());
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
Assert.isInstanceOf(AutowireCapableBeanFactory.class, beanFactory);
Object injectedObject = beanFactory.getBean(shortcut);
Object value = ((AutowireCapableBeanFactory) beanFactory)
.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter);
registerDependentBeans(beanFactory, beanName, autowiredBeanNames);
return injectedObject;
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
}
private Field getField(RegisteredBean registeredBean) {
Field field = ReflectionUtils.findField(registeredBean.getBeanClass(), this.fieldName);
Assert.notNull(
field,
() -> "No field '" + this.fieldName + "' found on "
+ registeredBean.getBeanClass().getName());
return field;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/AutowiredElementResolver.java | /*
* 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 org.apache.dubbo.config.spring6.beans.factory.aot;
import javax.lang.model.element.Element;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.core.log.LogMessage;
/**
* Base class for resolvers that support autowiring related to an
* {@link Element}.
*/
abstract class AutowiredElementResolver {
private final Log logger = LogFactory.getLog(getClass());
protected final void registerDependentBeans(
ConfigurableBeanFactory beanFactory, String beanName, Set<String> autowiredBeanNames) {
for (String autowiredBeanName : autowiredBeanNames) {
if (beanFactory.containsBean(autowiredBeanName)) {
beanFactory.registerDependentBean(autowiredBeanName, beanName);
}
logger.trace(LogMessage.format(
"Autowiring by type from bean name %s' to bean named '%s'", beanName, autowiredBeanName));
}
}
/**
* {@link DependencyDescriptor} that supports shortcut bean resolution.
*/
@SuppressWarnings("serial")
static class ShortcutDependencyDescriptor extends DependencyDescriptor {
private final String shortcut;
private final Class<?> requiredType;
public ShortcutDependencyDescriptor(DependencyDescriptor original, String shortcut, Class<?> requiredType) {
super(original);
this.shortcut = shortcut;
this.requiredType = requiredType;
}
@Override
public Object resolveShortcut(BeanFactory beanFactory) {
return beanFactory.getBean(this.shortcut, this.requiredType);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/aot/ReferencedMethodArgumentsResolver.java | /*
* 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 org.apache.dubbo.config.spring6.beans.factory.aot;
import org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.beans.BeansException;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.aot.AutowiredArguments;
import org.springframework.beans.factory.aot.AutowiredFieldValueResolver;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.function.ThrowingConsumer;
/**
* Resolver used to support the autowiring of methods. Typically used in
* AOT-processed applications as a targeted alternative to the
* {@link ReferenceAnnotationWithAotBeanPostProcessor
* ReferenceAnnotationBeanPostProcessor}.
*
* <p>When resolving arguments in a native image, the {@link Method} being used
* must be marked with an {@link ExecutableMode#INTROSPECT introspection} hint
* so that field annotations can be read. Full {@link ExecutableMode#INVOKE
* invocation} hints are only required if the
* {@link #resolveAndInvoke(RegisteredBean, Object)} method of this class is
* being used (typically to support private methods).
*/
public final class ReferencedMethodArgumentsResolver extends AutowiredElementResolver {
private final String methodName;
private final Class<?>[] parameterTypes;
private final boolean required;
@Nullable
private final String[] shortcuts;
private ReferencedMethodArgumentsResolver(
String methodName, Class<?>[] parameterTypes, boolean required, @Nullable String[] shortcuts) {
Assert.hasText(methodName, "'methodName' must not be empty");
this.methodName = methodName;
this.parameterTypes = parameterTypes;
this.required = required;
this.shortcuts = shortcuts;
}
/**
* Create a new {@link ReferencedMethodArgumentsResolver} for the specified
* method where injection is optional.
*
* @param methodName the method name
* @param parameterTypes the factory method parameter types
* @return a new {@link org.springframework.beans.factory.aot.AutowiredFieldValueResolver} instance
*/
public static ReferencedMethodArgumentsResolver forMethod(String methodName, Class<?>... parameterTypes) {
return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, false, null);
}
/**
* Create a new {@link ReferencedMethodArgumentsResolver} for the specified
* method where injection is required.
*
* @param methodName the method name
* @param parameterTypes the factory method parameter types
* @return a new {@link AutowiredFieldValueResolver} instance
*/
public static ReferencedMethodArgumentsResolver forRequiredMethod(String methodName, Class<?>... parameterTypes) {
return new ReferencedMethodArgumentsResolver(methodName, parameterTypes, true, null);
}
/**
* Return a new {@link ReferencedMethodArgumentsResolver} instance
* that uses direct bean name injection shortcuts for specific parameters.
*
* @param beanNames the bean names to use as shortcuts (aligned with the
* method parameters)
* @return a new {@link ReferencedMethodArgumentsResolver} instance that uses
* the shortcuts
*/
public ReferencedMethodArgumentsResolver withShortcut(String... beanNames) {
return new ReferencedMethodArgumentsResolver(this.methodName, this.parameterTypes, this.required, beanNames);
}
/**
* Resolve the method arguments for the specified registered bean and
* provide it to the given action.
*
* @param registeredBean the registered bean
* @param action the action to execute with the resolved method arguments
*/
public void resolve(RegisteredBean registeredBean, ThrowingConsumer<AutowiredArguments> action) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
Assert.notNull(action, "'action' must not be null");
AutowiredArguments resolved = resolve(registeredBean);
if (resolved != null) {
action.accept(resolved);
}
}
/**
* Resolve the method arguments for the specified registered bean.
*
* @param registeredBean the registered bean
* @return the resolved method arguments
*/
@Nullable
public AutowiredArguments resolve(RegisteredBean registeredBean) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
return resolveArguments(registeredBean, getMethod(registeredBean));
}
/**
* Resolve the method arguments for the specified registered bean and invoke
* the method using reflection.
*
* @param registeredBean the registered bean
* @param instance the bean instance
*/
public void resolveAndInvoke(RegisteredBean registeredBean, Object instance) {
Assert.notNull(registeredBean, "'registeredBean' must not be null");
Assert.notNull(instance, "'instance' must not be null");
Method method = getMethod(registeredBean);
AutowiredArguments resolved = resolveArguments(registeredBean, method);
if (resolved != null) {
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, instance, resolved.toArray());
}
}
@Nullable
private AutowiredArguments resolveArguments(RegisteredBean registeredBean, Method method) {
String beanName = registeredBean.getBeanName();
Class<?> beanClass = registeredBean.getBeanClass();
ConfigurableBeanFactory beanFactory = registeredBean.getBeanFactory();
Assert.isInstanceOf(AutowireCapableBeanFactory.class, beanFactory);
AutowireCapableBeanFactory autowireCapableBeanFactory = (AutowireCapableBeanFactory) beanFactory;
int argumentCount = method.getParameterCount();
Object[] arguments = new Object[argumentCount];
Set<String> autowiredBeanNames = new LinkedHashSet<>(argumentCount);
TypeConverter typeConverter = beanFactory.getTypeConverter();
for (int i = 0; i < argumentCount; i++) {
MethodParameter parameter = new MethodParameter(method, i);
DependencyDescriptor descriptor = new DependencyDescriptor(parameter, this.required);
descriptor.setContainingClass(beanClass);
String shortcut = (this.shortcuts != null) ? this.shortcuts[i] : null;
if (shortcut != null) {
descriptor = new ShortcutDependencyDescriptor(descriptor, shortcut, parameter.getParameterType());
}
try {
Object injectedArgument = beanFactory.getBean(shortcut);
Object argument = autowireCapableBeanFactory.resolveDependency(
descriptor, beanName, autowiredBeanNames, typeConverter);
arguments[i] = injectedArgument;
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(parameter), ex);
}
}
registerDependentBeans(beanFactory, beanName, autowiredBeanNames);
return AutowiredArguments.of(arguments);
}
private Method getMethod(RegisteredBean registeredBean) {
Method method = ReflectionUtils.findMethod(registeredBean.getBeanClass(), this.methodName, this.parameterTypes);
Assert.notNull(
method,
() -> "Method '" + this.methodName + "' with parameter types ["
+ toCommaSeparatedNames(this.parameterTypes) + "] declared on "
+ registeredBean.getBeanClass().getName() + " could not be found.");
return method;
}
private String toCommaSeparatedNames(Class<?>... parameterTypes) {
return Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining(", "));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ServiceAnnotationWithAotPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring6.beans.factory.annotation;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor;
import org.apache.dubbo.config.spring.schema.AnnotationBeanDefinitionParser;
import org.apache.dubbo.config.spring6.utils.AotUtils;
import java.util.Collection;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.TypeReference;
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationCode;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
/**
* The purpose of implementing {@link BeanRegistrationAotProcessor} is to
* supplement for {@link ServiceAnnotationPostProcessor} ability of AOT.
*
* @see AnnotationBeanDefinitionParser
* @see BeanDefinitionRegistryPostProcessor
* @since 3.3
*/
public class ServiceAnnotationWithAotPostProcessor extends ServiceAnnotationPostProcessor
implements BeanRegistrationAotProcessor {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
public ServiceAnnotationWithAotPostProcessor(String... packagesToScan) {
super(packagesToScan);
}
public ServiceAnnotationWithAotPostProcessor(Collection<?> packagesToScan) {
super(packagesToScan);
}
@Override
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
Class<?> beanClass = registeredBean.getBeanClass();
if (beanClass.equals(ServiceBean.class)) {
RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition();
String interfaceName = (String) beanDefinition.getPropertyValues().get("interface");
try {
Class<?> c = Class.forName(interfaceName);
return new DubboServiceBeanRegistrationAotContribution(c);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else if (servicePackagesHolder.isClassScanned(beanClass.getName())) {
return new DubboServiceBeanRegistrationAotContribution(beanClass);
}
return null;
}
private static class DubboServiceBeanRegistrationAotContribution implements BeanRegistrationAotContribution {
private final Class<?> cl;
public DubboServiceBeanRegistrationAotContribution(Class<?> cl) {
this.cl = cl;
}
@Override
public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) {
generationContext
.getRuntimeHints()
.reflection()
.registerType(TypeReference.of(cl), MemberCategory.INVOKE_PUBLIC_METHODS);
AotUtils.registerSerializationForService(cl, generationContext.getRuntimeHints());
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/beans/factory/annotation/ReferenceAnnotationWithAotBeanPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring6.beans.factory.annotation;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent;
import org.apache.dubbo.config.spring.util.SpringCompatUtils;
import org.apache.dubbo.config.spring6.beans.factory.aot.ReferencedFieldValueResolver;
import org.apache.dubbo.config.spring6.beans.factory.aot.ReferencedMethodArgumentsResolver;
import org.apache.dubbo.config.spring6.utils.AotUtils;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.service.EchoService;
import org.apache.dubbo.rpc.service.GenericService;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import org.springframework.aop.SpringProxy;
import org.springframework.aop.framework.Advised;
import org.springframework.aot.generate.AccessControl;
import org.springframework.aot.generate.GeneratedClass;
import org.springframework.aot.generate.GeneratedMethod;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.aot.hint.support.ClassHintUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.aot.AutowiredArgumentsCodeGenerator;
import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationCode;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.AutowireCandidateResolver;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.DecoratingProxy;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.javapoet.ClassName;
import org.springframework.javapoet.CodeBlock;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER;
/**
* The purpose of implementing {@link BeanRegistrationAotProcessor} is to
* supplement for {@link ReferenceAnnotationBeanPostProcessor} ability of AOT.
*
* @since 3.3
*/
public class ReferenceAnnotationWithAotBeanPostProcessor extends ReferenceAnnotationBeanPostProcessor
implements BeanRegistrationAotProcessor {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
@Nullable
private ConfigurableListableBeanFactory beanFactory;
/**
* {@link com.alibaba.dubbo.config.annotation.Reference @com.alibaba.dubbo.config.annotation.Reference} has been supported since 2.7.3
* <p>
* {@link DubboReference @DubboReference} has been supported since 2.7.7
*/
public ReferenceAnnotationWithAotBeanPostProcessor() {
super();
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] beanNames = beanFactory.getBeanDefinitionNames();
for (String beanName : beanNames) {
Class<?> beanType;
if (beanFactory.isFactoryBean(beanName)) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
if (isReferenceBean(beanDefinition)) {
continue;
}
if (isAnnotatedReferenceBean(beanDefinition)) {
// process @DubboReference at java-config @bean method
processReferenceAnnotatedBeanDefinition(beanName, (AnnotatedBeanDefinition) beanDefinition);
continue;
}
String beanClassName = beanDefinition.getBeanClassName();
beanType = ClassUtils.resolveClass(beanClassName, getClassLoader());
} else {
beanType = beanFactory.getType(beanName);
}
if (beanType != null) {
AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null);
try {
prepareInjection(metadata);
} catch (BeansException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Prepare dubbo reference injection element failed", e);
}
}
}
try {
// this is an early event, it will be notified at
// org.springframework.context.support.AbstractApplicationContext.registerListeners()
applicationContext.publishEvent(new DubboConfigInitEvent(applicationContext));
} catch (Exception e) {
// if spring version is less than 4.2, it does not support early application event
logger.warn(
CONFIG_DUBBO_BEAN_INITIALIZER,
"",
"",
"publish early application event failed, please upgrade spring version to 4.2.x or later: " + e);
}
}
/**
* check whether is @DubboReference at java-config @bean method
*/
private boolean isAnnotatedReferenceBean(BeanDefinition beanDefinition) {
if (beanDefinition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
String beanClassName = SpringCompatUtils.getFactoryMethodReturnType(annotatedBeanDefinition);
if (beanClassName != null && ReferenceBean.class.getName().equals(beanClassName)) {
return true;
}
}
return false;
}
private boolean isReferenceBean(BeanDefinition beanDefinition) {
return ReferenceBean.class.getName().equals(beanDefinition.getBeanClassName());
}
@Override
@Nullable
public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
Class<?> beanClass = registeredBean.getBeanClass();
String beanName = registeredBean.getBeanName();
RootBeanDefinition beanDefinition = registeredBean.getMergedBeanDefinition();
AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanDefinition, beanClass, beanName);
if (!CollectionUtils.isEmpty(metadata.getFieldElements())
|| !CollectionUtils.isEmpty(metadata.getMethodElements())) {
return new AotContribution(beanClass, metadata, getAutowireCandidateResolver());
}
return null;
}
private AnnotatedInjectionMetadata findInjectionMetadata(
RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
return metadata;
}
@Nullable
private AutowireCandidateResolver getAutowireCandidateResolver() {
if (this.beanFactory instanceof DefaultListableBeanFactory) {
return ((DefaultListableBeanFactory) this.beanFactory).getAutowireCandidateResolver();
}
return null;
}
private static class AotContribution implements BeanRegistrationAotContribution {
private static final String REGISTERED_BEAN_PARAMETER = "registeredBean";
private static final String INSTANCE_PARAMETER = "instance";
private final Class<?> target;
private final AnnotatedInjectionMetadata annotatedInjectionMetadata;
@Nullable
private final AutowireCandidateResolver candidateResolver;
AotContribution(
Class<?> target,
AnnotatedInjectionMetadata annotatedInjectionMetadata,
AutowireCandidateResolver candidateResolver) {
this.target = target;
this.annotatedInjectionMetadata = annotatedInjectionMetadata;
this.candidateResolver = candidateResolver;
}
@Override
public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) {
GeneratedClass generatedClass = generationContext
.getGeneratedClasses()
.addForFeatureComponent("DubboReference", this.target, type -> {
type.addJavadoc("DubboReference for {@link $T}.", this.target);
type.addModifiers(javax.lang.model.element.Modifier.PUBLIC);
});
GeneratedMethod generateMethod = generatedClass.getMethods().add("apply", method -> {
method.addJavadoc("Apply the dubbo reference.");
method.addModifiers(javax.lang.model.element.Modifier.PUBLIC, javax.lang.model.element.Modifier.STATIC);
method.addParameter(RegisteredBean.class, REGISTERED_BEAN_PARAMETER);
method.addParameter(this.target, INSTANCE_PARAMETER);
method.returns(this.target);
method.addCode(generateMethodCode(generatedClass.getName(), generationContext.getRuntimeHints()));
});
beanRegistrationCode.addInstancePostProcessor(generateMethod.toMethodReference());
if (this.candidateResolver != null) {
registerHints(generationContext.getRuntimeHints());
}
}
private CodeBlock generateMethodCode(ClassName targetClassName, RuntimeHints hints) {
CodeBlock.Builder code = CodeBlock.builder();
if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getFieldElements())) {
for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getFieldElements()) {
code.addStatement(generateStatementForElement(targetClassName, referenceElement, hints));
}
}
if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getMethodElements())) {
for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getMethodElements()) {
code.addStatement(generateStatementForElement(targetClassName, referenceElement, hints));
}
}
code.addStatement("return $L", INSTANCE_PARAMETER);
return code.build();
}
private CodeBlock generateStatementForElement(
ClassName targetClassName, AnnotatedInjectElement referenceElement, RuntimeHints hints) {
Member member = referenceElement.getMember();
AnnotationAttributes attributes = referenceElement.attributes;
Object injectedObject = referenceElement.injectedObject;
try {
Class<?> c = referenceElement.getInjectedType();
AotUtils.registerSerializationForService(c, hints);
hints.reflection().registerType(TypeReference.of(c), MemberCategory.INVOKE_PUBLIC_METHODS);
// need to enumerate all interfaces by the proxy
hints.proxies().registerJdkProxy(c, EchoService.class, Destroyable.class);
hints.proxies().registerJdkProxy(c, EchoService.class, Destroyable.class, GenericService.class);
hints.proxies()
.registerJdkProxy(
c,
EchoService.class,
Destroyable.class,
SpringProxy.class,
Advised.class,
DecoratingProxy.class);
hints.proxies()
.registerJdkProxy(
c,
EchoService.class,
GenericService.class,
Destroyable.class,
SpringProxy.class,
Advised.class,
DecoratingProxy.class);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
if (member instanceof Field) {
return generateMethodStatementForField(
targetClassName, (Field) member, attributes, injectedObject, hints);
}
if (member instanceof Method) {
return generateMethodStatementForMethod(
targetClassName, (Method) member, attributes, injectedObject, hints);
}
throw new IllegalStateException(
"Unsupported member type " + member.getClass().getName());
}
private CodeBlock generateMethodStatementForField(
ClassName targetClassName,
Field field,
AnnotationAttributes attributes,
Object injectedObject,
RuntimeHints hints) {
hints.reflection().registerField(field);
CodeBlock resolver =
CodeBlock.of("$T.$L($S)", ReferencedFieldValueResolver.class, "forRequiredField", field.getName());
CodeBlock shortcutResolver = CodeBlock.of("$L.withShortcut($S)", resolver, injectedObject);
AccessControl accessControl = AccessControl.forMember(field);
if (!accessControl.isAccessibleFrom(targetClassName)) {
return CodeBlock.of(
"$L.resolveAndSet($L, $L)", shortcutResolver, REGISTERED_BEAN_PARAMETER, INSTANCE_PARAMETER);
}
return CodeBlock.of(
"$L.$L = $L.resolve($L)",
INSTANCE_PARAMETER,
field.getName(),
shortcutResolver,
REGISTERED_BEAN_PARAMETER);
}
private CodeBlock generateMethodStatementForMethod(
ClassName targetClassName,
Method method,
AnnotationAttributes attributes,
Object injectedObject,
RuntimeHints hints) {
CodeBlock.Builder code = CodeBlock.builder();
code.add("$T.$L", ReferencedMethodArgumentsResolver.class, "forRequiredMethod");
code.add("($S", method.getName());
if (method.getParameterCount() > 0) {
code.add(", $L", generateParameterTypesCode(method.getParameterTypes()));
}
code.add(")");
if (method.getParameterCount() > 0) {
Parameter[] parameters = method.getParameters();
String[] parameterNames = new String[parameters.length];
for (int i = 0; i < parameterNames.length; i++) {
parameterNames[i] = parameters[i].getName();
}
code.add(".withShortcut($L)", generateParameterNamesCode(parameterNames));
}
AccessControl accessControl = AccessControl.forMember(method);
if (!accessControl.isAccessibleFrom(targetClassName)) {
hints.reflection().registerMethod(method, ExecutableMode.INVOKE);
code.add(".resolveAndInvoke($L, $L)", REGISTERED_BEAN_PARAMETER, INSTANCE_PARAMETER);
} else {
hints.reflection().registerMethod(method, ExecutableMode.INTROSPECT);
CodeBlock arguments = new AutowiredArgumentsCodeGenerator(this.target, method)
.generateCode(method.getParameterTypes());
CodeBlock injectionCode =
CodeBlock.of("args -> $L.$L($L)", INSTANCE_PARAMETER, method.getName(), arguments);
code.add(".resolve($L, $L)", REGISTERED_BEAN_PARAMETER, injectionCode);
}
return code.build();
}
private CodeBlock generateParameterNamesCode(String[] parameterNames) {
CodeBlock.Builder code = CodeBlock.builder();
for (int i = 0; i < parameterNames.length; i++) {
code.add(i != 0 ? ", " : "");
code.add("$S", parameterNames[i]);
}
return code.build();
}
private CodeBlock generateParameterTypesCode(Class<?>[] parameterTypes) {
CodeBlock.Builder code = CodeBlock.builder();
for (int i = 0; i < parameterTypes.length; i++) {
code.add(i != 0 ? ", " : "");
code.add("$T.class", parameterTypes[i]);
}
return code.build();
}
private void registerHints(RuntimeHints runtimeHints) {
if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getFieldElements())) {
for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getFieldElements()) {
Member member = referenceElement.getMember();
if (member instanceof Field) {
Field field = (Field) member;
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(field, true);
registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
}
}
}
if (!CollectionUtils.isEmpty(this.annotatedInjectionMetadata.getMethodElements())) {
for (AnnotatedInjectElement referenceElement : this.annotatedInjectionMetadata.getMethodElements()) {
Member member = referenceElement.getMember();
if (member instanceof Method) {
Method method = (Method) member;
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
MethodParameter methodParam = new MethodParameter(method, i);
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(methodParam, true);
registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
}
}
}
}
}
private void registerProxyIfNecessary(RuntimeHints runtimeHints, DependencyDescriptor dependencyDescriptor) {
if (this.candidateResolver != null) {
Class<?> proxyClass = this.candidateResolver.getLazyResolutionProxyClass(dependencyDescriptor, null);
if (proxyClass != null) {
ClassHintUtils.registerProxyIfNecessary(proxyClass, runtimeHints);
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/utils/AotUtils.java | /*
* 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 org.apache.dubbo.config.spring6.utils;
import org.apache.dubbo.common.compiler.support.ClassUtils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
public class AotUtils {
private AotUtils() {}
public static void registerSerializationForService(Class<?> serviceType, RuntimeHints hints) {
Set<Class<?>> serializationTypeCache = new LinkedHashSet<>();
Arrays.stream(serviceType.getMethods()).forEach((method) -> {
Arrays.stream(method.getParameterTypes())
.forEach(
(parameterType) -> registerSerializationType(parameterType, hints, serializationTypeCache));
registerSerializationType(method.getReturnType(), hints, serializationTypeCache);
});
}
private static void registerSerializationType(
Class<?> registerType, RuntimeHints hints, Set<Class<?>> serializationTypeCache) {
if (isPrimitive(registerType)) {
hints.serialization().registerType(TypeReference.of(ClassUtils.getBoxedClass(registerType)));
serializationTypeCache.add(registerType);
} else {
if (Serializable.class.isAssignableFrom(registerType)) {
hints.serialization().registerType(TypeReference.of(registerType));
serializationTypeCache.add(registerType);
Arrays.stream(registerType.getDeclaredFields()).forEach((field -> {
if (!serializationTypeCache.contains(field.getType())) {
registerSerializationType(field.getType(), hints, serializationTypeCache);
serializationTypeCache.add(field.getType());
}
}));
if (registerType.getSuperclass() != null) {
registerSerializationType(registerType.getSuperclass(), hints, serializationTypeCache);
}
}
}
}
private static boolean isPrimitive(Class<?> cls) {
return cls.isPrimitive()
|| cls == Boolean.class
|| cls == Byte.class
|| cls == Character.class
|| cls == Short.class
|| cls == Integer.class
|| cls == Long.class
|| cls == Float.class
|| cls == Double.class
|| cls == String.class
|| cls == Date.class
|| cls == Class.class;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java | dubbo-config/dubbo-config-spring6/src/main/java/org/apache/dubbo/config/spring6/context/DubboInfraBeanRegisterPostProcessor.java | /*
* 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 org.apache.dubbo.config.spring6.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
/**
* Register some infrastructure beans if not exists.
* This post-processor MUST impl BeanDefinitionRegistryPostProcessor,
* in order to enable the registered BeanFactoryPostProcessor bean to be loaded and executed.
*
* @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(
*ConfigurableListableBeanFactory, java.util.List)
*/
public class DubboInfraBeanRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.sameInstance;
class AbstractMethodConfigTest {
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void testTimeout() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setTimeout(10);
assertThat(methodConfig.getTimeout(), equalTo(10));
}
@Test
void testForks() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setForks(10);
assertThat(methodConfig.getForks(), equalTo(10));
}
@Test
void testRetries() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setRetries(3);
assertThat(methodConfig.getRetries(), equalTo(3));
}
@Test
void testLoadbalance() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setLoadbalance("mockloadbalance");
assertThat(methodConfig.getLoadbalance(), equalTo("mockloadbalance"));
}
@Test
void testAsync() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setAsync(true);
assertThat(methodConfig.isAsync(), is(true));
}
@Test
void testActives() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setActives(10);
assertThat(methodConfig.getActives(), equalTo(10));
}
@Test
void testSent() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setSent(true);
assertThat(methodConfig.getSent(), is(true));
}
@Test
void testMock() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setMock((Boolean) null);
assertThat(methodConfig.getMock(), isEmptyOrNullString());
methodConfig.setMock(true);
assertThat(methodConfig.getMock(), equalTo("true"));
methodConfig.setMock("return null");
assertThat(methodConfig.getMock(), equalTo("return null"));
methodConfig.setMock("mock");
assertThat(methodConfig.getMock(), equalTo("mock"));
}
@Test
void testMerger() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setMerger("merger");
assertThat(methodConfig.getMerger(), equalTo("merger"));
}
@Test
void testCache() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setCache("cache");
assertThat(methodConfig.getCache(), equalTo("cache"));
}
@Test
void testValidation() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setValidation("validation");
assertThat(methodConfig.getValidation(), equalTo("validation"));
}
@Test
void testParameters() throws Exception {
MethodConfig methodConfig = new MethodConfig();
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("key", "value");
methodConfig.setParameters(parameters);
assertThat(methodConfig.getParameters(), sameInstance(parameters));
}
private static class MethodConfig extends AbstractMethodConfig {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.mock.MockProtocol2;
import org.apache.dubbo.config.mock.MockRegistryFactory2;
import org.apache.dubbo.config.mock.MockServiceListener;
import org.apache.dubbo.config.mock.TestProxyFactory;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.service.GenericService;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.Lists;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.withSettings;
class ServiceConfigTest {
private Protocol protocolDelegate = Mockito.mock(Protocol.class);
private Registry registryDelegate = Mockito.mock(Registry.class);
private Exporter exporter = Mockito.mock(Exporter.class);
private ServiceConfig<DemoServiceImpl> service;
private ServiceConfig<DemoServiceImpl> service2;
private ServiceConfig<DemoServiceImpl> serviceWithoutRegistryConfig;
private ServiceConfig<DemoServiceImpl> delayService;
@BeforeEach
public void setUp() throws Exception {
DubboBootstrap.reset();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
service = new ServiceConfig<>();
service2 = new ServiceConfig<>();
serviceWithoutRegistryConfig = new ServiceConfig<>();
delayService = new ServiceConfig<>();
MockProtocol2.delegate = protocolDelegate;
MockRegistryFactory2.registry = registryDelegate;
Mockito.when(protocolDelegate.export(Mockito.any(Invoker.class))).thenReturn(exporter);
ApplicationConfig app = new ApplicationConfig("app");
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("mockprotocol2");
ProviderConfig provider = new ProviderConfig();
provider.setExport(true);
provider.setProtocol(protocolConfig);
RegistryConfig registry = new RegistryConfig();
registry.setProtocol("mockprotocol2");
registry.setAddress("N/A");
ArgumentConfig argument = new ArgumentConfig();
argument.setIndex(0);
argument.setCallback(false);
MethodConfig method = new MethodConfig();
method.setName("echo");
method.setArguments(Collections.singletonList(argument));
service.setProvider(provider);
service.setApplication(app);
service.setRegistry(registry);
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setMethods(Collections.singletonList(method));
service.setGroup("demo1");
service2.setProvider(provider);
service2.setApplication(app);
service2.setRegistry(registry);
service2.setInterface(DemoService.class);
service2.setRef(new DemoServiceImpl());
service2.setMethods(Collections.singletonList(method));
service2.setProxy("testproxyfactory");
service2.setGroup("demo2");
delayService.setProvider(provider);
delayService.setApplication(app);
delayService.setRegistry(registry);
delayService.setInterface(DemoService.class);
delayService.setRef(new DemoServiceImpl());
delayService.setMethods(Collections.singletonList(method));
delayService.setDelay(100);
delayService.setGroup("demo3");
serviceWithoutRegistryConfig.setProvider(provider);
serviceWithoutRegistryConfig.setApplication(app);
serviceWithoutRegistryConfig.setInterface(DemoService.class);
serviceWithoutRegistryConfig.setRef(new DemoServiceImpl());
serviceWithoutRegistryConfig.setMethods(Collections.singletonList(method));
serviceWithoutRegistryConfig.setGroup("demo4");
}
@AfterEach
public void tearDown() {
SysProps.clear();
DubboBootstrap.reset();
}
@Test
void testExport() throws Exception {
service.export();
try {
assertThat(service.getExportedUrls(), hasSize(1));
URL url = service.toUrl();
assertThat(url.getProtocol(), equalTo("mockprotocol2"));
assertThat(url.getPath(), equalTo(DemoService.class.getName()));
assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true"));
assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app"));
assertThat(url.getParameters(), hasKey(BIND_IP_KEY));
assertThat(url.getParameters(), hasKey(BIND_PORT_KEY));
assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true"));
assertThat(url.getParameters(), hasEntry("echo.0.callback", "false"));
assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false"));
assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName()));
assertThat(url.getParameters(), hasKey(METHODS_KEY));
assertThat(url.getParameters().get(METHODS_KEY), containsString("echo"));
assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER));
// export DemoService in "mockprotocol2" protocol.
Mockito.verify(protocolDelegate, times(1)).export(Mockito.any(Invoker.class));
// MetadataService will be exported on either dubbo or triple (the only two default acceptable protocol)
} finally {
service.unexport();
}
}
@Test
void testVersionAndGroupConfigFromProvider() {
// Service no configuration version , the Provider configured.
service.getProvider().setVersion("1.0.0");
service.getProvider().setGroup("groupA");
service.export();
try {
String serviceVersion = service.getVersion();
String serviceVersion2 = service.toUrl().getVersion();
String group = service.getGroup();
String group2 = service.toUrl().getGroup();
assertEquals(serviceVersion2, serviceVersion);
assertEquals(group, group2);
} finally {
service.unexport();
}
}
@Test
void testProxy() throws Exception {
service2.export();
try {
assertThat(service2.getExportedUrls(), hasSize(1));
assertEquals(2, TestProxyFactory.count); // local injvm and registry protocol, so expected is 2
TestProxyFactory.count = 0;
} finally {
service2.unexport();
}
}
@Test
void testDelayExport() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
delayService.addServiceListener(new ServiceListener() {
@Override
public void exported(ServiceConfig sc) {
assertEquals(delayService, sc);
assertThat(delayService.getExportedUrls(), hasSize(1));
latch.countDown();
}
@Override
public void unexported(ServiceConfig sc) {}
});
delayService.export();
try {
assertTrue(delayService.getExportedUrls().isEmpty());
latch.await();
} finally {
delayService.unexport();
}
}
@Test
void testUnexport() throws Exception {
System.setProperty(SHUTDOWN_WAIT_KEY, "0");
try {
service.export();
service.unexport();
// Thread.sleep(1000);
Mockito.verify(exporter, Mockito.atLeastOnce()).unexport();
} finally {
System.clearProperty(SHUTDOWN_TIMEOUT_KEY);
}
}
@Test
void testInterfaceClass() throws Exception {
ServiceConfig<Greeting> service = new ServiceConfig<>();
service.setInterface(Greeting.class.getName());
service.setRef(Mockito.mock(Greeting.class));
assertThat(service.getInterfaceClass() == Greeting.class, is(true));
service = new ServiceConfig<>();
service.setRef(Mockito.mock(Greeting.class, withSettings().extraInterfaces(GenericService.class)));
assertThat(service.getInterfaceClass() == GenericService.class, is(true));
}
@Test
void testInterface1() throws Exception {
Assertions.assertThrows(IllegalStateException.class, () -> {
ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.TRIPLE);
ServiceConfig<DemoService> service = new ServiceConfig<>();
service.setProtocol(protocolConfig);
service.setInterface(DemoServiceImpl.class);
});
}
@Test
void testInterface2() throws Exception {
ServiceConfig<DemoService> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
assertThat(service.getInterface(), equalTo(DemoService.class.getName()));
}
@Test
void testNoInterfaceSupport() throws Exception {
ProtocolConfig protocolConfig = new ProtocolConfig(CommonConstants.TRIPLE);
protocolConfig.setNoInterfaceSupport(true);
ServiceConfig<DemoService> service = new ServiceConfig<>();
service.setProtocol(protocolConfig);
service.setInterface(DemoServiceImpl.class);
assertThat(service.getInterface(), equalTo(DemoServiceImpl.class.getName()));
}
@Test
void testProvider() throws Exception {
ServiceConfig service = new ServiceConfig();
ProviderConfig provider = new ProviderConfig();
service.setProvider(provider);
assertThat(service.getProvider(), is(provider));
}
@Test
void testGeneric1() throws Exception {
ServiceConfig service = new ServiceConfig();
service.setGeneric(GENERIC_SERIALIZATION_DEFAULT);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT));
service.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA));
service.setGeneric(GENERIC_SERIALIZATION_BEAN);
assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN));
}
@Test
void testGeneric2() throws Exception {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig service = new ServiceConfig();
service.setGeneric("illegal");
});
}
@Test
void testApplicationInUrl() {
service.export();
try {
assertNotNull(service.toUrl().getApplication());
Assertions.assertEquals("app", service.toUrl().getApplication());
} finally {
service.unexport();
}
}
@Test
void testMetaData() {
// test new instance
ServiceConfig config = new ServiceConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
// test merged and override provider attributes
ProviderConfig providerConfig = new ProviderConfig();
providerConfig.setAsync(true);
providerConfig.setActives(10);
config.setProvider(providerConfig);
config.setAsync(false); // override
metaData = config.getMetaData();
Assertions.assertEquals(2, metaData.size());
Assertions.assertEquals("" + providerConfig.getActives(), metaData.get("actives"));
Assertions.assertEquals("" + config.isAsync(), metaData.get("async"));
}
@Test
void testExportWithoutRegistryConfig() {
serviceWithoutRegistryConfig.export();
try {
assertThat(serviceWithoutRegistryConfig.getExportedUrls(), hasSize(1));
URL url = serviceWithoutRegistryConfig.toUrl();
assertThat(url.getProtocol(), equalTo("mockprotocol2"));
assertThat(url.getPath(), equalTo(DemoService.class.getName()));
assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true"));
assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app"));
assertThat(url.getParameters(), hasKey(BIND_IP_KEY));
assertThat(url.getParameters(), hasKey(BIND_PORT_KEY));
assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true"));
assertThat(url.getParameters(), hasEntry("echo.0.callback", "false"));
assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false"));
assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName()));
assertThat(url.getParameters(), hasKey(METHODS_KEY));
assertThat(url.getParameters().get(METHODS_KEY), containsString("echo"));
assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER));
// export DemoService in "mockprotocol2" protocol (MetadataService will be not exported if no registry
// specified)
Mockito.verify(protocolDelegate, times(1)).export(Mockito.any(Invoker.class));
} finally {
serviceWithoutRegistryConfig.unexport();
}
}
@Test
void testServiceListener() {
ExtensionLoader<ServiceListener> extensionLoader = ExtensionLoader.getExtensionLoader(ServiceListener.class);
MockServiceListener mockServiceListener = (MockServiceListener) extensionLoader.getExtension("mock");
assertNotNull(mockServiceListener);
mockServiceListener.clearExportedServices();
service.export();
try {
Map<String, ServiceConfig> exportedServices = mockServiceListener.getExportedServices();
assertEquals(1, exportedServices.size());
ServiceConfig serviceConfig = exportedServices.get(service.getUniqueServiceName());
assertSame(service, serviceConfig);
} finally {
service.unexport();
}
}
@Test
void testMethodConfigWithInvalidArgumentConfig() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
// unset config.
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
service.unexport();
});
}
@Test
void testMethodConfigWithConfiguredArgumentTypeAndIndex() {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setType(String.class.getName());
setIndex(0);
setCallback(false);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
try {
assertFalse(service.getExportedUrls().isEmpty());
assertEquals(
"false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback"));
} finally {
service.unexport();
}
}
@Test
void testMethodConfigWithConfiguredArgumentIndex() {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setIndex(0);
setCallback(false);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
try {
assertFalse(service.getExportedUrls().isEmpty());
assertEquals(
"false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback"));
} finally {
service.unexport();
}
}
@Test
void testMethodConfigWithConfiguredArgumentType() {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setType(String.class.getName());
setCallback(false);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
try {
assertFalse(service.getExportedUrls().isEmpty());
assertEquals(
"false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback"));
} finally {
service.unexport();
}
}
@Test
void testMethodConfigWithUnknownArgumentType() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setType(Integer.class.getName());
setCallback(false);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
service.unexport();
});
}
@Test
void testMethodConfigWithUnmatchedArgument() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setType(Integer.class.getName());
setIndex(0);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
service.unexport();
});
}
@Test
void testMethodConfigWithInvalidArgumentIndex() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>();
service.setInterface(DemoService.class);
service.setRef(new DemoServiceImpl());
service.setProtocol(new ProtocolConfig() {
{
setName("dubbo");
}
});
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
// invalid argument index.
methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() {
{
setType(String.class.getName());
setIndex(1);
}
}));
service.setMethods(Lists.newArrayList(methodConfig));
service.export();
service.unexport();
});
}
@Test
void testOverride() {
System.setProperty("dubbo.service.version", "TEST");
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(DemoService.class);
serviceConfig.setRef(new DemoServiceImpl());
serviceConfig.setVersion("1.0.0");
serviceConfig.refresh();
Assertions.assertEquals("1.0.0", serviceConfig.getVersion());
System.clearProperty("dubbo.service.version");
}
@Test
void testMappingRetry() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(applicationModel.newModule());
serviceConfig.exported();
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
AtomicInteger count = new AtomicInteger(0);
ServiceNameMapping serviceNameMapping = new ServiceNameMapping() {
@Override
public boolean map(URL url) {
if (count.incrementAndGet() < 5) {
throw new RuntimeException();
}
return count.get() > 10;
}
@Override
public boolean hasValidMetadataCenter() {
return true;
}
@Override
public Set<String> getMapping(URL consumerURL) {
return null;
}
@Override
public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) {
return null;
}
@Override
public MappingListener stopListen(URL subscribeURL, MappingListener listener) {
return null;
}
@Override
public void putCachedMapping(String serviceKey, Set<String> apps) {}
@Override
public Set<String> getRemoteMapping(URL consumerURL) {
return null;
}
@Override
public Set<String> removeCachedMapping(String serviceKey) {
return null;
}
@Override
public void $destroy() {}
};
ApplicationConfig applicationConfig = new ApplicationConfig("app");
applicationConfig.setMappingRetryInterval(10);
serviceConfig.setApplication(applicationConfig);
serviceConfig.mapServiceName(URL.valueOf(""), serviceNameMapping, scheduledExecutorService);
await().until(() -> count.get() > 10);
scheduledExecutorService.shutdown();
}
@Test
void testMappingNoRetry() {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(applicationModel.newModule());
serviceConfig.exported();
ScheduledExecutorService scheduledExecutorService = Mockito.spy(Executors.newScheduledThreadPool(1));
AtomicInteger count = new AtomicInteger(0);
ServiceNameMapping serviceNameMapping = new ServiceNameMapping() {
@Override
public boolean map(URL url) {
return false;
}
@Override
public boolean hasValidMetadataCenter() {
return false;
}
@Override
public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) {
return null;
}
@Override
public MappingListener stopListen(URL subscribeURL, MappingListener listener) {
return null;
}
@Override
public void putCachedMapping(String serviceKey, Set<String> apps) {}
@Override
public Set<String> getMapping(URL consumerURL) {
return null;
}
@Override
public Set<String> getRemoteMapping(URL consumerURL) {
return null;
}
@Override
public Set<String> removeCachedMapping(String serviceKey) {
return null;
}
@Override
public void $destroy() {}
};
ApplicationConfig applicationConfig = new ApplicationConfig("app");
applicationConfig.setMappingRetryInterval(10);
serviceConfig.setApplication(applicationConfig);
serviceConfig.mapServiceName(URL.valueOf(""), serviceNameMapping, scheduledExecutorService);
verify(scheduledExecutorService, times(0)).schedule((Runnable) any(), anyLong(), any());
scheduledExecutorService.shutdown();
}
@Test
void testToString() {
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
service.setRef(new DemoServiceImpl() {
@Override
public String toString() {
throw new IllegalStateException();
}
});
try {
serviceConfig.toString();
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigMode;
import org.apache.dubbo.config.support.Nested;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class AbstractConfigTest {
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
}
@AfterEach
public void afterEach() {
SysProps.clear();
}
@Test
void testValidateProtocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setCodec("exchange");
protocolConfig.setName("test");
protocolConfig.setHost("host");
ConfigValidationUtils.validateProtocolConfig(protocolConfig);
}
@Test
void testValidateProtocolConfigSerialization() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setCodec("exchange");
protocolConfig.setName("dubbo");
protocolConfig.setHost("host");
protocolConfig.setSerialization("fastjson2");
protocolConfig.setPreferSerialization("hessian2");
ConfigValidationUtils.validateProtocolConfig(protocolConfig);
}
@Test
void testValidateProtocolConfigViolateSerialization() {
Assertions.assertThrowsExactly(IllegalStateException.class, () -> {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setCodec("exchange");
protocolConfig.setName("dubbo");
protocolConfig.setHost("host");
protocolConfig.setSerialization("violate");
protocolConfig.setPreferSerialization("violate");
ConfigValidationUtils.validateProtocolConfig(protocolConfig);
});
}
@Test
void testAppendParameters1() {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("num", "ONE");
AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password"), "prefix");
Assertions.assertEquals("one", parameters.get("prefix.key.1"));
Assertions.assertEquals("two", parameters.get("prefix.key.2"));
Assertions.assertEquals("ONE,1", parameters.get("prefix.num"));
Assertions.assertEquals("hello%2Fworld", parameters.get("prefix.naming"));
Assertions.assertEquals("30", parameters.get("prefix.age"));
Assertions.assertFalse(parameters.containsKey("prefix.secret"));
}
@Test
void testAppendParameters2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, new ParameterConfig());
});
}
@Test
void testAppendParameters3() {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, null);
assertTrue(parameters.isEmpty());
}
@Test
void testAppendParameters4() {
Map<String, String> parameters = new HashMap<String, String>();
AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password"));
Assertions.assertEquals("one", parameters.get("key.1"));
Assertions.assertEquals("two", parameters.get("key.2"));
Assertions.assertEquals("1", parameters.get("num"));
Assertions.assertEquals("hello%2Fworld", parameters.get("naming"));
Assertions.assertEquals("30", parameters.get("age"));
}
@Test
void testAppendAttributes1() {
ParameterConfig config = new ParameterConfig(1, "hello/world", 30, "password", "BEIJING");
Map<String, String> parameters = new HashMap<>();
AbstractConfig.appendParameters(parameters, config);
Map<String, String> attributes = new HashMap<>();
AbstractConfig.appendAttributes(attributes, config);
Assertions.assertEquals(null, parameters.get("secret"));
Assertions.assertEquals(null, parameters.get("parameters"));
// secret is excluded for url parameters, but keep for attributes
Assertions.assertEquals(config.getSecret(), attributes.get("secret"));
Assertions.assertEquals(config.getName(), attributes.get("name"));
Assertions.assertEquals(String.valueOf(config.getNumber()), attributes.get("number"));
Assertions.assertEquals(String.valueOf(config.getAge()), attributes.get("age"));
Assertions.assertEquals(StringUtils.encodeParameters(config.getParameters()), attributes.get("parameters"));
Assertions.assertTrue(parameters.containsKey("detail.address")); // detailAddress -> detail.address
Assertions.assertTrue(attributes.containsKey("detail-address")); // detailAddress -> detail-address
}
@Test
void checkExtension() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ConfigValidationUtils.checkExtension(
ApplicationModel.defaultModel(), Greeting.class, "hello", "world"));
}
@Test
void checkMultiExtension1() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ConfigValidationUtils.checkMultiExtension(
ApplicationModel.defaultModel(), Greeting.class, "hello", "default,world"));
}
@Test
void checkMultiExtension2() {
try {
ConfigValidationUtils.checkMultiExtension(
ApplicationModel.defaultModel(), Greeting.class, "hello", "default,-world");
} catch (Throwable t) {
Assertions.fail(t);
}
}
@Test
void checkMultiExtension3() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ConfigValidationUtils.checkMultiExtension(
ApplicationModel.defaultModel(), Greeting.class, "hello", "default , world"));
}
@Test
void checkMultiExtension4() {
try {
ConfigValidationUtils.checkMultiExtension(
ApplicationModel.defaultModel(), Greeting.class, "hello", "default , -world ");
} catch (Throwable t) {
Assertions.fail(t);
}
}
@Test
void checkLength() {
Assertions.assertDoesNotThrow(() -> {
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= 200; i++) {
builder.append('a');
}
ConfigValidationUtils.checkLength("hello", builder.toString());
});
}
@Test
void checkPathLength() {
Assertions.assertDoesNotThrow(() -> {
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= 200; i++) {
builder.append('a');
}
ConfigValidationUtils.checkPathLength("hello", builder.toString());
});
}
@Test
void checkName() {
Assertions.assertDoesNotThrow(() -> ConfigValidationUtils.checkName("hello", "world%"));
}
@Test
void checkNameHasSymbol() {
try {
ConfigValidationUtils.checkNameHasSymbol("hello", ":*,/ -0123\tabcdABCD");
ConfigValidationUtils.checkNameHasSymbol("mock", "force:return world");
} catch (Exception e) {
fail("the value should be legal.");
}
}
@Test
void checkKey() {
try {
ConfigValidationUtils.checkKey("hello", "*,-0123abcdABCD");
} catch (Exception e) {
fail("the value should be legal.");
}
}
@Test
void checkMultiName() {
try {
ConfigValidationUtils.checkMultiName("hello", ",-._0123abcdABCD");
} catch (Exception e) {
fail("the value should be legal.");
}
}
@Test
void checkPathName() {
try {
ConfigValidationUtils.checkPathName("hello", "/-$._0123abcdABCD");
} catch (Exception e) {
fail("the value should be legal.");
}
}
@Test
void checkMethodName() {
try {
ConfigValidationUtils.checkMethodName("hello", "abcdABCD0123abcd");
} catch (Exception e) {
fail("the value should be legal.");
}
try {
ConfigValidationUtils.checkMethodName("hello", "0a");
} catch (Exception e) {
// ignore
fail("the value should be legal.");
}
}
@Test
void checkParameterName() {
Map<String, String> parameters = Collections.singletonMap("hello", ":*,/-._0123abcdABCD");
try {
ConfigValidationUtils.checkParameterName(parameters);
} catch (Exception e) {
fail("the value should be legal.");
}
}
@Test
@Config(
interfaceClass = Greeting.class,
filter = {"f1, f2"},
listener = {"l1, l2"},
parameters = {"k1", "v1", "k2", "v2"})
public void appendAnnotation() throws Exception {
Config config = getClass().getMethod("appendAnnotation").getAnnotation(Config.class);
AnnotationConfig annotationConfig = new AnnotationConfig();
annotationConfig.appendAnnotation(Config.class, config);
Assertions.assertSame(Greeting.class, annotationConfig.getInterface());
Assertions.assertEquals("f1, f2", annotationConfig.getFilter());
Assertions.assertEquals("l1, l2", annotationConfig.getListener());
Assertions.assertEquals(2, annotationConfig.getParameters().size());
Assertions.assertEquals("v1", annotationConfig.getParameters().get("k1"));
Assertions.assertEquals("v2", annotationConfig.getParameters().get("k2"));
assertThat(annotationConfig.toString(), Matchers.containsString("filter=\"f1, f2\" "));
assertThat(annotationConfig.toString(), Matchers.containsString("listener=\"l1, l2\" "));
}
@Test
void testRefreshAll() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
overrideConfig.setExclude("override-config");
Map<String, String> external = new HashMap<>();
external.put("dubbo.override.address", "external://127.0.0.1:2181");
// @Parameter(exclude=true)
external.put("dubbo.override.exclude", "external");
// @Parameter(key="key1", useKeyAsProperty=false)
external.put("dubbo.override.key", "external");
// @Parameter(key="key2", useKeyAsProperty=true)
external.put("dubbo.override.key2", "external");
ApplicationModel.defaultModel().modelEnvironment().initialize();
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external);
SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181");
SysProps.setProperty("dubbo.override.protocol", "system");
// this will not override, use 'key' instead, @Parameter(key="key1", useKeyAsProperty=false)
SysProps.setProperty("dubbo.override.key1", "system");
SysProps.setProperty("dubbo.override.key2", "system");
// Load configuration from system properties -> externalConfiguration -> RegistryConfig -> dubbo.properties
overrideConfig.refresh();
Assertions.assertEquals("system://127.0.0.1:2181", overrideConfig.getAddress());
Assertions.assertEquals("system", overrideConfig.getProtocol());
Assertions.assertEquals("override-config://", overrideConfig.getEscape());
Assertions.assertEquals("external", overrideConfig.getKey());
Assertions.assertEquals("system", overrideConfig.getKey2());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshSystem() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
overrideConfig.setExclude("override-config");
SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181");
SysProps.setProperty("dubbo.override.protocol", "system");
SysProps.setProperty("dubbo.override.key", "system");
overrideConfig.refresh();
Assertions.assertEquals("system://127.0.0.1:2181", overrideConfig.getAddress());
Assertions.assertEquals("system", overrideConfig.getProtocol());
Assertions.assertEquals("override-config://", overrideConfig.getEscape());
Assertions.assertEquals("system", overrideConfig.getKey());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshProperties() throws Exception {
try {
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(new HashMap<>());
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("/dubbo.properties"));
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperties(properties);
overrideConfig.refresh();
Assertions.assertEquals("override-config://127.0.0.1:2181", overrideConfig.getAddress());
Assertions.assertEquals("override-config", overrideConfig.getProtocol());
Assertions.assertEquals("override-config://", overrideConfig.getEscape());
Assertions.assertEquals("properties", overrideConfig.getKey2());
// Assertions.assertEquals("properties", overrideConfig.getUseKeyAsProperty());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshExternal() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
overrideConfig.setExclude("override-config");
Map<String, String> external = new HashMap<>();
external.put("dubbo.override.address", "external://127.0.0.1:2181");
external.put("dubbo.override.protocol", "external");
external.put("dubbo.override.escape", "external://");
// @Parameter(exclude=true)
external.put("dubbo.override.exclude", "external");
// @Parameter(key="key1", useKeyAsProperty=false)
external.put("dubbo.override.key", "external");
// @Parameter(key="key2", useKeyAsProperty=true)
external.put("dubbo.override.key2", "external");
ApplicationModel.defaultModel().modelEnvironment().initialize();
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external);
overrideConfig.refresh();
Assertions.assertEquals("external://127.0.0.1:2181", overrideConfig.getAddress());
Assertions.assertEquals("external", overrideConfig.getProtocol());
Assertions.assertEquals("external://", overrideConfig.getEscape());
Assertions.assertEquals("external", overrideConfig.getExclude());
Assertions.assertEquals("external", overrideConfig.getKey());
Assertions.assertEquals("external", overrideConfig.getKey2());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshById() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setId("override-id");
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
overrideConfig.setExclude("override-config");
Map<String, String> external = new HashMap<>();
external.put("dubbo.overrides.override-id.address", "external-override-id://127.0.0.1:2181");
external.put("dubbo.overrides.override-id.key", "external");
external.put("dubbo.overrides.override-id.key2", "external");
external.put("dubbo.override.address", "external://127.0.0.1:2181");
external.put("dubbo.override.exclude", "external");
ApplicationModel.defaultModel().modelEnvironment().initialize();
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external);
// refresh config
overrideConfig.refresh();
Assertions.assertEquals("external-override-id://127.0.0.1:2181", overrideConfig.getAddress());
Assertions.assertEquals("override-config", overrideConfig.getProtocol());
Assertions.assertEquals("override-config://", overrideConfig.getEscape());
Assertions.assertEquals("external", overrideConfig.getKey());
Assertions.assertEquals("external", overrideConfig.getKey2());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshParameters() {
try {
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setParameters(parameters);
Map<String, String> external = new HashMap<>();
external.put("dubbo.override.parameters", "[{key3:value3},{key4:value4},{key2:value5}]");
ApplicationModel.defaultModel().modelEnvironment().initialize();
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external);
// refresh config
overrideConfig.refresh();
Assertions.assertEquals("value1", overrideConfig.getParameters().get("key1"));
Assertions.assertEquals("value5", overrideConfig.getParameters().get("key2"));
Assertions.assertEquals("value3", overrideConfig.getParameters().get("key3"));
Assertions.assertEquals("value4", overrideConfig.getParameters().get("key4"));
SysProps.setProperty("dubbo.override.parameters", "[{key3:value6}]");
overrideConfig.refresh();
Assertions.assertEquals("value6", overrideConfig.getParameters().get("key3"));
Assertions.assertEquals("value4", overrideConfig.getParameters().get("key4"));
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshParametersWithAttribute() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
SysProps.setProperty("dubbo.override.parameters.key00", "value00");
overrideConfig.refresh();
assertEquals("value00", overrideConfig.getParameters().get("key00"));
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void testRefreshParametersWithOverrideConfigMode() {
FrameworkModel frameworkModel = new FrameworkModel();
try {
// test OVERRIDE_ALL configMode
{
SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_ALL.name());
SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181");
SysProps.setProperty("dubbo.override.protocol", "system");
SysProps.setProperty("dubbo.override.parameters", "[{key1:systemValue1},{key2:systemValue2}]");
ApplicationModel applicationModel1 = frameworkModel.newApplication();
OverrideConfig overrideConfig = new OverrideConfig(applicationModel1);
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key3", "value3");
overrideConfig.setParameters(parameters);
// overrideConfig's config is overridden by system config
overrideConfig.refresh();
Assertions.assertEquals(overrideConfig.getAddress(), "system://127.0.0.1:2181");
Assertions.assertEquals(overrideConfig.getProtocol(), "system");
Assertions.assertEquals(
overrideConfig.getParameters(),
StringUtils.parseParameters("[{key1:systemValue1},{key2:systemValue2},{key3:value3}]"));
}
// test OVERRIDE_IF_ABSENT configMode
{
SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_IF_ABSENT.name());
SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181");
SysProps.setProperty("dubbo.override.protocol", "system");
SysProps.setProperty("dubbo.override.parameters", "[{key1:systemValue1},{key2:systemValue2}]");
SysProps.setProperty("dubbo.override.key", "systemKey");
ApplicationModel applicationModel = frameworkModel.newApplication();
OverrideConfig overrideConfig = new OverrideConfig(applicationModel);
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key3", "value3");
overrideConfig.setParameters(parameters);
// overrideConfig's config is overridden/set by system config only when the overrideConfig's config is
// absent/empty
overrideConfig.refresh();
Assertions.assertEquals(overrideConfig.getAddress(), "override-config://127.0.0.1:2181");
Assertions.assertEquals(overrideConfig.getProtocol(), "override-config");
Assertions.assertEquals(overrideConfig.getKey(), "systemKey");
Assertions.assertEquals(
overrideConfig.getParameters(),
StringUtils.parseParameters("[{key1:value1},{key2:systemValue2},{key3:value3}]"));
}
} finally {
frameworkModel.destroy();
}
}
@Test
void testOnlyPrefixedKeyTakeEffect() {
try {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setNotConflictKey("value-from-config");
Map<String, String> external = new HashMap<>();
external.put("notConflictKey", "value-from-external");
external.put("dubbo.override.notConflictKey2", "value-from-external");
ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external);
overrideConfig.refresh();
Assertions.assertEquals("value-from-config", overrideConfig.getNotConflictKey());
Assertions.assertEquals("value-from-external", overrideConfig.getNotConflictKey2());
} finally {
ApplicationModel.defaultModel().modelEnvironment().destroy();
}
}
@Test
void tetMetaData() {
OverrideConfig overrideConfig = new OverrideConfig();
overrideConfig.setId("override-id");
overrideConfig.setAddress("override-config://127.0.0.1:2181");
overrideConfig.setProtocol("override-config");
overrideConfig.setEscape("override-config://");
overrideConfig.setExclude("override-config");
Map<String, String> metaData = overrideConfig.getMetaData();
Assertions.assertEquals("override-config://127.0.0.1:2181", metaData.get("address"));
Assertions.assertEquals("override-config", metaData.get("protocol"));
Assertions.assertEquals("override-config://", metaData.get("escape"));
Assertions.assertEquals("override-config", metaData.get("exclude"));
Assertions.assertNull(metaData.get("key"));
Assertions.assertNull(metaData.get("key2"));
// with prefix
Map<String, String> prefixMetadata =
overrideConfig.getMetaData(OverrideConfig.getTypePrefix(OverrideConfig.class));
Assertions.assertEquals("override-config://127.0.0.1:2181", prefixMetadata.get("dubbo.override.address"));
Assertions.assertEquals("override-config", prefixMetadata.get("dubbo.override.protocol"));
Assertions.assertEquals("override-config://", prefixMetadata.get("dubbo.override.escape"));
Assertions.assertEquals("override-config", prefixMetadata.get("dubbo.override.exclude"));
}
@Test
void testEquals() {
ApplicationConfig application1 = new ApplicationConfig();
ApplicationConfig application2 = new ApplicationConfig();
application1.setName("app1");
application2.setName("app2");
Assertions.assertNotEquals(application1, application2);
application1.setName("sameName");
application2.setName("sameName");
Assertions.assertEquals(application1, application2);
ProtocolConfig protocol1 = new ProtocolConfig();
protocol1.setName("dubbo");
protocol1.setPort(1234);
ProtocolConfig protocol2 = new ProtocolConfig();
protocol2.setName("dubbo");
protocol2.setPort(1235);
Assertions.assertNotEquals(protocol1, protocol2);
}
@Test
void testRegistryConfigEquals() {
RegistryConfig hangzhou = new RegistryConfig();
hangzhou.setAddress("nacos://localhost:8848");
HashMap<String, String> parameters = new HashMap<>();
parameters.put("namespace", "hangzhou");
hangzhou.setParameters(parameters);
RegistryConfig shanghai = new RegistryConfig();
shanghai.setAddress("nacos://localhost:8848");
parameters = new HashMap<>();
parameters.put("namespace", "shanghai");
shanghai.setParameters(parameters);
Assertions.assertNotEquals(hangzhou, shanghai);
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface ConfigField {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Config {
Class<?> interfaceClass() default void.class;
String interfaceName() default "";
String[] filter() default {};
String[] listener() default {};
String[] parameters() default {};
ConfigField[] configFields() default {};
ConfigField configField() default @ConfigField;
}
private static class OverrideConfig extends AbstractConfig {
public String address;
public String protocol;
public String exclude;
public String key;
public String key2;
public String escape;
public String notConflictKey;
public String notConflictKey2;
protected Map<String, String> parameters;
public OverrideConfig() {}
public OverrideConfig(ScopeModel scopeModel) {
super(scopeModel);
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
@Parameter(excluded = true)
public String getExclude() {
return exclude;
}
public void setExclude(String exclude) {
this.exclude = exclude;
}
@Parameter(key = "key1")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Parameter(key = "mykey")
public String getKey2() {
return key2;
}
public void setKey2(String key2) {
this.key2 = key2;
}
@Parameter(escaped = true)
public String getEscape() {
return escape;
}
public void setEscape(String escape) {
this.escape = escape;
}
public String getNotConflictKey() {
return notConflictKey;
}
public void setNotConflictKey(String notConflictKey) {
this.notConflictKey = notConflictKey;
}
public String getNotConflictKey2() {
return notConflictKey2;
}
public void setNotConflictKey2(String notConflictKey2) {
this.notConflictKey2 = notConflictKey2;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
}
private static class ParameterConfig {
private int number;
private String name;
private int age;
private String secret;
private String detailAddress;
ParameterConfig() {}
ParameterConfig(int number, String name, int age, String secret) {
this(number, name, age, secret, "");
}
ParameterConfig(int number, String name, int age, String secret, String detailAddress) {
this.number = number;
this.name = name;
this.age = age;
this.secret = secret;
this.detailAddress = detailAddress;
}
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
@Parameter(key = "num", append = true)
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java | /*
* 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 org.apache.dubbo.config;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
class ProviderConfigTest {
@Test
void testProtocol() {
ProviderConfig provider = new ProviderConfig();
provider.setProtocol("protocol");
assertThat(provider.getProtocol().getName(), equalTo("protocol"));
}
@Test
void testDefault() {
ProviderConfig provider = new ProviderConfig();
provider.setDefault(true);
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.isDefault(), is(true));
assertThat(parameters, not(hasKey("default")));
}
@Test
void testHost() {
ProviderConfig provider = new ProviderConfig();
provider.setHost("demo-host");
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.getHost(), equalTo("demo-host"));
assertThat(parameters, not(hasKey("host")));
}
@Test
void testPort() {
ProviderConfig provider = new ProviderConfig();
provider.setPort(8080);
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.getPort(), is(8080));
assertThat(parameters, not(hasKey("port")));
}
@Test
void testPath() {
ProviderConfig provider = new ProviderConfig();
provider.setPath("/path");
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.getPath(), equalTo("/path"));
assertThat(provider.getContextpath(), equalTo("/path"));
assertThat(parameters, not(hasKey("path")));
}
@Test
void testContextPath() {
ProviderConfig provider = new ProviderConfig();
provider.setContextpath("/context-path");
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.getContextpath(), equalTo("/context-path"));
assertThat(parameters, not(hasKey("/context-path")));
}
@Test
void testThreadpool() {
ProviderConfig provider = new ProviderConfig();
provider.setThreadpool("mockthreadpool");
assertThat(provider.getThreadpool(), equalTo("mockthreadpool"));
}
@Test
void testThreadname() {
ProviderConfig provider = new ProviderConfig();
provider.setThreadname("test-thread-pool");
assertThat(provider.getThreadname(), equalTo("test-thread-pool"));
}
@Test
void testThreads() {
ProviderConfig provider = new ProviderConfig();
provider.setThreads(10);
assertThat(provider.getThreads(), is(10));
}
@Test
void testIothreads() {
ProviderConfig provider = new ProviderConfig();
provider.setIothreads(10);
assertThat(provider.getIothreads(), is(10));
}
@Test
void testAlive() {
ProviderConfig provider = new ProviderConfig();
provider.setAlive(10);
assertThat(provider.getAlive(), is(10));
}
@Test
void testQueues() {
ProviderConfig provider = new ProviderConfig();
provider.setQueues(10);
assertThat(provider.getQueues(), is(10));
}
@Test
void testAccepts() {
ProviderConfig provider = new ProviderConfig();
provider.setAccepts(10);
assertThat(provider.getAccepts(), is(10));
}
@Test
void testCharset() {
ProviderConfig provider = new ProviderConfig();
provider.setCharset("utf-8");
assertThat(provider.getCharset(), equalTo("utf-8"));
}
@Test
void testPayload() {
ProviderConfig provider = new ProviderConfig();
provider.setPayload(10);
assertThat(provider.getPayload(), is(10));
}
@Test
void testBuffer() {
ProviderConfig provider = new ProviderConfig();
provider.setBuffer(10);
assertThat(provider.getBuffer(), is(10));
}
@Test
void testServer() {
ProviderConfig provider = new ProviderConfig();
provider.setServer("demo-server");
assertThat(provider.getServer(), equalTo("demo-server"));
}
@Test
void testClient() {
ProviderConfig provider = new ProviderConfig();
provider.setClient("client");
assertThat(provider.getClient(), equalTo("client"));
}
@Test
void testTelnet() {
ProviderConfig provider = new ProviderConfig();
provider.setTelnet("mocktelnethandler");
assertThat(provider.getTelnet(), equalTo("mocktelnethandler"));
}
@Test
void testPrompt() {
ProviderConfig provider = new ProviderConfig();
provider.setPrompt("#");
Map<String, String> parameters = new HashMap<>();
ProviderConfig.appendParameters(parameters, provider);
assertThat(provider.getPrompt(), equalTo("#"));
assertThat(parameters, hasEntry("prompt", "%23"));
}
@Test
void testStatus() {
ProviderConfig provider = new ProviderConfig();
provider.setStatus("mockstatuschecker");
assertThat(provider.getStatus(), equalTo("mockstatuschecker"));
}
@Test
void testTransporter() {
ProviderConfig provider = new ProviderConfig();
provider.setTransporter("mocktransporter");
assertThat(provider.getTransporter(), equalTo("mocktransporter"));
}
@Test
void testExchanger() {
ProviderConfig provider = new ProviderConfig();
provider.setExchanger("mockexchanger");
assertThat(provider.getExchanger(), equalTo("mockexchanger"));
}
@Test
void testDispatcher() {
ProviderConfig provider = new ProviderConfig();
provider.setDispatcher("mockdispatcher");
assertThat(provider.getDispatcher(), equalTo("mockdispatcher"));
}
@Test
void testNetworker() {
ProviderConfig provider = new ProviderConfig();
provider.setNetworker("networker");
assertThat(provider.getNetworker(), equalTo("networker"));
}
@Test
void testWait() {
ProviderConfig provider = new ProviderConfig();
provider.setWait(10);
assertThat(provider.getWait(), equalTo(10));
}
@Test
void testMetaData() {
ProviderConfig config = new ProviderConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ConfigManager;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNull;
class ProtocolConfigTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
}
@AfterEach
public void afterEach() {
DubboBootstrap.reset();
SysProps.clear();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void testName() {
ProtocolConfig protocol = new ProtocolConfig();
String protocolName = "xprotocol";
protocol.setName(protocolName);
Map<String, String> parameters = new HashMap<>();
ProtocolConfig.appendParameters(parameters, protocol);
assertThat(protocol.getName(), equalTo(protocolName));
assertThat(protocol.getId(), equalTo(null));
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testHost() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setHost("host");
Map<String, String> parameters = new HashMap<String, String>();
ProtocolConfig.appendParameters(parameters, protocol);
assertThat(protocol.getHost(), equalTo("host"));
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testPort() {
ProtocolConfig protocol = new ProtocolConfig();
int port = NetUtils.getAvailablePort();
protocol.setPort(port);
Map<String, String> parameters = new HashMap<>();
ProtocolConfig.appendParameters(parameters, protocol);
assertThat(protocol.getPort(), equalTo(port));
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testPath() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setContextpath("context-path");
Map<String, String> parameters = new HashMap<>();
ProtocolConfig.appendParameters(parameters, protocol);
assertThat(protocol.getPath(), equalTo("context-path"));
assertThat(protocol.getContextpath(), equalTo("context-path"));
assertThat(parameters.isEmpty(), is(true));
protocol.setPath("path");
assertThat(protocol.getPath(), equalTo("path"));
assertThat(protocol.getContextpath(), equalTo("path"));
}
@Test
void testCorethreads() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setCorethreads(10);
assertThat(protocol.getCorethreads(), is(10));
}
@Test
void testThreads() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setThreads(10);
assertThat(protocol.getThreads(), is(10));
}
@Test
void testIothreads() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setIothreads(10);
assertThat(protocol.getIothreads(), is(10));
}
@Test
void testQueues() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setQueues(10);
assertThat(protocol.getQueues(), is(10));
}
@Test
void testAccepts() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setAccepts(10);
assertThat(protocol.getAccepts(), is(10));
}
@Test
void testCodec() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("dubbo");
protocol.setCodec("mockcodec");
assertThat(protocol.getCodec(), equalTo("mockcodec"));
}
@Test
void testAccesslog() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setAccesslog("access.log");
assertThat(protocol.getAccesslog(), equalTo("access.log"));
}
@Test
void testTelnet() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setTelnet("mocktelnethandler");
assertThat(protocol.getTelnet(), equalTo("mocktelnethandler"));
}
@Test
void testRegister() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setRegister(true);
assertThat(protocol.isRegister(), is(true));
}
@Test
void testTransporter() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setTransporter("mocktransporter");
assertThat(protocol.getTransporter(), equalTo("mocktransporter"));
}
@Test
void testExchanger() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setExchanger("mockexchanger");
assertThat(protocol.getExchanger(), equalTo("mockexchanger"));
}
@Test
void testDispatcher() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setDispatcher("mockdispatcher");
assertThat(protocol.getDispatcher(), equalTo("mockdispatcher"));
}
@Test
void testNetworker() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setNetworker("networker");
assertThat(protocol.getNetworker(), equalTo("networker"));
}
@Test
void testParameters() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setParameters(Collections.singletonMap("k1", "v1"));
assertThat(protocol.getParameters(), hasEntry("k1", "v1"));
}
@Test
void testDefault() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setDefault(true);
assertThat(protocol.isDefault(), is(true));
}
@Test
void testKeepAlive() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setKeepAlive(true);
assertThat(protocol.getKeepAlive(), is(true));
}
@Test
void testOptimizer() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setOptimizer("optimizer");
assertThat(protocol.getOptimizer(), equalTo("optimizer"));
}
@Test
void testExtension() {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setExtension("extension");
assertThat(protocol.getExtension(), equalTo("extension"));
}
@Test
void testMetaData() {
ProtocolConfig config = new ProtocolConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "actual: " + metaData);
}
@Test
void testOverrideEmptyConfig() {
int port = NetUtils.getAvailablePort();
// dubbo.protocol.name=rest
// dubbo.protocol.port=port
SysProps.setProperty("dubbo.protocol.name", "rest");
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port));
try {
ProtocolConfig protocolConfig = new ProtocolConfig();
DubboBootstrap.getInstance()
.application("test-app")
.protocol(protocolConfig)
.initialize();
Assertions.assertEquals("rest", protocolConfig.getName());
Assertions.assertEquals(port, protocolConfig.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testOverrideConfigByName() {
int port = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocols.rest.port", String.valueOf(port));
try {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("rest");
DubboBootstrap.getInstance()
.application("test-app")
.protocol(protocolConfig)
.initialize();
Assertions.assertEquals("rest", protocolConfig.getName());
Assertions.assertEquals(port, protocolConfig.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testOverrideConfigById() {
int port = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocols.rest1.name", "rest");
SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port));
try {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("xxx");
protocolConfig.setId("rest1");
DubboBootstrap.getInstance()
.application("test-app")
.protocol(protocolConfig)
.initialize();
Assertions.assertEquals("rest", protocolConfig.getName());
Assertions.assertEquals(port, protocolConfig.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testCreateConfigFromPropsWithId() {
int port1 = NetUtils.getAvailablePort();
int port2 = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocols.rest1.name", "rest");
SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port1));
SysProps.setProperty("dubbo.protocol.name", "dubbo"); // ignore
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port2));
try {
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application("test-app").initialize();
ConfigManager configManager = bootstrap.getConfigManager();
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocol = configManager.getProtocol("rest1").get();
Assertions.assertEquals("rest", protocol.getName());
Assertions.assertEquals(port1, protocol.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testCreateConfigFromPropsWithName() {
int port1 = NetUtils.getAvailablePort();
int port2 = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocols.rest.port", String.valueOf(port1));
SysProps.setProperty("dubbo.protocol.name", "dubbo"); // ignore
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port2));
try {
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application("test-app").initialize();
ConfigManager configManager = bootstrap.getConfigManager();
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocol = configManager.getProtocol("rest").get();
Assertions.assertEquals("rest", protocol.getName());
Assertions.assertEquals(port1, protocol.getPort());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testCreateDefaultConfigFromProps() {
int port = NetUtils.getAvailablePort();
SysProps.setProperty("dubbo.protocol.name", "rest");
SysProps.setProperty("dubbo.protocol.port", String.valueOf(port));
String protocolId = "rest-protocol";
SysProps.setProperty("dubbo.protocol.id", protocolId); // Allow override config id from props
try {
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application("test-app").initialize();
ConfigManager configManager = bootstrap.getConfigManager();
Collection<ProtocolConfig> protocols = configManager.getProtocols();
Assertions.assertEquals(1, protocols.size());
ProtocolConfig protocol = configManager.getProtocol("rest").get();
Assertions.assertEquals("rest", protocol.getName());
Assertions.assertEquals(port, protocol.getPort());
Assertions.assertEquals(protocolId, protocol.getId());
} finally {
DubboBootstrap.getInstance().stop();
}
}
@Test
void testPreferSerializationDefault1() {
ProtocolConfig protocolConfig = new ProtocolConfig();
assertNull(protocolConfig.getPreferSerialization());
protocolConfig.checkDefault();
assertThat(protocolConfig.getPreferSerialization(), equalTo("hessian2,fastjson2"));
protocolConfig = new ProtocolConfig();
protocolConfig.setSerialization("x-serialization");
assertNull(protocolConfig.getPreferSerialization());
protocolConfig.checkDefault();
assertThat(protocolConfig.getPreferSerialization(), equalTo("x-serialization"));
}
@Test
void testPreferSerializationDefault2() {
ProtocolConfig protocolConfig = new ProtocolConfig();
assertNull(protocolConfig.getPreferSerialization());
protocolConfig.refresh();
assertThat(protocolConfig.getPreferSerialization(), equalTo("hessian2,fastjson2"));
protocolConfig = new ProtocolConfig();
protocolConfig.setSerialization("x-serialization");
assertNull(protocolConfig.getPreferSerialization());
protocolConfig.refresh();
assertThat(protocolConfig.getPreferSerialization(), equalTo("x-serialization"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class MetricsConfigTest {
@Test
void testToUrl() {
MetricsConfig metrics = new MetricsConfig();
metrics.setProtocol(PROTOCOL_PROMETHEUS);
PrometheusConfig prometheus = new PrometheusConfig();
PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter();
PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway();
exporter.setEnabled(true);
pushgateway.setEnabled(true);
prometheus.setExporter(exporter);
prometheus.setPushgateway(pushgateway);
metrics.setPrometheus(prometheus);
AggregationConfig aggregation = new AggregationConfig();
aggregation.setEnabled(true);
metrics.setAggregation(aggregation);
HistogramConfig histogram = new HistogramConfig();
histogram.setEnabled(true);
metrics.setHistogram(histogram);
URL url = metrics.toUrl();
assertThat(url.getProtocol(), equalTo(PROTOCOL_PROMETHEUS));
assertThat(url.getAddress(), equalTo("localhost:9090"));
assertThat(url.getHost(), equalTo("localhost"));
assertThat(url.getPort(), equalTo(9090));
assertThat(url.getParameter("prometheus.exporter.enabled"), equalTo("true"));
assertThat(url.getParameter("prometheus.pushgateway.enabled"), equalTo("true"));
assertThat(url.getParameter("aggregation.enabled"), equalTo("true"));
assertThat(url.getParameter("histogram.enabled"), equalTo("true"));
}
@Test
void testProtocol() {
MetricsConfig metrics = new MetricsConfig();
metrics.setProtocol(PROTOCOL_PROMETHEUS);
assertThat(metrics.getProtocol(), equalTo(PROTOCOL_PROMETHEUS));
}
@Test
void testPrometheus() {
MetricsConfig metrics = new MetricsConfig();
PrometheusConfig prometheus = new PrometheusConfig();
PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter();
PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway();
exporter.setEnabled(true);
exporter.setEnableHttpServiceDiscovery(true);
exporter.setHttpServiceDiscoveryUrl("localhost:8080");
prometheus.setExporter(exporter);
pushgateway.setEnabled(true);
pushgateway.setBaseUrl("localhost:9091");
pushgateway.setUsername("username");
pushgateway.setPassword("password");
pushgateway.setJob("job");
pushgateway.setPushInterval(30);
prometheus.setPushgateway(pushgateway);
metrics.setPrometheus(prometheus);
assertThat(metrics.getPrometheus().getExporter().getEnabled(), equalTo(true));
assertThat(metrics.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), equalTo(true));
assertThat(metrics.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), equalTo("localhost:8080"));
assertThat(metrics.getPrometheus().getPushgateway().getEnabled(), equalTo(true));
assertThat(metrics.getPrometheus().getPushgateway().getBaseUrl(), equalTo("localhost:9091"));
assertThat(metrics.getPrometheus().getPushgateway().getUsername(), equalTo("username"));
assertThat(metrics.getPrometheus().getPushgateway().getPassword(), equalTo("password"));
assertThat(metrics.getPrometheus().getPushgateway().getJob(), equalTo("job"));
assertThat(metrics.getPrometheus().getPushgateway().getPushInterval(), equalTo(30));
}
@Test
void testAggregation() {
MetricsConfig metrics = new MetricsConfig();
AggregationConfig aggregation = new AggregationConfig();
aggregation.setEnabled(true);
aggregation.setBucketNum(5);
aggregation.setTimeWindowSeconds(120);
metrics.setAggregation(aggregation);
assertThat(metrics.getAggregation().getEnabled(), equalTo(true));
assertThat(metrics.getAggregation().getBucketNum(), equalTo(5));
assertThat(metrics.getAggregation().getTimeWindowSeconds(), equalTo(120));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.compiler.support.CtClassBuilder;
import org.apache.dubbo.common.compiler.support.JavassistCompiler;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder;
import org.apache.dubbo.rpc.cluster.support.registry.ZoneAwareClusterInvoker;
import org.apache.dubbo.rpc.cluster.support.wrapper.ScopeClusterInvoker;
import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import org.apache.dubbo.rpc.protocol.ReferenceCountInvokerWrapper;
import org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker;
import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol;
import org.apache.dubbo.rpc.service.GenericService;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.NotFoundException;
import demo.MultiClassLoaderService;
import demo.MultiClassLoaderServiceImpl;
import demo.MultiClassLoaderServiceRequest;
import demo.MultiClassLoaderServiceResult;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LIVENESS_PROBE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.READINESS_PROBE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_ASYNC_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_BACKGROUND_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFER_THREAD_NUM_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.STARTUP_PROBE;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST;
import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT;
import static org.apache.dubbo.rpc.Constants.LOCAL_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY;
class ReferenceConfigTest {
private static final Logger logger = LoggerFactory.getLogger(ReferenceConfigTest.class);
private static String zkUrl1;
private static String zkUrl2;
private static String registryUrl1;
@BeforeAll
public static void beforeAll() {
int zkServerPort1 = 2181;
int zkServerPort2 = 2182;
zkUrl1 = "zookeeper://localhost:" + zkServerPort1;
zkUrl2 = "zookeeper://localhost:" + zkServerPort2;
registryUrl1 = "registry://localhost:" + zkServerPort1 + "?registry=zookeeper";
}
@BeforeEach
public void setUp() throws Exception {
DubboBootstrap.reset();
FrameworkModel.destroyAll();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
ApplicationModel.defaultModel().getApplicationConfigManager();
DubboBootstrap.getInstance();
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
FrameworkModel.destroyAll();
SysProps.clear();
Mockito.framework().clearInlineMocks();
}
/**
* Test whether the configuration required for the aggregation service reference meets expectations
*/
@Test
void testAppendConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
applicationConfig.setVersion("v1");
applicationConfig.setOwner("owner1");
applicationConfig.setOrganization("bu1");
applicationConfig.setArchitecture("architecture1");
applicationConfig.setEnvironment("test");
applicationConfig.setCompiler("javassist");
applicationConfig.setLogger("log4j2");
applicationConfig.setDumpDirectory("/");
applicationConfig.setQosEnable(false);
applicationConfig.setQosHost("127.0.0.1");
applicationConfig.setQosPort(77777);
applicationConfig.setQosAcceptForeignIp(false);
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
applicationConfig.setShutwait("5");
applicationConfig.setMetadataType("local");
applicationConfig.setRegisterConsumer(false);
applicationConfig.setRepository("repository1");
applicationConfig.setEnableFileCache(false);
applicationConfig.setProtocol("dubbo");
applicationConfig.setMetadataServicePort(88888);
applicationConfig.setMetadataServiceProtocol("tri");
applicationConfig.setLivenessProbe("livenessProbe");
applicationConfig.setReadinessProbe("readinessProb");
applicationConfig.setStartupProbe("startupProbe");
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setClient("netty");
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
referenceConfig.setReconnect("reconnect");
referenceConfig.setSticky(false);
referenceConfig.setStub(DEFAULT_STUB_EVENT);
referenceConfig.setRouter("default");
referenceConfig.setReferAsync(true);
MonitorConfig monitorConfig = new MonitorConfig();
applicationConfig.setMonitor(monitorConfig);
ModuleConfig moduleConfig = new ModuleConfig();
moduleConfig.setMonitor("default");
moduleConfig.setName("module1");
moduleConfig.setOrganization("application1");
moduleConfig.setVersion("v1");
moduleConfig.setOwner("owner1");
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setClient("netty");
consumerConfig.setThreadpool("fixed");
consumerConfig.setCorethreads(200);
consumerConfig.setQueues(500);
consumerConfig.setThreads(300);
consumerConfig.setShareconnections(10);
consumerConfig.setUrlMergeProcessor("default");
consumerConfig.setReferThreadNum(20);
consumerConfig.setReferBackground(false);
referenceConfig.setConsumer(consumerConfig);
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
methodConfig.setStat(1);
methodConfig.setRetries(0);
methodConfig.setExecutes(10);
methodConfig.setDeprecated(false);
methodConfig.setSticky(false);
methodConfig.setReturn(false);
methodConfig.setService("service");
methodConfig.setServiceId(DemoService.class.getName());
methodConfig.setParentPrefix("demo");
referenceConfig.setMethods(Collections.singletonList(methodConfig));
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
RegistryConfig registry = new RegistryConfig();
registry.setAddress(zkUrl1);
applicationConfig.setRegistries(Collections.singletonList(registry));
applicationConfig.setRegistryIds(registry.getId());
moduleConfig.setRegistries(Collections.singletonList(registry));
referenceConfig.setRegistry(registry);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
dubboBootstrap
.application(applicationConfig)
.reference(referenceConfig)
.registry(registry)
.module(moduleConfig)
.initialize();
referenceConfig.init();
ServiceMetadata serviceMetadata = referenceConfig.getServiceMetadata();
// verify additional side parameter
Assertions.assertEquals(CONSUMER_SIDE, serviceMetadata.getAttachments().get(SIDE_KEY));
// verify additional interface parameter
Assertions.assertEquals(
DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY));
// verify additional metadata-type parameter
Assertions.assertEquals(
DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY));
// verify additional register.ip parameter
Assertions.assertEquals(
NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY));
// verify additional runtime parameters
Assertions.assertEquals(
Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY));
Assertions.assertEquals(
Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY));
Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(TIMESTAMP_KEY));
Assertions.assertEquals(
String.valueOf(ConfigUtils.getPid()),
serviceMetadata.getAttachments().get(PID_KEY));
// verify additional application config
Assertions.assertEquals(
applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY));
Assertions.assertEquals(
applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner"));
Assertions.assertEquals(
applicationConfig.getVersion(), serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY));
Assertions.assertEquals(
applicationConfig.getOrganization(),
serviceMetadata.getAttachments().get("organization"));
Assertions.assertEquals(
applicationConfig.getArchitecture(),
serviceMetadata.getAttachments().get("architecture"));
Assertions.assertEquals(
applicationConfig.getEnvironment(),
serviceMetadata.getAttachments().get("environment"));
Assertions.assertEquals(
applicationConfig.getCompiler(),
serviceMetadata.getAttachments().get("compiler"));
Assertions.assertEquals(
applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registry.ids"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor"));
Assertions.assertEquals(
applicationConfig.getDumpDirectory(),
serviceMetadata.getAttachments().get(DUMP_DIRECTORY));
Assertions.assertEquals(
applicationConfig.getQosEnable().toString(),
serviceMetadata.getAttachments().get(QOS_ENABLE));
Assertions.assertEquals(
applicationConfig.getQosHost(), serviceMetadata.getAttachments().get(QOS_HOST));
Assertions.assertEquals(
applicationConfig.getQosPort().toString(),
serviceMetadata.getAttachments().get(QOS_PORT));
Assertions.assertEquals(
applicationConfig.getQosAcceptForeignIp().toString(),
serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP));
Assertions.assertEquals(
applicationConfig.getParameters().get("key1"),
serviceMetadata.getAttachments().get("key1"));
Assertions.assertEquals(
applicationConfig.getParameters().get("key2"),
serviceMetadata.getAttachments().get("key2"));
Assertions.assertEquals(
applicationConfig.getShutwait(),
serviceMetadata.getAttachments().get("shutwait"));
Assertions.assertEquals(
applicationConfig.getMetadataType(),
serviceMetadata.getAttachments().get(METADATA_KEY));
Assertions.assertEquals(
applicationConfig.getRegisterConsumer().toString(),
serviceMetadata.getAttachments().get("register.consumer"));
Assertions.assertEquals(
applicationConfig.getRepository(),
serviceMetadata.getAttachments().get("repository"));
Assertions.assertEquals(
applicationConfig.getEnableFileCache().toString(),
serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED));
Assertions.assertEquals(
applicationConfig.getMetadataServicePort().toString(),
serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY));
Assertions.assertEquals(
applicationConfig.getMetadataServiceProtocol().toString(),
serviceMetadata.getAttachments().get(METADATA_SERVICE_PROTOCOL_KEY));
Assertions.assertEquals(
applicationConfig.getLivenessProbe(),
serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY));
Assertions.assertEquals(
applicationConfig.getReadinessProbe(),
serviceMetadata.getAttachments().get(READINESS_PROBE_KEY));
Assertions.assertEquals(
applicationConfig.getStartupProbe(),
serviceMetadata.getAttachments().get(STARTUP_PROBE));
// verify additional module config
Assertions.assertEquals(
moduleConfig.getName(), serviceMetadata.getAttachments().get("module"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor"));
Assertions.assertEquals(
moduleConfig.getOrganization(), serviceMetadata.getAttachments().get("module.organization"));
Assertions.assertEquals(
moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries"));
Assertions.assertEquals(
moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version"));
// verify additional consumer config
Assertions.assertEquals(
consumerConfig.getClient(), serviceMetadata.getAttachments().get("client"));
Assertions.assertEquals(
consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool"));
Assertions.assertEquals(
consumerConfig.getCorethreads().toString(),
serviceMetadata.getAttachments().get("corethreads"));
Assertions.assertEquals(
consumerConfig.getQueues().toString(),
serviceMetadata.getAttachments().get("queues"));
Assertions.assertEquals(
consumerConfig.getThreads().toString(),
serviceMetadata.getAttachments().get("threads"));
Assertions.assertEquals(
consumerConfig.getShareconnections().toString(),
serviceMetadata.getAttachments().get("shareconnections"));
Assertions.assertEquals(
consumerConfig.getUrlMergeProcessor(),
serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_THREAD_NUM_KEY));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_BACKGROUND_KEY));
// verify additional reference config
Assertions.assertEquals(
referenceConfig.getClient(), serviceMetadata.getAttachments().get("client"));
Assertions.assertEquals(
referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic"));
Assertions.assertEquals(
referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol"));
Assertions.assertEquals(
referenceConfig.isInit().toString(),
serviceMetadata.getAttachments().get("init"));
Assertions.assertEquals(
referenceConfig.getLazy().toString(),
serviceMetadata.getAttachments().get("lazy"));
Assertions.assertEquals(
referenceConfig.isInjvm().toString(),
serviceMetadata.getAttachments().get("injvm"));
Assertions.assertEquals(
referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect"));
Assertions.assertEquals(
referenceConfig.getSticky().toString(),
serviceMetadata.getAttachments().get("sticky"));
Assertions.assertEquals(
referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub"));
Assertions.assertEquals(
referenceConfig.getProvidedBy(),
serviceMetadata.getAttachments().get("provided-by"));
Assertions.assertEquals(
referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router"));
Assertions.assertEquals(
referenceConfig.getReferAsync().toString(),
serviceMetadata.getAttachments().get(REFER_ASYNC_KEY));
// verify additional method config
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("name"));
Assertions.assertEquals(
methodConfig.getStat().toString(),
serviceMetadata.getAttachments().get("sayName.stat"));
Assertions.assertEquals(
methodConfig.getRetries().toString(),
serviceMetadata.getAttachments().get("sayName.retries"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.reliable"));
Assertions.assertEquals(
methodConfig.getExecutes().toString(),
serviceMetadata.getAttachments().get("sayName.executes"));
Assertions.assertEquals(
methodConfig.getDeprecated().toString(),
serviceMetadata.getAttachments().get("sayName.deprecated"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.stick"));
Assertions.assertEquals(
methodConfig.isReturn().toString(),
serviceMetadata.getAttachments().get("sayName.return"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service.id"));
Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.parent.prefix"));
// verify additional revision and methods parameter
Assertions.assertEquals(
Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()),
serviceMetadata.getAttachments().get(REVISION_KEY));
Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(METHODS_KEY));
Assertions.assertEquals(
DemoService.class.getMethods().length,
StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length);
dubboBootstrap.stop();
}
@Test
void testCreateInvokerForLocalRefer() {
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setScope(LOCAL_KEY);
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize();
referenceConfig.init();
Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker);
ScopeClusterInvoker<?> scopeClusterInvoker = (ScopeClusterInvoker<?>) referenceConfig.getInvoker();
Invoker<?> mockInvoker = scopeClusterInvoker.getInvoker();
// Assertions.assertTrue(mockInvoker instanceof MockClusterInvoker);
// Invoker<?> withCount = ((MockClusterInvoker<?>) mockInvoker).getDirectory().getAllInvokers().get(0);
Invoker<?> withCount =
scopeClusterInvoker.getDirectory().getAllInvokers().get(0);
Assertions.assertTrue(withCount instanceof ReferenceCountInvokerWrapper);
Invoker<?> withFilter = ((ReferenceCountInvokerWrapper<?>) withCount).getInvoker();
Assertions.assertTrue(withFilter instanceof ListenerInvokerWrapper
|| withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker);
if (withFilter instanceof ListenerInvokerWrapper) {
Assertions.assertTrue(
((ListenerInvokerWrapper<?>) (((ReferenceCountInvokerWrapper<?>) withCount).getInvoker()))
.getInvoker()
instanceof InjvmInvoker);
}
if (withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker) {
Invoker filterInvoker = ((FilterChainBuilder.CallbackRegistrationInvoker) withFilter).getFilterInvoker();
FilterChainBuilder.CopyOfFilterChainNode filterInvoker1 =
(FilterChainBuilder.CopyOfFilterChainNode) filterInvoker;
ListenerInvokerWrapper originalInvoker = (ListenerInvokerWrapper) filterInvoker1.getOriginalInvoker();
Invoker invoker = originalInvoker.getInvoker();
Assertions.assertTrue(invoker instanceof InjvmInvoker);
}
URL url = withFilter.getUrl();
Assertions.assertEquals("application1", url.getParameter("application"));
Assertions.assertEquals("value1", url.getParameter("key1"));
Assertions.assertEquals("value2", url.getParameter("key2"));
dubboBootstrap.stop();
}
/**
* Verify the configuration of the registry protocol for remote reference
*/
@Test
void testCreateInvokerForRemoteRefer() {
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
referenceConfig.refreshed.set(true);
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
RegistryConfig registry = new RegistryConfig();
registry.setAddress(zkUrl1);
applicationConfig.setRegistries(Collections.singletonList(registry));
applicationConfig.setRegistryIds(registry.getId());
referenceConfig.setRegistry(registry);
dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize();
referenceConfig.init();
Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker);
dubboBootstrap.destroy();
}
/**
* Verify that the remote url is directly configured for remote reference
*/
@Test
void testCreateInvokerWithRemoteUrlForRemoteRefer() {
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
referenceConfig.refreshed.set(true);
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
referenceConfig.setUrl("dubbo://127.0.0.1:20880");
dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize();
referenceConfig.init();
Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker);
Invoker scopeClusterInvoker = referenceConfig.getInvoker();
// Assertions.assertTrue(((ScopeClusterInvoker) scopeClusterInvoker).getInvoker() instanceof
// MockClusterInvoker);
Assertions.assertEquals(
Boolean.TRUE,
((ScopeClusterInvoker) scopeClusterInvoker)
.getInvoker()
.getUrl()
.getAttribute(PEER_KEY));
dubboBootstrap.destroy();
}
/**
* Verify that the registry url is directly configured for remote reference
*/
@Test
void testCreateInvokerWithRegistryUrlForRemoteRefer() {
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
referenceConfig.refreshed.set(true);
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
referenceConfig.setUrl(registryUrl1);
dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize();
referenceConfig.init();
Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker);
dubboBootstrap.destroy();
}
/**
* Verify the service reference of multiple registries
*/
@Test
void testMultipleRegistryForRemoteRefer() {
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setGeneric(Boolean.FALSE.toString());
referenceConfig.setProtocol("dubbo");
referenceConfig.setInit(true);
referenceConfig.setLazy(false);
referenceConfig.setInjvm(false);
DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel());
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("application1");
Map<String, String> parameters = new HashMap<>();
parameters.put("key1", "value1");
parameters.put("key2", "value2");
applicationConfig.setParameters(parameters);
referenceConfig.refreshed.set(true);
referenceConfig.setInterface(DemoService.class);
referenceConfig.getInterfaceClass();
referenceConfig.setCheck(false);
RegistryConfig registry1 = new RegistryConfig();
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java | /*
* 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 org.apache.dubbo.config;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
class ArgumentConfigTest {
@Test
void testIndex() {
ArgumentConfig argument = new ArgumentConfig();
argument.setIndex(1);
assertThat(argument.getIndex(), is(1));
}
@Test
void testType() {
ArgumentConfig argument = new ArgumentConfig();
argument.setType("int");
assertThat(argument.getType(), equalTo("int"));
}
@Test
void testCallback() {
ArgumentConfig argument = new ArgumentConfig();
argument.setCallback(true);
assertThat(argument.isCallback(), is(true));
}
@Test
void testArguments() {
ArgumentConfig argument = new ArgumentConfig();
argument.setIndex(1);
argument.setType("int");
argument.setCallback(true);
Map<String, String> parameters = new HashMap<String, String>();
AbstractServiceConfig.appendParameters(parameters, argument);
assertThat(parameters, hasEntry("callback", "true"));
assertThat(parameters.size(), is(1));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java | /*
* 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 org.apache.dubbo.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
class MonitorConfigTest {
@Test
void testAddress() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setAddress("monitor-addr");
assertThat(monitor.getAddress(), equalTo("monitor-addr"));
Map<String, String> parameters = new HashMap<String, String>();
MonitorConfig.appendParameters(parameters, monitor);
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testProtocol() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setProtocol("protocol");
assertThat(monitor.getProtocol(), equalTo("protocol"));
Map<String, String> parameters = new HashMap<String, String>();
MonitorConfig.appendParameters(parameters, monitor);
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testUsername() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setUsername("user");
assertThat(monitor.getUsername(), equalTo("user"));
Map<String, String> parameters = new HashMap<String, String>();
MonitorConfig.appendParameters(parameters, monitor);
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testPassword() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setPassword("secret");
assertThat(monitor.getPassword(), equalTo("secret"));
Map<String, String> parameters = new HashMap<String, String>();
MonitorConfig.appendParameters(parameters, monitor);
assertThat(parameters.isEmpty(), is(true));
}
@Test
void testGroup() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setGroup("group");
assertThat(monitor.getGroup(), equalTo("group"));
}
@Test
void testVersion() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setVersion("1.0.0");
assertThat(monitor.getVersion(), equalTo("1.0.0"));
}
@Test
void testParameters() throws Exception {
MonitorConfig monitor = new MonitorConfig();
Map<String, String> parameters = Collections.singletonMap("k1", "v1");
monitor.setParameters(parameters);
assertThat(monitor.getParameters(), hasEntry("k1", "v1"));
}
@Test
void testDefault() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setDefault(true);
assertThat(monitor.isDefault(), is(true));
}
@Test
void testInterval() throws Exception {
MonitorConfig monitor = new MonitorConfig();
monitor.setInterval("100");
assertThat(monitor.getInterval(), equalTo("100"));
}
@Test
void testMetaData() {
MonitorConfig config = new MonitorConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
class MetadataReportConfigTest {
@Test
void testFile() {
MetadataReportConfig metadataReportConfig = new MetadataReportConfig();
metadataReportConfig.setFile("file");
assertThat(metadataReportConfig.getFile(), equalTo("file"));
metadataReportConfig.setAddress("file://dir-to-file");
URL url = metadataReportConfig.toUrl();
assertThat(url.getParameter("file"), equalTo("file"));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ConfigScopeModelInitializerTest {
private FrameworkModel frameworkModel;
private ApplicationModel applicationModel;
private ModuleModel moduleModel;
@BeforeEach
public void setUp() {
frameworkModel = new FrameworkModel();
applicationModel = frameworkModel.newApplication();
moduleModel = applicationModel.newModule();
}
@AfterEach
public void reset() {
frameworkModel.destroy();
}
@Test
void test() {
Assertions.assertNotNull(applicationModel.getDeployer());
Assertions.assertNotNull(moduleModel.getDeployer());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.SystemProperty.SYSTEM_TCP_RESPONSE_TIMEOUT;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
class ConsumerConfigTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
}
@AfterEach
public void afterEach() {
SysProps.clear();
DubboBootstrap.reset();
}
@Test
void testTimeout() {
SystemPropertyConfigUtils.clearSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT);
ConsumerConfig consumer = new ConsumerConfig();
consumer.setTimeout(10);
assertThat(consumer.getTimeout(), is(10));
assertThat(SystemPropertyConfigUtils.getSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT), equalTo("10"));
}
@Test
void testDefault() throws Exception {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setDefault(true);
assertThat(consumer.isDefault(), is(true));
}
@Test
void testClient() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setClient("client");
assertThat(consumer.getClient(), equalTo("client"));
}
@Test
void testThreadpool() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setThreadpool("fixed");
assertThat(consumer.getThreadpool(), equalTo("fixed"));
}
@Test
void testCorethreads() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setCorethreads(10);
assertThat(consumer.getCorethreads(), equalTo(10));
}
@Test
void testThreads() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setThreads(20);
assertThat(consumer.getThreads(), equalTo(20));
}
@Test
void testQueues() {
ConsumerConfig consumer = new ConsumerConfig();
consumer.setQueues(5);
assertThat(consumer.getQueues(), equalTo(5));
}
@Test
void testOverrideConfigSingle() {
SysProps.setProperty("dubbo.consumer.check", "false");
SysProps.setProperty("dubbo.consumer.group", "demo");
SysProps.setProperty("dubbo.consumer.threads", "10");
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setGroup("groupA");
consumerConfig.setThreads(20);
consumerConfig.setCheck(true);
DubboBootstrap.getInstance()
.application("demo-app")
.consumer(consumerConfig)
.initialize();
Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel()
.getDefaultModule()
.getConfigManager()
.getConsumers();
Assertions.assertEquals(1, consumers.size());
Assertions.assertEquals(consumerConfig, consumers.iterator().next());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals("demo", consumerConfig.getGroup());
Assertions.assertEquals(10, consumerConfig.getThreads());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigByPluralityId() {
SysProps.setProperty("dubbo.consumer.group", "demoA"); // ignore
SysProps.setProperty("dubbo.consumers.consumerA.check", "false");
SysProps.setProperty("dubbo.consumers.consumerA.group", "demoB");
SysProps.setProperty("dubbo.consumers.consumerA.threads", "10");
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setId("consumerA");
consumerConfig.setGroup("groupA");
consumerConfig.setThreads(20);
consumerConfig.setCheck(true);
DubboBootstrap.getInstance()
.application("demo-app")
.consumer(consumerConfig)
.initialize();
Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel()
.getDefaultModule()
.getConfigManager()
.getConsumers();
Assertions.assertEquals(1, consumers.size());
Assertions.assertEquals(consumerConfig, consumers.iterator().next());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals("demoB", consumerConfig.getGroup());
Assertions.assertEquals(10, consumerConfig.getThreads());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigBySingularId() {
// override success
SysProps.setProperty("dubbo.consumer.group", "demoA");
SysProps.setProperty("dubbo.consumer.threads", "15");
// ignore singular format: dubbo.{tag-name}.{config-id}.{config-item}={config-value}
SysProps.setProperty("dubbo.consumer.consumerA.check", "false");
SysProps.setProperty("dubbo.consumer.consumerA.group", "demoB");
SysProps.setProperty("dubbo.consumer.consumerA.threads", "10");
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setId("consumerA");
consumerConfig.setGroup("groupA");
consumerConfig.setThreads(20);
consumerConfig.setCheck(true);
DubboBootstrap.getInstance()
.application("demo-app")
.consumer(consumerConfig)
.initialize();
Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel()
.getDefaultModule()
.getConfigManager()
.getConsumers();
Assertions.assertEquals(1, consumers.size());
Assertions.assertEquals(consumerConfig, consumers.iterator().next());
Assertions.assertEquals(true, consumerConfig.isCheck());
Assertions.assertEquals("demoA", consumerConfig.getGroup());
Assertions.assertEquals(15, consumerConfig.getThreads());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigByDubboProps() {
ApplicationModel.defaultModel().getDefaultModule();
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.consumers.consumerA.check", "false");
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.consumers.consumerA.group", "demo");
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.consumers.consumerA.threads", "10");
try {
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setId("consumerA");
consumerConfig.setGroup("groupA");
DubboBootstrap.getInstance()
.application("demo-app")
.consumer(consumerConfig)
.initialize();
Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel()
.getDefaultModule()
.getConfigManager()
.getConsumers();
Assertions.assertEquals(1, consumers.size());
Assertions.assertEquals(consumerConfig, consumers.iterator().next());
Assertions.assertEquals(false, consumerConfig.isCheck());
Assertions.assertEquals("groupA", consumerConfig.getGroup());
Assertions.assertEquals(10, consumerConfig.getThreads());
} finally {
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.refresh();
DubboBootstrap.getInstance().destroy();
}
}
@Test
void testReferenceAndConsumerConfigOverlay() {
SysProps.setProperty("dubbo.consumer.group", "demo");
SysProps.setProperty("dubbo.consumer.threads", "12");
SysProps.setProperty("dubbo.consumer.timeout", "1234");
SysProps.setProperty("dubbo.consumer.init", "false");
SysProps.setProperty("dubbo.consumer.check", "false");
SysProps.setProperty("dubbo.registry.address", "N/A");
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setInterface(DemoService.class);
DubboBootstrap.getInstance()
.application("demo-app")
.reference(referenceConfig)
.initialize();
Assertions.assertEquals("demo", referenceConfig.getGroup());
Assertions.assertEquals(1234, referenceConfig.getTimeout());
Assertions.assertEquals(false, referenceConfig.isInit());
Assertions.assertEquals(false, referenceConfig.isCheck());
DubboBootstrap.getInstance().destroy();
}
@Test
void testMetaData() {
ConsumerConfig consumerConfig = new ConsumerConfig();
Map<String, String> metaData = consumerConfig.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
@Test
void testSerialize() {
ConsumerConfig consumerConfig = new ConsumerConfig();
consumerConfig.setCorethreads(1);
consumerConfig.setQueues(1);
consumerConfig.setThreads(1);
consumerConfig.setThreadpool("Mock");
consumerConfig.setGroup("Test");
consumerConfig.setMeshEnable(false);
consumerConfig.setReferThreadNum(2);
consumerConfig.setShareconnections(2);
consumerConfig.setTimeout(2);
consumerConfig.setUrlMergeProcessor("test");
consumerConfig.setReferBackground(false);
consumerConfig.setActives(1);
consumerConfig.setAsync(false);
consumerConfig.setCache("false");
consumerConfig.setCallbacks(1);
consumerConfig.setConnections(1);
consumerConfig.setInterfaceClassLoader(Thread.currentThread().getContextClassLoader());
consumerConfig.setApplication(new ApplicationConfig());
consumerConfig.setRegistries(Collections.singletonList(new RegistryConfig()));
consumerConfig.setModule(new ModuleConfig());
consumerConfig.setMetadataReportConfig(new MetadataReportConfig());
consumerConfig.setMonitor(new MonitorConfig());
consumerConfig.setConfigCenter(new ConfigCenterConfig());
try {
JsonUtils.toJson(consumerConfig);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
class ConfigCenterConfigTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
}
@AfterEach
public void afterEach() {
SysProps.clear();
DubboBootstrap.reset();
}
@Test
void testPrefix() {
ConfigCenterConfig config = new ConfigCenterConfig();
Assertions.assertEquals(Arrays.asList("dubbo.config-center"), config.getPrefixes());
config.setId("configcenterA");
Assertions.assertEquals(
Arrays.asList("dubbo.config-centers.configcenterA", "dubbo.config-center"), config.getPrefixes());
}
@Test
void testToUrl() {
ConfigCenterConfig config = new ConfigCenterConfig();
config.setNamespace("namespace");
config.setGroup("group");
config.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress());
config.setHighestPriority(null);
config.refresh();
Assertions.assertEquals(
ZookeeperRegistryCenterConfig.getConnectionAddress() + "/"
+ ConfigCenterConfig.class.getName()
+ "?check=true&config-file=dubbo.properties&group=group&namespace=namespace&timeout=30000",
config.toUrl().toFullString());
}
@Test
void testOverrideConfig() {
String zkAddr = ZookeeperRegistryCenterConfig.getConnectionAddress();
// sysprops has no id
SysProps.setProperty("dubbo.config-center.check", "false");
SysProps.setProperty("dubbo.config-center.address", zkAddr);
// No id and no address
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setAddress("N/A");
try {
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.initialize();
} catch (Exception e) {
// ignore
e.printStackTrace();
}
Collection<ConfigCenterConfig> configCenters =
ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(zkAddr, configCenter.getAddress());
Assertions.assertEquals(false, configCenter.isCheck());
DubboBootstrap.getInstance().stop();
}
@Test
void testOverrideConfig2() {
String zkAddr = "nacos://127.0.0.1:8848";
// sysprops has no id
SysProps.setProperty("dubbo.config-center.check", "false");
SysProps.setProperty("dubbo.config-center.address", zkAddr);
// No id but has address
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress());
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.start();
Collection<ConfigCenterConfig> configCenters =
ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(zkAddr, configCenter.getAddress());
Assertions.assertEquals(false, configCenter.isCheck());
DubboBootstrap.getInstance().stop();
}
@Test
void testOverrideConfigBySystemProps() {
// Config instance has Id, but sysprops without id
SysProps.setProperty("dubbo.config-center.check", "false");
SysProps.setProperty("dubbo.config-center.timeout", "1234");
// Config instance has id
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setTimeout(3000L);
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.initialize();
Collection<ConfigCenterConfig> configCenters =
ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(1234, configCenter.getTimeout());
Assertions.assertEquals(false, configCenter.isCheck());
DubboBootstrap.getInstance().stop();
}
@Test
void testOverrideConfigByDubboProps() {
ApplicationModel.defaultModel().getDefaultModule();
// Config instance has id, dubbo props has no id
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.config-center.check", "false");
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.config-center.timeout", "1234");
try {
// Config instance has id
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setTimeout(3000L);
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.initialize();
Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel()
.getApplicationConfigManager()
.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(3000L, configCenter.getTimeout());
Assertions.assertEquals(false, configCenter.isCheck());
} finally {
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.refresh();
DubboBootstrap.getInstance().stop();
}
}
@Test
void testOverrideConfigBySystemPropsWithId() {
// Both config instance and sysprops have id
SysProps.setProperty("dubbo.config-centers.configcenterA.check", "false");
SysProps.setProperty("dubbo.config-centers.configcenterA.timeout", "1234");
// Config instance has id
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setId("configcenterA");
configCenter.setTimeout(3000L);
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.start();
Collection<ConfigCenterConfig> configCenters =
ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(1234, configCenter.getTimeout());
Assertions.assertEquals(false, configCenter.isCheck());
DubboBootstrap.getInstance().stop();
}
@Test
void testOverrideConfigByDubboPropsWithId() {
ApplicationModel.defaultModel().getDefaultModule();
// Config instance has id, dubbo props has id
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.config-centers.configcenterA.check", "false");
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.setProperty("dubbo.config-centers.configcenterA.timeout", "1234");
try {
// Config instance has id
ConfigCenterConfig configCenter = new ConfigCenterConfig();
configCenter.setId("configcenterA");
configCenter.setTimeout(3000L);
DubboBootstrap.getInstance()
.application("demo-app")
.configCenter(configCenter)
.start();
Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel()
.getApplicationConfigManager()
.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
Assertions.assertEquals(configCenter, configCenters.iterator().next());
Assertions.assertEquals(3000L, configCenter.getTimeout());
Assertions.assertEquals(false, configCenter.isCheck());
} finally {
ApplicationModel.defaultModel()
.modelEnvironment()
.getPropertiesConfiguration()
.refresh();
DubboBootstrap.getInstance().stop();
}
}
@Test
void testMetaData() {
ConfigCenterConfig configCenter = new ConfigCenterConfig();
Map<String, String> metaData = configCenter.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
@Test
void testParameters() {
ConfigCenterConfig cc = new ConfigCenterConfig();
cc.setParameters(new LinkedHashMap<>());
cc.getParameters().put(CLIENT_KEY, null);
Map<String, String> params = new LinkedHashMap<>();
ConfigCenterConfig.appendParameters(params, cc);
Map<String, String> attributes = new LinkedHashMap<>();
ConfigCenterConfig.appendAttributes(attributes, cc);
String encodedParametersStr = attributes.get("parameters");
Assertions.assertEquals("[]", encodedParametersStr);
Assertions.assertEquals(
0, StringUtils.parseParameters(encodedParametersStr).size());
}
@Test
void testAttributes() {
ConfigCenterConfig cc = new ConfigCenterConfig();
cc.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress());
Map<String, String> attributes = new LinkedHashMap<>();
ConfigCenterConfig.appendAttributes(attributes, cc);
Assertions.assertEquals(cc.getAddress(), attributes.get("address"));
Assertions.assertEquals(cc.getProtocol(), attributes.get("protocol"));
Assertions.assertEquals("" + cc.getPort(), attributes.get("port"));
Assertions.assertEquals(null, attributes.get("valid"));
Assertions.assertEquals(null, attributes.get("refreshed"));
}
@Test
void testSetAddress() {
String address = ZookeeperRegistryCenterConfig.getConnectionAddress();
ConfigCenterConfig cc = new ConfigCenterConfig();
cc.setUsername("user123"); // set username first
cc.setPassword("pass123");
cc.setAddress(address); // set address last, expect did not override username/password
Assertions.assertEquals(address, cc.getAddress());
Assertions.assertEquals("zookeeper", cc.getProtocol());
Assertions.assertEquals(2181, cc.getPort());
Assertions.assertEquals("user123", cc.getUsername());
Assertions.assertEquals("pass123", cc.getPassword());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java | /*
* 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 org.apache.dubbo.config;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_FILTER_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertNull;
class AbstractServiceConfigTest {
@Test
void testVersion() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setVersion("version");
assertThat(serviceConfig.getVersion(), equalTo("version"));
}
@Test
void testGroup() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setGroup("group");
assertThat(serviceConfig.getGroup(), equalTo("group"));
}
@Test
void testDelay() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setDelay(1000);
assertThat(serviceConfig.getDelay(), equalTo(1000));
}
@Test
void testExport() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setExport(true);
assertThat(serviceConfig.getExport(), is(true));
}
@Test
void testWeight() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setWeight(500);
assertThat(serviceConfig.getWeight(), equalTo(500));
}
@Test
void testDocument() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setDocument("http://dubbo.apache.org");
assertThat(serviceConfig.getDocument(), equalTo("http://dubbo.apache.org"));
Map<String, String> parameters = new HashMap<String, String>();
AbstractServiceConfig.appendParameters(parameters, serviceConfig);
assertThat(parameters, hasEntry("document", "http%3A%2F%2Fdubbo.apache.org"));
}
@Test
void testToken() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setToken("token");
assertThat(serviceConfig.getToken(), equalTo("token"));
serviceConfig.setToken((Boolean) null);
assertThat(serviceConfig.getToken(), nullValue());
serviceConfig.setToken(true);
assertThat(serviceConfig.getToken(), is("true"));
}
@Test
void testDeprecated() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setDeprecated(true);
assertThat(serviceConfig.isDeprecated(), is(true));
}
@Test
void testDynamic() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setDynamic(true);
assertThat(serviceConfig.isDynamic(), is(true));
}
@Test
void testProtocol() {
ServiceConfig serviceConfig = new ServiceConfig();
assertThat(serviceConfig.getProtocol(), nullValue());
serviceConfig.setProtocol(new ProtocolConfig());
assertThat(serviceConfig.getProtocol(), notNullValue());
serviceConfig.setProtocols(new ArrayList<>(Collections.singletonList(new ProtocolConfig())));
assertThat(serviceConfig.getProtocols(), hasSize(1));
}
@Test
void testAccesslog() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setAccesslog("access.log");
assertThat(serviceConfig.getAccesslog(), equalTo("access.log"));
serviceConfig.setAccesslog((Boolean) null);
assertThat(serviceConfig.getAccesslog(), nullValue());
serviceConfig.setAccesslog(true);
assertThat(serviceConfig.getAccesslog(), equalTo("true"));
}
@Test
void testExecutes() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setExecutes(10);
assertThat(serviceConfig.getExecutes(), equalTo(10));
}
@Test
void testFilter() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setFilter("mockfilter");
assertThat(serviceConfig.getFilter(), equalTo("mockfilter"));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(SERVICE_FILTER_KEY, "prefilter");
AbstractServiceConfig.appendParameters(parameters, serviceConfig);
assertThat(parameters, hasEntry(SERVICE_FILTER_KEY, "prefilter,mockfilter"));
}
@Test
void testListener() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setListener("mockexporterlistener");
assertThat(serviceConfig.getListener(), equalTo("mockexporterlistener"));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(EXPORTER_LISTENER_KEY, "prelistener");
AbstractServiceConfig.appendParameters(parameters, serviceConfig);
assertThat(parameters, hasEntry(EXPORTER_LISTENER_KEY, "prelistener,mockexporterlistener"));
}
@Test
void testRegister() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setRegister(true);
assertThat(serviceConfig.isRegister(), is(true));
}
@Test
void testWarmup() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setWarmup(100);
assertThat(serviceConfig.getWarmup(), equalTo(100));
}
@Test
void testSerialization() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setSerialization("serialization");
assertThat(serviceConfig.getSerialization(), equalTo("serialization"));
}
@Test
void testPreferSerialization() {
ServiceConfig serviceConfig = new ServiceConfig();
serviceConfig.setPreferSerialization("preferSerialization");
assertThat(serviceConfig.getPreferSerialization(), equalTo("preferSerialization"));
}
@Test
void testPreferSerializationDefault1() {
ServiceConfig serviceConfig = new ServiceConfig();
assertNull(serviceConfig.getPreferSerialization());
serviceConfig.checkDefault();
assertNull(serviceConfig.getPreferSerialization());
serviceConfig = new ServiceConfig();
serviceConfig.setSerialization("x-serialization");
assertNull(serviceConfig.getPreferSerialization());
serviceConfig.checkDefault();
assertThat(serviceConfig.getPreferSerialization(), equalTo("x-serialization"));
}
@Test
void testPreferSerializationDefault2() {
ServiceConfig serviceConfig = new ServiceConfig();
assertNull(serviceConfig.getPreferSerialization());
serviceConfig.refresh();
assertNull(serviceConfig.getPreferSerialization());
serviceConfig = new ServiceConfig();
serviceConfig.setSerialization("x-serialization");
assertNull(serviceConfig.getPreferSerialization());
serviceConfig.refresh();
assertThat(serviceConfig.getPreferSerialization(), equalTo("x-serialization"));
}
private static class ServiceConfig extends AbstractServiceConfig {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
class RegistryConfigTest {
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
}
@AfterEach
public void afterEach() {
SysProps.clear();
}
@Test
void testProtocol() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setProtocol("protocol");
assertThat(registry.getProtocol(), equalTo(registry.getProtocol()));
}
@Test
void testAddress() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1");
assertThat(
registry.getAddress(),
equalTo("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1"));
assertThat(registry.getProtocol(), equalTo("zookeeper"));
assertThat(registry.getUsername(), equalTo("mrh"));
assertThat(registry.getPassword(), equalTo("123"));
assertThat(registry.getParameters().get("k1"), equalTo("v1"));
Map<String, String> parameters = new HashMap<>();
RegistryConfig.appendParameters(parameters, registry);
assertThat(parameters, not(hasKey("address")));
}
@Test
void testUsername() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setUsername("username");
assertThat(registry.getUsername(), equalTo("username"));
}
@Test
void testPassword() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setPassword("password");
assertThat(registry.getPassword(), equalTo("password"));
}
@Test
void testWait() throws Exception {
try {
RegistryConfig registry = new RegistryConfig();
registry.setWait(10);
assertThat(registry.getWait(), is(10));
assertThat(System.getProperty(SHUTDOWN_WAIT_KEY), equalTo("10"));
} finally {
System.clearProperty(SHUTDOWN_TIMEOUT_KEY);
}
}
@Test
void testCheck() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setCheck(true);
assertThat(registry.isCheck(), is(true));
}
@Test
void testFile() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setFile("file");
assertThat(registry.getFile(), equalTo("file"));
}
@Test
void testTransporter() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setTransporter("transporter");
assertThat(registry.getTransporter(), equalTo("transporter"));
}
@Test
void testClient() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setClient("client");
assertThat(registry.getClient(), equalTo("client"));
}
@Test
void testTimeout() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setTimeout(10);
assertThat(registry.getTimeout(), is(10));
}
@Test
void testSession() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setSession(10);
assertThat(registry.getSession(), is(10));
}
@Test
void testDynamic() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setDynamic(true);
assertThat(registry.isDynamic(), is(true));
}
@Test
void testRegister() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setRegister(true);
assertThat(registry.isRegister(), is(true));
}
@Test
void testSubscribe() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setSubscribe(true);
assertThat(registry.isSubscribe(), is(true));
}
@Test
void testCluster() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setCluster("cluster");
assertThat(registry.getCluster(), equalTo("cluster"));
}
@Test
void testGroup() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setGroup("group");
assertThat(registry.getGroup(), equalTo("group"));
}
@Test
void testVersion() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setVersion("1.0.0");
assertThat(registry.getVersion(), equalTo("1.0.0"));
}
@Test
void testParameters() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setParameters(Collections.singletonMap("k1", "v1"));
assertThat(registry.getParameters(), hasEntry("k1", "v1"));
Map<String, String> parameters = new HashMap<String, String>();
RegistryConfig.appendParameters(parameters, registry);
assertThat(parameters, hasEntry("k1", "v1"));
}
@Test
void testDefault() throws Exception {
RegistryConfig registry = new RegistryConfig();
registry.setDefault(true);
assertThat(registry.isDefault(), is(true));
}
@Test
void testEquals() throws Exception {
RegistryConfig registry1 = new RegistryConfig();
RegistryConfig registry2 = new RegistryConfig();
registry1.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress2());
registry2.setAddress("zookeeper://127.0.0.1:2183");
Assertions.assertNotEquals(registry1, registry2);
}
@Test
void testMetaData() {
RegistryConfig config = new RegistryConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
@Test
void testOverrideConfigBySystemProps() {
SysProps.setProperty("dubbo.registry.address", "zookeeper://${zookeeper.address}:${zookeeper.port}");
SysProps.setProperty("dubbo.registry.useAsConfigCenter", "false");
SysProps.setProperty("dubbo.registry.useAsMetadataCenter", "false");
SysProps.setProperty("zookeeper.address", "localhost");
SysProps.setProperty("zookeeper.port", "2188");
DubboBootstrap.getInstance().application("demo-app").initialize();
Collection<RegistryConfig> registries =
ApplicationModel.defaultModel().getApplicationConfigManager().getRegistries();
Assertions.assertEquals(1, registries.size());
RegistryConfig registryConfig = registries.iterator().next();
Assertions.assertEquals("zookeeper://localhost:2188", registryConfig.getAddress());
}
public void testPreferredWithTrueValue() {
RegistryConfig registry = new RegistryConfig();
registry.setPreferred(true);
Map<String, String> map = new HashMap<>();
// process Parameter annotation
AbstractConfig.appendParameters(map, registry);
// Simulate the check that ZoneAwareClusterInvoker#doInvoke do
URL url = UrlUtils.parseURL(ZookeeperRegistryCenterConfig.getConnectionAddress1(), map);
Assertions.assertTrue(url.getParameter(PREFERRED_KEY, false));
}
@Test
void testPreferredWithFalseValue() {
RegistryConfig registry = new RegistryConfig();
registry.setPreferred(false);
Map<String, String> map = new HashMap<>();
// Process Parameter annotation
AbstractConfig.appendParameters(map, registry);
// Simulate the check that ZoneAwareClusterInvoker#doInvoke do
URL url = UrlUtils.parseURL(ZookeeperRegistryCenterConfig.getConnectionAddress1(), map);
Assertions.assertFalse(url.getParameter(PREFERRED_KEY, false));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static java.util.Arrays.asList;
public class DubboShutdownHookTest {
private DubboShutdownHook dubboShutdownHook;
private ApplicationModel applicationModel;
@BeforeEach
public void init() {
SysProps.setProperty(CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK, "false");
FrameworkModel frameworkModel = new FrameworkModel();
applicationModel = frameworkModel.newApplication();
ModuleModel moduleModel = applicationModel.newModule();
dubboShutdownHook = new DubboShutdownHook(applicationModel);
}
@AfterEach
public void clear() {
SysProps.clear();
}
@Test
public void testDubboShutdownHook() {
Assertions.assertNotNull(dubboShutdownHook);
Assertions.assertLinesMatch(asList("DubboShutdownHook"), asList(dubboShutdownHook.getName()));
Assertions.assertFalse(dubboShutdownHook.getRegistered());
}
@Test
public void testDestoryNoModuleManagedExternally() {
boolean hasModuleManagedExternally = false;
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.isLifeCycleManagedExternally()) {
hasModuleManagedExternally = true;
break;
}
}
Assertions.assertFalse(hasModuleManagedExternally);
dubboShutdownHook.run();
Assertions.assertTrue(applicationModel.isDestroyed());
}
@Test
public void testDestoryWithModuleManagedExternally() throws InterruptedException {
applicationModel.getModuleModels().get(0).setLifeCycleManagedExternally(true);
new Thread(() -> {
applicationModel.getModuleModels().get(0).destroy();
})
.start();
TimeUnit.MILLISECONDS.sleep(10);
dubboShutdownHook.run();
Assertions.assertTrue(applicationModel.isDestroyed());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP;
import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
class ApplicationConfigTest {
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
}
@AfterEach
public void afterEach() {
SysProps.clear();
DubboBootstrap.reset();
}
@Test
void testName() {
ApplicationConfig application = new ApplicationConfig();
application.setName("app");
assertThat(application.getName(), equalTo("app"));
assertThat(application.getId(), equalTo(null));
application = new ApplicationConfig("app2");
assertThat(application.getName(), equalTo("app2"));
assertThat(application.getId(), equalTo(null));
Map<String, String> parameters = new HashMap<String, String>();
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry(APPLICATION_KEY, "app2"));
}
@Test
void testVersion() {
ApplicationConfig application = new ApplicationConfig("app");
application.setVersion("1.0.0");
assertThat(application.getVersion(), equalTo("1.0.0"));
Map<String, String> parameters = new HashMap<String, String>();
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry("application.version", "1.0.0"));
}
@Test
void testOwner() {
ApplicationConfig application = new ApplicationConfig("app");
application.setOwner("owner");
assertThat(application.getOwner(), equalTo("owner"));
}
@Test
void testOrganization() {
ApplicationConfig application = new ApplicationConfig("app");
application.setOrganization("org");
assertThat(application.getOrganization(), equalTo("org"));
}
@Test
void testArchitecture() {
ApplicationConfig application = new ApplicationConfig("app");
application.setArchitecture("arch");
assertThat(application.getArchitecture(), equalTo("arch"));
}
@Test
void testEnvironment1() {
ApplicationConfig application = new ApplicationConfig("app");
application.setEnvironment("develop");
assertThat(application.getEnvironment(), equalTo("develop"));
application.setEnvironment("test");
assertThat(application.getEnvironment(), equalTo("test"));
application.setEnvironment("product");
assertThat(application.getEnvironment(), equalTo("product"));
}
@Test
void testEnvironment2() {
Assertions.assertThrows(IllegalStateException.class, () -> {
ApplicationConfig application = new ApplicationConfig("app");
application.setEnvironment("illegal-env");
});
}
@Test
void testRegistry() {
ApplicationConfig application = new ApplicationConfig("app");
RegistryConfig registry = new RegistryConfig();
application.setRegistry(registry);
assertThat(application.getRegistry(), sameInstance(registry));
application.setRegistries(Collections.singletonList(registry));
assertThat(application.getRegistries(), contains(registry));
assertThat(application.getRegistries(), hasSize(1));
}
@Test
void testMonitor() {
ApplicationConfig application = new ApplicationConfig("app");
application.setMonitor(new MonitorConfig("monitor-addr"));
assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr"));
application.setMonitor("monitor-addr");
assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr"));
}
@Test
void testLogger() {
ApplicationConfig application = new ApplicationConfig("app");
application.setLogger("log4j2");
assertThat(application.getLogger(), equalTo("log4j2"));
}
@Test
void testDefault() {
ApplicationConfig application = new ApplicationConfig("app");
application.setDefault(true);
assertThat(application.isDefault(), is(true));
}
@Test
void testDumpDirectory() {
ApplicationConfig application = new ApplicationConfig("app");
application.setDumpDirectory("/dump");
assertThat(application.getDumpDirectory(), equalTo("/dump"));
Map<String, String> parameters = new HashMap<String, String>();
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry(DUMP_DIRECTORY, "/dump"));
}
@Test
void testQosEnable() {
ApplicationConfig application = new ApplicationConfig("app");
application.setQosEnable(true);
assertThat(application.getQosEnable(), is(true));
Map<String, String> parameters = new HashMap<String, String>();
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry(QOS_ENABLE, "true"));
}
@Test
void testQosPort() {
ApplicationConfig application = new ApplicationConfig("app");
application.setQosPort(8080);
assertThat(application.getQosPort(), equalTo(8080));
}
@Test
void testQosAcceptForeignIp() {
ApplicationConfig application = new ApplicationConfig("app");
application.setQosAcceptForeignIp(true);
assertThat(application.getQosAcceptForeignIp(), is(true));
Map<String, String> parameters = new HashMap<String, String>();
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true"));
}
@Test
void testParameters() throws Exception {
ApplicationConfig application = new ApplicationConfig("app");
application.setQosAcceptForeignIp(true);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("k1", "v1");
ApplicationConfig.appendParameters(parameters, application);
assertThat(parameters, hasEntry("k1", "v1"));
assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true"));
}
@Test
void testAppendEnvironmentProperties() {
ApplicationConfig application = new ApplicationConfig("app");
SysProps.setProperty("dubbo.labels", "tag1=value1;tag2=value2 ; tag3 = value3");
application.refresh();
Map<String, String> parameters = application.getParameters();
Assertions.assertEquals("value1", parameters.get("tag1"));
Assertions.assertEquals("value2", parameters.get("tag2"));
Assertions.assertEquals("value3", parameters.get("tag3"));
ApplicationConfig application1 = new ApplicationConfig("app");
SysProps.setProperty("dubbo.env.keys", "tag1, tag2,tag3");
// mock environment variables
SysProps.setProperty("tag1", "value1");
SysProps.setProperty("tag2", "value2");
SysProps.setProperty("tag3", "value3");
application1.refresh();
Map<String, String> parameters1 = application1.getParameters();
Assertions.assertEquals("value2", parameters1.get("tag2"));
Assertions.assertEquals("value3", parameters1.get("tag3"));
Map<String, String> urlParameters = new HashMap<>();
ApplicationConfig.appendParameters(urlParameters, application1);
Assertions.assertEquals("value1", urlParameters.get("tag1"));
Assertions.assertEquals("value2", urlParameters.get("tag2"));
Assertions.assertEquals("value3", urlParameters.get("tag3"));
}
@Test
void testMetaData() {
ApplicationConfig config = new ApplicationConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
@Test
void testOverrideEmptyConfig() {
String owner = "tom1";
SysProps.setProperty("dubbo.application.name", "demo-app");
SysProps.setProperty("dubbo.application.owner", owner);
SysProps.setProperty("dubbo.application.version", "1.2.3");
ApplicationConfig applicationConfig = new ApplicationConfig();
DubboBootstrap.getInstance().application(applicationConfig).initialize();
Assertions.assertEquals(owner, applicationConfig.getOwner());
Assertions.assertEquals("1.2.3", applicationConfig.getVersion());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigById() {
String owner = "tom2";
SysProps.setProperty("dubbo.applications.demo-app.owner", owner);
SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3");
SysProps.setProperty("dubbo.applications.demo-app.name", "demo-app");
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setId("demo-app");
DubboBootstrap.getInstance().application(applicationConfig).initialize();
Assertions.assertEquals("demo-app", applicationConfig.getId());
Assertions.assertEquals("demo-app", applicationConfig.getName());
Assertions.assertEquals(owner, applicationConfig.getOwner());
Assertions.assertEquals("1.2.3", applicationConfig.getVersion());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigByName() {
String owner = "tom3";
SysProps.setProperty("dubbo.applications.demo-app.owner", owner);
SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3");
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("demo-app");
DubboBootstrap.getInstance().application(applicationConfig).initialize();
Assertions.assertEquals(owner, applicationConfig.getOwner());
Assertions.assertEquals("1.2.3", applicationConfig.getVersion());
DubboBootstrap.getInstance().destroy();
}
@Test
void testLoadConfig() {
String owner = "tom4";
SysProps.setProperty("dubbo.applications.demo-app.owner", owner);
SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3");
DubboBootstrap.getInstance().initialize();
ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication();
Assertions.assertEquals("demo-app", applicationConfig.getId());
Assertions.assertEquals("demo-app", applicationConfig.getName());
Assertions.assertEquals(owner, applicationConfig.getOwner());
Assertions.assertEquals("1.2.3", applicationConfig.getVersion());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideConfigConvertCase() {
SysProps.setProperty("dubbo.application.NAME", "demo-app");
SysProps.setProperty("dubbo.application.qos-Enable", "false");
SysProps.setProperty("dubbo.application.qos_host", "127.0.0.1");
SysProps.setProperty("dubbo.application.qosPort", "2345");
DubboBootstrap.getInstance().initialize();
ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication();
Assertions.assertEquals(false, applicationConfig.getQosEnable());
Assertions.assertEquals("127.0.0.1", applicationConfig.getQosHost());
Assertions.assertEquals(2345, applicationConfig.getQosPort());
Assertions.assertEquals("demo-app", applicationConfig.getName());
DubboBootstrap.getInstance().destroy();
}
@Test
void testDefaultValue() {
SysProps.setProperty("dubbo.application.NAME", "demo-app");
DubboBootstrap.getInstance().initialize();
ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication();
Assertions.assertEquals(DUBBO, applicationConfig.getProtocol());
Assertions.assertEquals(EXECUTOR_MANAGEMENT_MODE_ISOLATION, applicationConfig.getExecutorManagementMode());
Assertions.assertEquals(Boolean.TRUE, applicationConfig.getEnableFileCache());
DubboBootstrap.getInstance().destroy();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java | /*
* 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 org.apache.dubbo.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
class ModuleConfigTest {
@Test
void testName2() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setName("module-name");
assertThat(module.getName(), equalTo("module-name"));
assertThat(module.getId(), equalTo(null));
Map<String, String> parameters = new HashMap<String, String>();
ModuleConfig.appendParameters(parameters, module);
assertThat(parameters, hasEntry("module", "module-name"));
}
@Test
void testVersion() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setName("module-name");
module.setVersion("1.0.0");
assertThat(module.getVersion(), equalTo("1.0.0"));
Map<String, String> parameters = new HashMap<String, String>();
ModuleConfig.appendParameters(parameters, module);
assertThat(parameters, hasEntry("module.version", "1.0.0"));
}
@Test
void testOwner() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setOwner("owner");
assertThat(module.getOwner(), equalTo("owner"));
}
@Test
void testOrganization() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setOrganization("org");
assertThat(module.getOrganization(), equalTo("org"));
}
@Test
void testRegistry() throws Exception {
ModuleConfig module = new ModuleConfig();
RegistryConfig registry = new RegistryConfig();
module.setRegistry(registry);
assertThat(module.getRegistry(), sameInstance(registry));
}
@Test
void testRegistries() throws Exception {
ModuleConfig module = new ModuleConfig();
RegistryConfig registry = new RegistryConfig();
module.setRegistries(Collections.singletonList(registry));
assertThat(module.getRegistries(), Matchers.<RegistryConfig>hasSize(1));
assertThat(module.getRegistries(), contains(registry));
}
@Test
void testMonitor() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setMonitor("monitor-addr1");
assertThat(module.getMonitor().getAddress(), equalTo("monitor-addr1"));
module.setMonitor(new MonitorConfig("monitor-addr2"));
assertThat(module.getMonitor().getAddress(), equalTo("monitor-addr2"));
}
@Test
void testDefault() throws Exception {
ModuleConfig module = new ModuleConfig();
module.setDefault(true);
assertThat(module.isDefault(), is(true));
}
@Test
void testMetaData() {
MonitorConfig config = new MonitorConfig();
Map<String, String> metaData = config.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.common.Person;
import org.apache.dubbo.config.provider.impl.DemoServiceImpl;
import org.apache.dubbo.rpc.model.AsyncMethodInfo;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_ATTRIBUTE_KEY;
import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_ATTRIBUTE_KEY;
import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_ATTRIBUTE_KEY;
import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_ATTRIBUTE_KEY;
import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_ATTRIBUTE_KEY;
import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_ATTRIBUTE_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MethodConfigTest {
private static final String METHOD_NAME = "sayHello";
private static final int TIMEOUT = 1300;
private static final int RETRIES = 4;
private static final String LOADBALANCE = "random";
private static final boolean ASYNC = true;
private static final int ACTIVES = 3;
private static final int EXECUTES = 5;
private static final boolean DEPRECATED = true;
private static final boolean STICKY = true;
private static final String ONINVOKE = "invokeNotify";
private static final String ONINVOKE_METHOD = "onInvoke";
private static final String ONTHROW = "throwNotify";
private static final String ONTHROW_METHOD = "onThrow";
private static final String ONRETURN = "returnNotify";
private static final String ONRETURN_METHOD = "onReturn";
private static final String CACHE = "c";
private static final String VALIDATION = "v";
private static final int ARGUMENTS_INDEX = 24;
private static final boolean ARGUMENTS_CALLBACK = true;
private static final String ARGUMENTS_TYPE = "sss";
@Reference(
methods = {
@Method(
name = METHOD_NAME,
timeout = TIMEOUT,
retries = RETRIES,
loadbalance = LOADBALANCE,
async = ASYNC,
actives = ACTIVES,
executes = EXECUTES,
deprecated = DEPRECATED,
sticky = STICKY,
oninvoke = ONINVOKE + "." + ONINVOKE_METHOD,
onthrow = ONTHROW + "." + ONTHROW_METHOD,
onreturn = ONRETURN + "." + ONRETURN_METHOD,
cache = CACHE,
validation = VALIDATION,
arguments = {
@Argument(index = ARGUMENTS_INDEX, callback = ARGUMENTS_CALLBACK, type = ARGUMENTS_TYPE)
})
})
private String testField;
@BeforeEach
public void beforeEach() {
DubboBootstrap.reset();
SysProps.clear();
SysProps.setProperty("dubbo.metrics.enabled", "false");
SysProps.setProperty("dubbo.metrics.protocol", "disabled");
}
@AfterEach
public void afterEach() {
DubboBootstrap.reset();
SysProps.clear();
}
// TODO remove this test
@Test
void testStaticConstructor() throws NoSuchFieldException {
Method[] methods = this.getClass()
.getDeclaredField("testField")
.getAnnotation(Reference.class)
.methods();
List<MethodConfig> methodConfigs = MethodConfig.constructMethodConfig(methods);
MethodConfig methodConfig = methodConfigs.get(0);
assertThat(METHOD_NAME, equalTo(methodConfig.getName()));
assertThat(TIMEOUT, equalTo(methodConfig.getTimeout()));
assertThat(RETRIES, equalTo(methodConfig.getRetries()));
assertThat(LOADBALANCE, equalTo(methodConfig.getLoadbalance()));
assertThat(ASYNC, equalTo(methodConfig.isAsync()));
assertThat(ACTIVES, equalTo(methodConfig.getActives()));
assertThat(EXECUTES, equalTo(methodConfig.getExecutes()));
assertThat(DEPRECATED, equalTo(methodConfig.getDeprecated()));
assertThat(STICKY, equalTo(methodConfig.getSticky()));
assertThat(ONINVOKE, equalTo(methodConfig.getOninvoke()));
assertThat(ONINVOKE_METHOD, equalTo(methodConfig.getOninvokeMethod()));
assertThat(ONTHROW, equalTo(methodConfig.getOnthrow()));
assertThat(ONTHROW_METHOD, equalTo(methodConfig.getOnthrowMethod()));
assertThat(ONRETURN, equalTo(methodConfig.getOnreturn()));
assertThat(ONRETURN_METHOD, equalTo(methodConfig.getOnreturnMethod()));
assertThat(CACHE, equalTo(methodConfig.getCache()));
assertThat(VALIDATION, equalTo(methodConfig.getValidation()));
assertThat(ARGUMENTS_INDEX, equalTo(methodConfig.getArguments().get(0).getIndex()));
assertThat(
ARGUMENTS_CALLBACK, equalTo(methodConfig.getArguments().get(0).isCallback()));
assertThat(ARGUMENTS_TYPE, equalTo(methodConfig.getArguments().get(0).getType()));
}
@Test
void testName() {
MethodConfig method = new MethodConfig();
method.setName("hello");
assertThat(method.getName(), equalTo("hello"));
Map<String, String> parameters = new HashMap<>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters, not(hasKey("name")));
}
@Test
void testStat() {
MethodConfig method = new MethodConfig();
method.setStat(10);
assertThat(method.getStat(), equalTo(10));
}
@Test
void testRetry() {
MethodConfig method = new MethodConfig();
method.setRetry(true);
assertThat(method.isRetry(), is(true));
}
@Test
void testReliable() {
MethodConfig method = new MethodConfig();
method.setReliable(true);
assertThat(method.isReliable(), is(true));
}
@Test
void testExecutes() {
MethodConfig method = new MethodConfig();
method.setExecutes(10);
assertThat(method.getExecutes(), equalTo(10));
}
@Test
void testDeprecated() {
MethodConfig method = new MethodConfig();
method.setDeprecated(true);
assertThat(method.getDeprecated(), is(true));
}
@Test
void testArguments() {
MethodConfig method = new MethodConfig();
ArgumentConfig argument = new ArgumentConfig();
method.setArguments(Collections.singletonList(argument));
assertThat(method.getArguments(), contains(argument));
assertThat(method.getArguments(), Matchers.<ArgumentConfig>hasSize(1));
}
@Test
void testSticky() {
MethodConfig method = new MethodConfig();
method.setSticky(true);
assertThat(method.getSticky(), is(true));
}
@Test
void testConvertMethodConfig2AsyncInfo() throws Exception {
MethodConfig methodConfig = new MethodConfig();
String methodName = "setName";
methodConfig.setOninvokeMethod(methodName);
methodConfig.setOnthrowMethod(methodName);
methodConfig.setOnreturnMethod(methodName);
methodConfig.setOninvoke(new Person());
methodConfig.setOnthrow(new Person());
methodConfig.setOnreturn(new Person());
AsyncMethodInfo methodInfo = methodConfig.convertMethodConfig2AsyncInfo();
assertEquals(methodInfo.getOninvokeMethod(), Person.class.getMethod(methodName, String.class));
assertEquals(methodInfo.getOnthrowMethod(), Person.class.getMethod(methodName, String.class));
assertEquals(methodInfo.getOnreturnMethod(), Person.class.getMethod(methodName, String.class));
}
// @Test
void testOnReturn() {
MethodConfig method = new MethodConfig();
method.setOnreturn("on-return-object");
assertThat(method.getOnreturn(), equalTo("on-return-object"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_RETURN_INSTANCE_ATTRIBUTE_KEY, "on-return-object"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
@Test
void testOnReturnMethod() {
MethodConfig method = new MethodConfig();
method.setOnreturnMethod("on-return-method");
assertThat(method.getOnreturnMethod(), equalTo("on-return-method"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_RETURN_METHOD_ATTRIBUTE_KEY, "on-return-method"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
// @Test
void testOnThrow() {
MethodConfig method = new MethodConfig();
method.setOnthrow("on-throw-object");
assertThat(method.getOnthrow(), equalTo("on-throw-object"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_THROW_INSTANCE_ATTRIBUTE_KEY, "on-throw-object"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
@Test
void testOnThrowMethod() {
MethodConfig method = new MethodConfig();
method.setOnthrowMethod("on-throw-method");
assertThat(method.getOnthrowMethod(), equalTo("on-throw-method"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_THROW_METHOD_ATTRIBUTE_KEY, "on-throw-method"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
// @Test
void testOnInvoke() {
MethodConfig method = new MethodConfig();
method.setOninvoke("on-invoke-object");
assertThat(method.getOninvoke(), equalTo("on-invoke-object"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_INVOKE_INSTANCE_ATTRIBUTE_KEY, "on-invoke-object"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
@Test
void testOnInvokeMethod() {
MethodConfig method = new MethodConfig();
method.setOninvokeMethod("on-invoke-method");
assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method"));
Map<String, String> attributes = new HashMap<>();
MethodConfig.appendAttributes(attributes, method);
assertThat(attributes, hasEntry(ON_INVOKE_METHOD_ATTRIBUTE_KEY, "on-invoke-method"));
Map<String, String> parameters = new HashMap<String, String>();
MethodConfig.appendParameters(parameters, method);
assertThat(parameters.size(), is(0));
}
@Test
void testReturn() {
MethodConfig method = new MethodConfig();
method.setReturn(true);
assertThat(method.isReturn(), is(true));
}
@Test
void testOverrideMethodConfigOfReference() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234");
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true");
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]");
SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false");
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(interfaceName);
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
methodConfig.setTimeout(1000);
referenceConfig.setMethods(Arrays.asList(methodConfig));
DubboBootstrap.getInstance()
.application("demo-app")
.reference(referenceConfig)
.initialize();
Map<String, String> params = new LinkedHashMap<>();
params.put("a", "1");
params.put("b", "2");
Assertions.assertEquals(1234, methodConfig.getTimeout());
Assertions.assertEquals(true, methodConfig.getSticky());
Assertions.assertEquals(params, methodConfig.getParameters());
Assertions.assertEquals(false, referenceConfig.isInit());
}
@Test
void testAddMethodConfigOfReference() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234");
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true");
SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]");
SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false");
ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(interfaceName);
DubboBootstrap.getInstance()
.application("demo-app")
.reference(referenceConfig)
.initialize();
List<MethodConfig> methodConfigs = referenceConfig.getMethods();
Assertions.assertEquals(1, methodConfigs.size());
MethodConfig methodConfig = methodConfigs.get(0);
Map<String, String> params = new LinkedHashMap<>();
params.put("a", "1");
params.put("b", "2");
Assertions.assertEquals(1234, methodConfig.getTimeout());
Assertions.assertEquals(true, methodConfig.getSticky());
Assertions.assertEquals(params, methodConfig.getParameters());
Assertions.assertEquals(false, referenceConfig.isInit());
DubboBootstrap.getInstance().destroy();
}
@Test
void testOverrideMethodConfigOfService() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]");
SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo");
SysProps.setProperty("dubbo.registry.address", "N/A");
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(interfaceName);
serviceConfig.setRef(new DemoServiceImpl());
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayName");
methodConfig.setTimeout(1000);
serviceConfig.setMethods(Collections.singletonList(methodConfig));
DubboBootstrap.getInstance()
.application("demo-app")
.service(serviceConfig)
.initialize();
Map<String, String> params = new LinkedHashMap<>();
params.put("a", "1");
params.put("b", "2");
Assertions.assertEquals(1234, methodConfig.getTimeout());
Assertions.assertEquals(true, methodConfig.getSticky());
Assertions.assertEquals(params, methodConfig.getParameters());
Assertions.assertEquals("demo", serviceConfig.getGroup());
DubboBootstrap.getInstance().destroy();
}
@Test
void testAddMethodConfigOfService() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.0.callback", "true");
SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo");
SysProps.setProperty("dubbo.service." + interfaceName + ".echo", "non-method-config");
SysProps.setProperty("dubbo.registry.address", "N/A");
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(interfaceName);
serviceConfig.setRef(new DemoServiceImpl());
Assertions.assertNull(serviceConfig.getMethods());
DubboBootstrap.getInstance()
.application("demo-app")
.service(serviceConfig)
.initialize();
List<MethodConfig> methodConfigs = serviceConfig.getMethods();
Assertions.assertEquals(1, methodConfigs.size());
MethodConfig methodConfig = methodConfigs.get(0);
List<ArgumentConfig> arguments = methodConfig.getArguments();
Assertions.assertEquals(1, arguments.size());
ArgumentConfig argumentConfig = arguments.get(0);
Map<String, String> params = new LinkedHashMap<>();
params.put("a", "1");
params.put("b", "2");
Assertions.assertEquals("demo", serviceConfig.getGroup());
Assertions.assertEquals(params, methodConfig.getParameters());
Assertions.assertEquals(1234, methodConfig.getTimeout());
Assertions.assertEquals(true, methodConfig.getSticky());
Assertions.assertEquals(0, argumentConfig.getIndex());
Assertions.assertEquals(true, argumentConfig.isCallback());
DubboBootstrap.getInstance().destroy();
}
@Test
void testVerifyMethodConfigOfService() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234");
SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo");
SysProps.setProperty("dubbo.registry.address", "N/A");
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(interfaceName);
serviceConfig.setRef(new DemoServiceImpl());
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayHello");
methodConfig.setTimeout(1000);
serviceConfig.setMethods(Collections.singletonList(methodConfig));
try {
DubboBootstrap.getInstance()
.application("demo-app")
.service(serviceConfig)
.initialize();
Assertions.fail("Method config verification should failed");
} catch (Exception e) {
// ignore
Throwable cause = e.getCause();
Assertions.assertEquals(IllegalStateException.class, cause.getClass());
Assertions.assertTrue(cause.getMessage().contains("not found method"), cause.toString());
} finally {
DubboBootstrap.getInstance().destroy();
}
}
@Test
void testIgnoreInvalidMethodConfigOfService() {
String interfaceName = DemoService.class.getName();
SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234");
SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234");
SysProps.setProperty("dubbo.registry.address", "N/A");
SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "true");
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(interfaceName);
serviceConfig.setRef(new DemoServiceImpl());
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("sayHello");
methodConfig.setTimeout(1000);
serviceConfig.setMethods(Collections.singletonList(methodConfig));
DubboBootstrap.getInstance()
.application("demo-app")
.service(serviceConfig)
.initialize();
// expect sayHello method config will be ignored, and sayName method config will be created.
Assertions.assertEquals(1, serviceConfig.getMethods().size());
Assertions.assertEquals("sayName", serviceConfig.getMethods().get(0).getName());
DubboBootstrap.getInstance().destroy();
}
@Test
void testMetaData() {
MethodConfig methodConfig = new MethodConfig();
Map<String, String> metaData = methodConfig.getMetaData();
Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java | /*
* 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 org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouterFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasValue;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AbstractReferenceConfigTest {
@AfterAll
public static void afterAll() throws Exception {
FrameworkModel.destroyAll();
}
@Test
void testCheck() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setCheck(true);
assertThat(referenceConfig.isCheck(), is(true));
}
@Test
void testInit() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setInit(true);
assertThat(referenceConfig.isInit(), is(true));
}
@Test
void testGeneric() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setGeneric(true);
assertThat(referenceConfig.isGeneric(), is(true));
Map<String, String> parameters = new HashMap<String, String>();
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
// FIXME: not sure why AbstractReferenceConfig has both isGeneric and getGeneric
assertThat(parameters, hasKey("generic"));
}
@Test
void testInjvm() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setInjvm(true);
assertThat(referenceConfig.isInjvm(), is(true));
}
@Test
void testFilter() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setFilter("mockfilter");
assertThat(referenceConfig.getFilter(), equalTo("mockfilter"));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(REFERENCE_FILTER_KEY, "prefilter");
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(parameters, hasValue("prefilter,mockfilter"));
}
@Test
void testRouter() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setRouter("condition");
assertThat(referenceConfig.getRouter(), equalTo("condition"));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(ROUTER_KEY, "tag");
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(parameters, hasValue("tag,condition"));
URL url = mock(URL.class);
when(url.getParameter(ROUTER_KEY)).thenReturn("condition");
List<StateRouterFactory> routerFactories =
ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY);
assertThat(
routerFactories.stream()
.anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionStateRouterFactory.class)),
is(true));
when(url.getParameter(ROUTER_KEY)).thenReturn("-tag,-app");
routerFactories =
ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY);
assertThat(
routerFactories.stream()
.allMatch(routerFactory -> !routerFactory.getClass().equals(TagStateRouterFactory.class)
&& !routerFactory.getClass().equals(AppStateRouterFactory.class)),
is(true));
}
@Test
void testListener() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setListener("mockinvokerlistener");
assertThat(referenceConfig.getListener(), equalTo("mockinvokerlistener"));
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(INVOKER_LISTENER_KEY, "prelistener");
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(parameters, hasValue("prelistener,mockinvokerlistener"));
}
@Test
void testLazy() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setLazy(true);
assertThat(referenceConfig.getLazy(), is(true));
}
@Test
void testOnconnect() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setOnconnect("onConnect");
assertThat(referenceConfig.getOnconnect(), equalTo("onConnect"));
assertThat(referenceConfig.getStubevent(), is(true));
}
@Test
void testOndisconnect() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setOndisconnect("onDisconnect");
assertThat(referenceConfig.getOndisconnect(), equalTo("onDisconnect"));
assertThat(referenceConfig.getStubevent(), is(true));
}
@Test
void testStubevent() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setOnconnect("onConnect");
Map<String, String> parameters = new HashMap<String, String>();
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(parameters, hasKey(STUB_EVENT_KEY));
}
@Test
void testReconnect() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setReconnect("reconnect");
Map<String, String> parameters = new HashMap<String, String>();
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(referenceConfig.getReconnect(), equalTo("reconnect"));
assertThat(parameters, hasKey(Constants.RECONNECT_KEY));
}
@Test
void testSticky() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setSticky(true);
Map<String, String> parameters = new HashMap<String, String>();
AbstractInterfaceConfig.appendParameters(parameters, referenceConfig);
assertThat(referenceConfig.getSticky(), is(true));
assertThat(parameters, hasKey(CLUSTER_STICKY_KEY));
}
@Test
void testVersion() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setVersion("version");
assertThat(referenceConfig.getVersion(), equalTo("version"));
}
@Test
void testGroup() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setGroup("group");
assertThat(referenceConfig.getGroup(), equalTo("group"));
}
@Test
void testGenericOverride() {
ReferenceConfig referenceConfig = new ReferenceConfig();
referenceConfig.setGeneric("false");
referenceConfig.refresh();
Assertions.assertFalse(referenceConfig.isGeneric());
Assertions.assertEquals("false", referenceConfig.getGeneric());
ReferenceConfig referenceConfig1 = new ReferenceConfig();
referenceConfig1.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
referenceConfig1.refresh();
Assertions.assertEquals(GENERIC_SERIALIZATION_NATIVE_JAVA, referenceConfig1.getGeneric());
Assertions.assertTrue(referenceConfig1.isGeneric());
ReferenceConfig referenceConfig2 = new ReferenceConfig();
referenceConfig2.refresh();
Assertions.assertNull(referenceConfig2.getGeneric());
}
private static class ReferenceConfig extends AbstractReferenceConfig {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java | /*
* 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 org.apache.dubbo.config;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Use to set and clear System property
*/
public class SysProps {
private static Map<String, String> map = new LinkedHashMap<String, String>();
public static void reset() {
map.clear();
}
public static void setProperty(String key, String value) {
map.put(key, value);
System.setProperty(key, value);
}
public static void clear() {
for (String key : map.keySet()) {
System.clearProperty(key);
}
reset();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java | /*
* 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 org.apache.dubbo.config.integration;
/**
* The interface for integration testcases.
*/
public interface IntegrationTest {
/**
* Run the integration testcases.
*/
void integrate();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java | /*
* 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 org.apache.dubbo.config.integration;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder;
import org.apache.dubbo.rpc.listener.ListenerExporterWrapper;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* The abstraction of {@link ExporterListener} is to record exported exporters, which should be extended by different sub-classes.
*/
public abstract class AbstractRegistryCenterExporterListener implements ExporterListener {
/**
* Exported exporters.
*/
private List<Exporter<?>> exportedExporters = new ArrayList();
/**
* Resolve all filters
*/
private Set<Filter> filters = new HashSet<>();
/**
* Returns the interface of exported service.
*/
protected abstract Class<?> getInterface();
/**
* {@inheritDoc}
*/
@Override
public void exported(Exporter<?> exporter) throws RpcException {
ListenerExporterWrapper listenerExporterWrapper = (ListenerExporterWrapper) exporter;
Invoker invoker = listenerExporterWrapper.getInvoker();
if (!(invoker instanceof FilterChainBuilder.CallbackRegistrationInvoker)) {
exportedExporters.add(exporter);
return;
}
FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker =
(FilterChainBuilder.CallbackRegistrationInvoker) invoker;
if (callbackRegistrationInvoker == null || callbackRegistrationInvoker.getInterface() != getInterface()) {
return;
}
exportedExporters.add(exporter);
FilterChainBuilder.CopyOfFilterChainNode filterChainNode = getFilterChainNode(callbackRegistrationInvoker);
do {
Filter filter = this.getFilter(filterChainNode);
if (filter != null) {
filters.add(filter);
}
filterChainNode = this.getNextNode(filterChainNode);
} while (filterChainNode != null);
}
/**
* {@inheritDoc}
*/
@Override
public void unexported(Exporter<?> exporter) {
exportedExporters.remove(exporter);
}
/**
* Returns the exported exporters.
*/
public List<Exporter<?>> getExportedExporters() {
return Collections.unmodifiableList(exportedExporters);
}
/**
* Returns all filters
*/
public Set<Filter> getFilters() {
return Collections.unmodifiableSet(filters);
}
/**
* Use reflection to obtain {@link Filter}
*/
private FilterChainBuilder.CopyOfFilterChainNode getFilterChainNode(
FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker) {
if (callbackRegistrationInvoker != null) {
Field field = null;
try {
field = callbackRegistrationInvoker.getClass().getDeclaredField("filterInvoker");
field.setAccessible(true);
return (FilterChainBuilder.CopyOfFilterChainNode) field.get(callbackRegistrationInvoker);
} catch (NoSuchFieldException | IllegalAccessException e) {
// ignore
}
}
return null;
}
/**
* Use reflection to obtain {@link Filter}
*/
private Filter getFilter(FilterChainBuilder.CopyOfFilterChainNode filterChainNode) {
if (filterChainNode != null) {
Field field = null;
try {
field = filterChainNode.getClass().getDeclaredField("filter");
field.setAccessible(true);
return (Filter) field.get(filterChainNode);
} catch (NoSuchFieldException | IllegalAccessException e) {
// ignore
}
}
return null;
}
/**
* Use reflection to obtain {@link FilterChainBuilder.CopyOfFilterChainNode}
*/
private FilterChainBuilder.CopyOfFilterChainNode getNextNode(
FilterChainBuilder.CopyOfFilterChainNode filterChainNode) {
if (filterChainNode != null) {
Field field = null;
try {
field = filterChainNode.getClass().getDeclaredField("nextNode");
field.setAccessible(true);
Object object = field.get(filterChainNode);
if (object instanceof FilterChainBuilder.CopyOfFilterChainNode) {
return (FilterChainBuilder.CopyOfFilterChainNode) object;
}
} catch (NoSuchFieldException | IllegalAccessException e) {
// ignore
}
}
return null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java | /*
* 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 org.apache.dubbo.config.integration;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This implementation of {@link ServiceListener} is to record exported services, which should be extended by different sub-classes.
*/
public abstract class AbstractRegistryCenterServiceListener implements ServiceListener {
private List<ServiceConfig> exportedServices = new ArrayList<>(2);
/**
* Return the interface name of exported service.
*/
protected abstract Class<?> getInterface();
/**
* {@inheritDoc}
*/
@Override
public void exported(ServiceConfig sc) {
// All exported services will be added
if (sc.getInterfaceClass() == getInterface()) {
exportedServices.add(sc);
}
}
/**
* {@inheritDoc}
*/
@Override
public void unexported(ServiceConfig sc) {
// remove the exported services.
exportedServices.remove(sc);
}
/**
* Return all exported services.
*/
public List<ServiceConfig> getExportedServices() {
return Collections.unmodifiableList(exportedServices);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/Constants.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/Constants.java | /*
* 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 org.apache.dubbo.config.integration;
public interface Constants {
String MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY = "multipleConfigCenterServiceDiscoveryRegistry";
String SINGLE_CONFIG_CENTER_EXPORT_PROVIDER = "singleConfigCenterExportProvider";
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/package-info.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/package-info.java | /*
* 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.
*/
/**
* There are two scenario in integration testcases.<p>
* The one is single registry center, the other is multiple registry centers.<p>
* The purpose of all of testcases in this package is to test for multiple registry center.
*/
package org.apache.dubbo.config.integration.multiple;
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java | /*
* 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 org.apache.dubbo.config.integration.multiple;
/**
* This interface to store the given type instance in multiple registry center.
* @param <T> The type to store
*/
public interface Storage<T> {
/**
* Gets the stored instance with the given host and port.
* @param host the host in the register center.
* @param port the port in the register center.
* @return the stored instance.
*/
T get(String host, int port);
/**
* Sets the stored instance with the given host and port as key.
* @param host the host in the register center.
* @param port the port in the register center.
* @param value the instance to store.
*/
void put(String host, int port, T value);
/**
* Checks if the instance exists with the given host and port.
* @param host the host in the register center.
* @param port the port in the register center.
* @return {@code true} if the instance exists with the given host and port, otherwise {@code false}
*/
boolean contains(String host, int port);
/**
* Returns the size of all stored values.
*/
int size();
/**
* Clear all data.
*/
void clear();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java | /*
* 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 org.apache.dubbo.config.integration.multiple;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This abstraction class to implement the basic methods for {@link Storage}.
*
* @param <T> The type to store
*/
public abstract class AbstractStorage<T> implements Storage<T> {
private Map<String, T> storage = new ConcurrentHashMap<>();
/**
* Generate the key for storage
*
* @param host the host in the register center.
* @param port the port in the register center.
* @return the generated key with the given host and port.
*/
private String generateKey(String host, int port) {
return String.format("%s:%d", host, port);
}
/**
* {@inheritDoc}
*/
@Override
public T get(String host, int port) {
return storage.get(generateKey(host, port));
}
/**
* {@inheritDoc}
*/
@Override
public void put(String host, int port, T value) {
storage.put(generateKey(host, port), value);
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(String host, int port) {
return storage.containsKey(generateKey(host, port));
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return storage.size();
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
storage.clear();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.registry.integration.RegistryProtocolListener;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The testcases are only for checking the core process of exporting provider.
*/
class MultipleRegistryCenterExportProviderIntegrationTest implements IntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(MultipleRegistryCenterExportProviderIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-for-export-provider";
/**
* The name for getting the specified instance, which is loaded using SPI.
*/
private static String SPI_NAME = "multipleConfigCenterExportProvider";
/**
* Define the protocol's name.
*/
private static String PROTOCOL_NAME = CommonConstants.DUBBO;
/**
* Define the protocol's port.
*/
private static int PROTOCOL_PORT = 20800;
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<MultipleRegistryCenterExportProviderService> serviceConfig;
/**
* Define a {@link RegistryProtocolListener} instance.
*/
private MultipleRegistryCenterExportProviderRegistryProtocolListener registryProtocolListener;
/**
* Define a {@link ExporterListener} instance.
*/
private MultipleRegistryCenterExportProviderExporterListener exporterListener;
/**
* Define a {@link Filter} instance.
*/
private MultipleRegistryCenterExportProviderFilter filter;
/**
* Define a {@link ServiceListener} instance.
*/
private MultipleRegistryCenterExportProviderServiceListener serviceListener;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MultipleRegistryCenterExportProviderService.class);
serviceConfig.setRef(new MultipleRegistryCenterExportProviderServiceImpl());
serviceConfig.setAsync(false);
// initialize bootstrap
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT))
.service(serviceConfig)
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()))
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()));
}
/**
* There are some checkpoints need to verify as follow:
* <ul>
* <li>ServiceConfig is exported or not</li>
* <li>MultipleRegistryCenterExportProviderRegistryProtocolListener is null or not</li>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* </ul>
*/
private void beforeExport() {
registryProtocolListener = (MultipleRegistryCenterExportProviderRegistryProtocolListener)
ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)
.getExtension(SPI_NAME);
exporterListener = (MultipleRegistryCenterExportProviderExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME);
filter = (MultipleRegistryCenterExportProviderFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME);
serviceListener = (MultipleRegistryCenterExportProviderServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME);
// ---------------checkpoints--------------- //
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
// registryProtocolListener is just initialized by SPI
// so, all of fields are the default value.
Assertions.assertNotNull(registryProtocolListener);
Assertions.assertFalse(registryProtocolListener.isExported());
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
ReferenceConfig<MultipleRegistryCenterExportProviderService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MultipleRegistryCenterExportProviderService.class);
referenceConfig.get().hello(PROVIDER_APPLICATION_NAME);
afterInvoke();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>the exporter is exported or not</li>
* <li>The exported exporter are three</li>
* <li>The exported service is MultipleRegistryCenterExportProviderService or not</li>
* <li>The MultipleRegistryCenterExportProviderService is exported or not</li>
* <li>The exported exporter contains MultipleRegistryCenterExportProviderFilter or not</li>
* </ul>
*/
private void afterExport() {
// The exporter is exported
Assertions.assertTrue(registryProtocolListener.isExported());
// The exported service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is MultipleRegistryCenterExportProviderService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(),
MultipleRegistryCenterExportProviderService.class);
// The MultipleRegistryCenterExportProviderService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// The exported exporter are three
// 1. InjvmExporter
// 2. DubboExporter with service-discovery-registry protocol
// 3. DubboExporter with registry protocol
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 4);
// The exported exporter contains MultipleRegistryCenterExportProviderFilter
Assertions.assertTrue(exporterListener.getFilters().contains(filter));
// The consumer can be notified and get provider's metadata through metadata mapping info.
// So, the metadata mapping is necessary to check after exported service (or provider)
// The best way to verify this issue is to check if the exported service (or provider)
// has been registered in the path of /dubbo/mapping/****
// FixME We should check if the exported service (or provider) has been registered in multiple registry centers.
// However, the registered exporter are override in RegistryProtocol#export, so there is only the first
// registry center
// that can register the mapping relationship. This is really a problem that needs to be fix.
// Now, we are discussing the solution for this issue.
// For this testcase, we still check the only exported service (or provider).
// all testcase below are temporary and will be replaced after the above problem is fixed.
// What are the parameters?
// registryKey: the registryKey is the default cluster, CommonConstants.DEFAULT_KEY
// key: The exported interface's name
// group: the group is "mapping", ServiceNameMapping.DEFAULT_MAPPING_GROUP
ConfigItem configItem = ApplicationModel.defaultModel()
.getBeanFactory()
.getBean(MetadataReportInstance.class)
.getMetadataReport(CommonConstants.DEFAULT_KEY)
.getConfigItem(serviceConfig.getInterface(), ServiceNameMapping.DEFAULT_MAPPING_GROUP);
// Check if the exported service (provider) is registered
Assertions.assertNotNull(configItem);
// Check if registered service (provider)'s name is right
Assertions.assertEquals(PROVIDER_APPLICATION_NAME, configItem.getContent());
// Check if registered service (provider)'s version exists
Assertions.assertNotNull(configItem.getTicket());
}
/**
* There are some checkpoints need to check after invoked as follow:
* <ul>
* <li>The MultipleRegistryCenterExportProviderFilter has called or not</li>
* <li>The MultipleRegistryCenterExportProviderFilter exists error after invoked</li>
* <li>The MultipleRegistryCenterExportProviderFilter's response is right or not</li>
* </ul>
*/
private void afterInvoke() {
// The MultipleRegistryCenterExportProviderFilter has called
Assertions.assertTrue(filter.hasCalled());
// The MultipleRegistryCenterExportProviderFilter doesn't exist error
Assertions.assertFalse(filter.hasError());
// Check the MultipleRegistryCenterExportProviderFilter's response
Assertions.assertEquals("Hello " + PROVIDER_APPLICATION_NAME, filter.getResponse());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
logger.info(getClass().getSimpleName() + " testcase is ending...");
registryProtocolListener = null;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.registry.integration.RegistryProtocolListener;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
/**
* The {@link RegistryProtocolListener} for {@link MultipleRegistryCenterExportProviderService}
*/
@Activate(order = 100)
public class MultipleRegistryCenterExportProviderRegistryProtocolListener implements RegistryProtocolListener {
private boolean exported = false;
/**
* {@inheritDoc}
*/
@Override
public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {
if (registryProtocol instanceof InterfaceCompatibleRegistryProtocol
&& exporter != null
&& exporter.getInvoker() != null
&& exporter.getInvoker().getInterface().equals(MultipleRegistryCenterExportProviderService.class)) {
this.exported = true;
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL) {}
/**
* {@inheritDoc}
*/
@Override
public void onDestroy() {}
/**
* Returns if this exporter is exported.
*/
public boolean isExported() {
return exported;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderExporterListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderExporterListener.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class MultipleRegistryCenterExportProviderExporterListener extends AbstractRegistryCenterExporterListener {
/**
* Returns the interface of exported service.
*/
@Override
protected Class<?> getInterface() {
return MultipleRegistryCenterExportProviderService.class;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceListener.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener;
/**
* This implementation of {@link ServiceListener} is to record exported services with injvm protocol in single registry center.
*/
public class MultipleRegistryCenterExportProviderServiceListener extends AbstractRegistryCenterServiceListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return MultipleRegistryCenterExportProviderService.class;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
@Activate(group = CommonConstants.PROVIDER, order = 10001)
public class MultipleRegistryCenterExportProviderFilter implements Filter, Filter.Listener {
/**
* The filter is called or not
*/
private boolean called = false;
/**
* There has error after invoked
*/
private boolean error = false;
/**
* The returned result
*/
private String response;
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*
* @param invoker
* @param invocation
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
called = true;
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
response = String.valueOf(appResponse.getValue());
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
error = true;
}
/**
* Returns if the filter has called.
*/
public boolean hasCalled() {
return called;
}
/**
* Returns if there exists error.
*/
public boolean hasError() {
return error;
}
/**
* Returns the response.
*/
public String getResponse() {
return response;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderService.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderService.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
/**
* This interface is used to check if the exported provider works well or not in multiple registry center.
*/
public interface MultipleRegistryCenterExportProviderService {
/**
* The simple method for testing.
*/
String hello(String name);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceImpl.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceImpl.java | /*
* 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 org.apache.dubbo.config.integration.multiple.exportprovider;
/**
* The implementation of {@link MultipleRegistryCenterExportProviderService}
*/
public class MultipleRegistryCenterExportProviderServiceImpl implements MultipleRegistryCenterExportProviderService {
/**
* {@inheritDoc}
*/
@Override
public String hello(String name) {
return "Hello " + name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java | /*
* 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 org.apache.dubbo.config.integration.multiple.injvm;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
@Activate(group = CommonConstants.PROVIDER, order = 10200)
public class MultipleRegistryCenterInjvmFilter implements Filter, Filter.Listener {
/**
* The filter is called or not
*/
private boolean called = false;
/**
* There has error after invoked
*/
private boolean error = false;
/**
* The returned result
*/
private String response;
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*
* @param invoker
* @param invocation
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
called = true;
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
response = String.valueOf(appResponse.getValue());
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
error = true;
}
/**
* Returns if the filter has called.
*/
public boolean hasCalled() {
return called;
}
/**
* Returns if there exists error.
*/
public boolean hasError() {
return error;
}
/**
* Returns the response.
*/
public String getResponse() {
return response;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java | /*
* 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 org.apache.dubbo.config.integration.multiple.injvm;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceListener;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.integration.IntegrationTest;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
/**
* The testcases are only for checking the process of exporting provider using injvm protocol.
*/
class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterInjvmIntegrationTest.class);
/**
* Define the provider application name.
*/
private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-injvm-protocol";
/**
* The name for getting the specified instance, which is loaded using SPI.
*/
private static String SPI_NAME = "multipleConfigCenterInjvm";
/**
* Define the {@link ServiceConfig} instance.
*/
private ServiceConfig<MultipleRegistryCenterInjvmService> serviceConfig;
/**
* The listener to record exported services
*/
private MultipleRegistryCenterInjvmServiceListener serviceListener;
/**
* The listener to record exported exporters.
*/
private MultipleRegistryCenterInjvmExporterListener exporterListener;
/**
* The filter for checking filter chain.
*/
private MultipleRegistryCenterInjvmFilter filter;
@BeforeEach
public void setUp() throws Exception {
logger.info(getClass().getSimpleName() + " testcase is beginning...");
DubboBootstrap.reset();
// initialize service config
serviceConfig = new ServiceConfig<>();
serviceConfig.setInterface(MultipleRegistryCenterInjvmService.class);
serviceConfig.setRef(new MultipleRegistryCenterInjvmServiceImpl());
serviceConfig.setAsync(false);
serviceConfig.setScope(SCOPE_LOCAL);
DubboBootstrap.getInstance()
.application(new ApplicationConfig(PROVIDER_APPLICATION_NAME))
.protocol(new ProtocolConfig("injvm"))
.service(serviceConfig)
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()))
.registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()));
}
/**
* Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check.
* <p>Use SPI to load them before exporting.
* <p>After that, there are some checkpoints need to verify as follow:
* <ul>
* <li>There is nothing in ServiceListener or not</li>
* <li>There is nothing in ExporterListener or not</li>
* <li>ServiceConfig is exported or not</li>
* </ul>
*/
private void beforeExport() {
// ---------------initialize--------------- //
serviceListener = (MultipleRegistryCenterInjvmServiceListener)
ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME);
exporterListener = (MultipleRegistryCenterInjvmExporterListener)
ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME);
filter = (MultipleRegistryCenterInjvmFilter)
ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME);
// ---------------checkpoints--------------- //
// There is nothing in ServiceListener
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
// There is nothing in ExporterListener
Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty());
// ServiceConfig isn't exported
Assertions.assertFalse(serviceConfig.isExported());
}
/**
* {@inheritDoc}
*/
@Test
@Override
public void integrate() {
beforeExport();
DubboBootstrap.getInstance().start();
afterExport();
ReferenceConfig<MultipleRegistryCenterInjvmService> referenceConfig = new ReferenceConfig<>();
referenceConfig.setInterface(MultipleRegistryCenterInjvmService.class);
referenceConfig.setScope(SCOPE_LOCAL);
referenceConfig.get().hello("Dubbo in multiple registry center");
afterInvoke();
}
/**
* There are some checkpoints need to check after exported as follow:
* <ul>
* <li>The exported service is only one or not</li>
* <li>The exported service is MultipleRegistryCenterInjvmService or not</li>
* <li>The MultipleRegistryCenterInjvmService is exported or not</li>
* <li>The exported exporter is only one or not</li>
* <li>The exported exporter contains MultipleRegistryCenterInjvmFilter or not</li>
* </ul>
*/
private void afterExport() {
// The exported service is only one
Assertions.assertEquals(serviceListener.getExportedServices().size(), 1);
// The exported service is MultipleRegistryCenterInjvmService
Assertions.assertEquals(
serviceListener.getExportedServices().get(0).getInterfaceClass(),
MultipleRegistryCenterInjvmService.class);
// The MultipleRegistryCenterInjvmService is exported
Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported());
// The exported exporter is only one
Assertions.assertEquals(exporterListener.getExportedExporters().size(), 3);
// The exported exporter contains MultipleRegistryCenterInjvmFilter
Assertions.assertTrue(exporterListener.getFilters().contains(filter));
}
/**
* There are some checkpoints need to check after invoked as follow:
* <ul>
* <li>The MultipleRegistryCenterInjvmFilter has called or not</li>
* <li>The MultipleRegistryCenterInjvmFilter exists error after invoked</li>
* <li>The MultipleRegistryCenterInjvmFilter's response is right or not</li>
* </ul>
*/
private void afterInvoke() {
// The MultipleRegistryCenterInjvmFilter has called
Assertions.assertTrue(filter.hasCalled());
// The MultipleRegistryCenterInjvmFilter doesn't exist error
Assertions.assertFalse(filter.hasError());
// Check the MultipleRegistryCenterInjvmFilter's response
Assertions.assertEquals("Hello Dubbo in multiple registry center", filter.getResponse());
}
@AfterEach
public void tearDown() throws IOException {
DubboBootstrap.reset();
serviceConfig = null;
// The exported service has been unexported
Assertions.assertTrue(serviceListener.getExportedServices().isEmpty());
serviceListener = null;
logger.info(getClass().getSimpleName() + " testcase is ending...");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmExporterListener.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmExporterListener.java | /*
* 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 org.apache.dubbo.config.integration.multiple.injvm;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener;
@Activate(group = CommonConstants.PROVIDER, order = 1000)
public class MultipleRegistryCenterInjvmExporterListener extends AbstractRegistryCenterExporterListener {
/**
* {@inheritDoc}
*/
@Override
protected Class<?> getInterface() {
return MultipleRegistryCenterInjvmService.class;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.