implements
+ ApplicationContextAware, ApplicationEventPublisherAware, EnvironmentAware {
- // Use default implementation
- if (NacosConfigConverter.class.equals(converterClass)) {
- configConverter = new DefaultNacosConfigConverter(targetType, conversionService, type);
+ /**
+ * The bean name of {@link NacosConfigListenerMethodProcessor}
+ */
+ public static final String BEAN_NAME = "nacosConfigListenerMethodProcessor";
- } else {
- // Use customized implementation
- configConverter = (NacosConfigConverter) instantiateClass(converterClass);
+ /**
+ * The bean name of {@link ConversionService} for Nacos Configuration
+ */
+ public static final String NACOS_CONFIG_CONVERSION_SERVICE_BEAN_NAME = "nacosConfigConversionService";
- }
+ private Properties globalNacosProperties;
- return configConverter;
- }
+ private NacosServiceFactory nacosServiceFactory;
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- globalNacosProperties = CONFIG.getMergedGlobalProperties(applicationContext);
- nacosServiceFactory = getNacosServiceFactoryBean(applicationContext);
- conversionService = determineConversionService(applicationContext);
- configServiceBeanBuilder = getConfigServiceBeanBuilder(applicationContext);
- }
+ private ConversionService conversionService;
+
+ private ConfigServiceBeanBuilder configServiceBeanBuilder;
- private ConversionService determineConversionService(ApplicationContext applicationContext) {
+ private Environment environment;
+
+ private ApplicationEventPublisher applicationEventPublisher;
+
+ @Override
+ protected void processListenerMethod(String beanName, final Object bean,
+ Class> beanClass, final NacosConfigListener listener, final Method method,
+ ApplicationContext applicationContext) {
+
+ final String dataId = NacosUtils.readFromEnvironment(listener.dataId(),
+ environment);
+ final String groupId = NacosUtils.readFromEnvironment(listener.groupId(),
+ environment);
+ final String type = StringUtils.isEmpty(NacosUtils.readTypeFromDataId(dataId))
+ ? listener.type().getType()
+ : NacosUtils.readTypeFromDataId(dataId);
+ long timeout = listener.timeout();
+
+ Assert.isTrue(StringUtils.hasText(dataId), "dataId must have content");
+ Assert.isTrue(StringUtils.hasText(groupId), "groupId must have content");
+ Assert.isTrue(timeout > 0, "timeout must be greater than zero");
+
+ ConfigService configService = configServiceBeanBuilder
+ .build(listener.properties());
+
+ try {
+ configService.addListener(dataId, groupId,
+ new TimeoutNacosConfigListener(dataId, groupId, timeout) {
+
+ @Override
+ protected void onReceived(String config) {
+ Class> targetType = method.getParameterTypes()[0];
+ NacosConfigConverter configConverter = determineNacosConfigConverter(
+ targetType, listener, type);
+ Object parameterValue = configConverter.convert(config);
+ // Execute target method
+ ReflectionUtils.invokeMethod(method, bean, parameterValue);
+ }
+ });
+ }
+ catch (NacosException e) {
+ logger.error("ConfigService can't add Listener for dataId : " + dataId
+ + " , groupId : " + groupId, e);
+ }
- String beanName = NACOS_CONFIG_CONVERSION_SERVICE_BEAN_NAME;
+ publishMetadataEvent(beanName, bean, beanClass, dataId, groupId, listener,
+ method);
- ConversionService conversionService = applicationContext.containsBean(beanName) ?
- applicationContext.getBean(beanName, ConversionService.class) : null;
+ }
+
+ private void publishMetadataEvent(String beanName, Object bean, Class> beanClass,
+ String dataId, String groupId, NacosConfigListener listener, Method method) {
+
+ NacosProperties nacosProperties = listener.properties();
+
+ Properties resolvedNacosProperties = configServiceBeanBuilder
+ .resolveProperties(nacosProperties);
+
+ NacosConfigMetadataEvent metadataEvent = new NacosConfigMetadataEvent(listener);
+
+ // Nacos Metadata
+ metadataEvent.setDataId(dataId);
+ metadataEvent.setGroupId(groupId);
+
+ Map nacosPropertiesAttributes = getAnnotationAttributes(
+ nacosProperties);
+ metadataEvent.setNacosPropertiesAttributes(nacosPropertiesAttributes);
+ metadataEvent.setNacosProperties(resolvedNacosProperties);
- if (conversionService == null) {
- conversionService = new DefaultFormattingConversionService();
- }
+ // Bean Metadata
+ metadataEvent.setBeanName(beanName);
+ metadataEvent.setBean(bean);
+ metadataEvent.setBeanType(beanClass);
+ metadataEvent.setAnnotatedElement(method);
+
+ // Publish event
+ applicationEventPublisher.publishEvent(metadataEvent);
+ }
+
+ private ConfigService resolveConfigService(Properties nacosProperties,
+ ApplicationContext applicationContext) throws BeansException {
+
+ ConfigService configService = null;
+
+ try {
+ configService = nacosServiceFactory.createConfigService(nacosProperties);
+ }
+ catch (NacosException e) {
+ throw new BeanCreationException(e.getErrMsg(), e);
+ }
+
+ return configService;
+ }
+
+ @Override
+ protected boolean isCandidateMethod(Object bean, Class> beanClass,
+ NacosConfigListener listener, Method method,
+ ApplicationContext applicationContext) {
+ Class>[] parameterTypes = method.getParameterTypes();
+
+ if (parameterTypes.length != 1) { // Only one argument on method
+ if (logger.isWarnEnabled()) {
+ logger.warn("Listener method [" + method
+ + "] parameters' count must be one !");
+ }
+ return false;
+ }
+
+ Class> targetType = parameterTypes[0];
+
+ NacosConfigConverter configConverter = determineNacosConfigConverter(targetType,
+ listener, listener.type().getType());
+
+ if (!configConverter.canConvert(targetType)) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("Listener method [" + method
+ + "] is not a candidate , thus its parameter type [" + targetType
+ + "] can't be converted , please check NacosConfigConverter implementation : "
+ + configConverter.getClass().getName());
+ }
+ }
+
+ return true;
+ }
+
+ private NacosConfigConverter determineNacosConfigConverter(Class> targetType,
+ NacosConfigListener listener, String type) {
+
+ Class> converterClass = listener.converter();
+
+ NacosConfigConverter configConverter = null;
+
+ // Use default implementation
+ if (NacosConfigConverter.class.equals(converterClass)) {
+ configConverter = new DefaultNacosConfigConverter(targetType,
+ conversionService, type);
+
+ }
+ else {
+ // Use customized implementation
+ configConverter = (NacosConfigConverter) instantiateClass(converterClass);
- return conversionService;
- }
+ }
- @Override
- public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
- this.applicationEventPublisher = applicationEventPublisher;
- }
+ return configConverter;
+ }
- @Override
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext)
+ throws BeansException {
+ globalNacosProperties = CONFIG.getMergedGlobalProperties(applicationContext);
+ nacosServiceFactory = getNacosServiceFactoryBean(applicationContext);
+ conversionService = determineConversionService(applicationContext);
+ configServiceBeanBuilder = getConfigServiceBeanBuilder(applicationContext);
+ }
+
+ private ConversionService determineConversionService(
+ ApplicationContext applicationContext) {
+
+ String beanName = NACOS_CONFIG_CONVERSION_SERVICE_BEAN_NAME;
+
+ ConversionService conversionService = applicationContext.containsBean(beanName)
+ ? applicationContext.getBean(beanName, ConversionService.class)
+ : null;
+
+ if (conversionService == null) {
+ conversionService = new DefaultFormattingConversionService();
+ }
+
+ return conversionService;
+ }
+
+ @Override
+ public void setApplicationEventPublisher(
+ ApplicationEventPublisher applicationEventPublisher) {
+ this.applicationEventPublisher = applicationEventPublisher;
+ }
+
+ @Override
+ public void setEnvironment(Environment environment) {
+ this.environment = environment;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource.java
index a625d268..4781ebdc 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource.java
@@ -16,19 +16,24 @@
*/
package com.alibaba.nacos.spring.context.annotation.config;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.util.Map;
+
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.spring.context.annotation.EnableNacos;
import com.alibaba.nacos.spring.util.NacosUtils;
-import org.springframework.core.env.PropertySource;
-import java.lang.annotation.*;
-import java.util.Map;
+import org.springframework.core.env.PropertySource;
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
import static com.alibaba.nacos.spring.util.NacosUtils.DEFAULT_BOOLEAN_ATTRIBUTE_VALUE;
-import static com.alibaba.nacos.spring.util.NacosUtils.DEFAULT_CONFIG_TYPE_VALUE;
import static com.alibaba.nacos.spring.util.NacosUtils.DEFAULT_STRING_ATTRIBUTE_VALUE;
/**
@@ -39,134 +44,133 @@
* @see org.springframework.context.annotation.PropertySource
* @since 0.1.0
*/
-@Target({ElementType.TYPE})
+@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(NacosPropertySources.class)
public @interface NacosPropertySource {
- /**
- * The attribute name of {@link NacosPropertySource#name()}
- */
- String NAME_ATTRIBUTE_NAME = "name";
-
- /**
- * The attribute name of {@link NacosPropertySource#groupId()}
- */
- String GROUP_ID_ATTRIBUTE_NAME = "groupId";
-
- /**
- * The attribute name of {@link NacosPropertySource#dataId()}
- */
- String DATA_ID_ATTRIBUTE_NAME = "dataId";
-
- /**
- * The attribute name of {@link NacosPropertySource#autoRefreshed()}
- */
- String AUTO_REFRESHED_ATTRIBUTE_NAME = "autoRefreshed";
-
- /**
- * The attribute name of {@link NacosPropertySource#first()}
- */
- String FIRST_ATTRIBUTE_NAME = "first";
-
- /**
- * The attribute name of {@link NacosPropertySource#before()}
- */
- String BEFORE_ATTRIBUTE_NAME = "before";
-
- /**
- * The attribute name of {@link NacosPropertySource#after()}
- */
- String AFTER_ATTRIBUTE_NAME = "after";
-
- /**
- * The attribute name of {@link NacosPropertySource#properties()}
- */
- String PROPERTIES_ATTRIBUTE_NAME = "properties";
-
- /**
- * The attribute name of {@link NacosPropertySource#type()} ()}
- */
- String CONFIG_TYPE_ATTRIBUTE_NAME = "type";
-
- /**
- * The name of Nacos {@link PropertySource}
- * If absent , the default name will be built from
- * {@link #dataId() dataId}, {@link #groupId() groupid} and {@link #properties() properties} by
- * {@link NacosUtils#buildDefaultPropertySourceName(String, String, Map)} method
- *
- * @return default value is ""
- */
- String name() default DEFAULT_STRING_ATTRIBUTE_VALUE;
-
- /**
- * Nacos Group ID
- *
- * @return default value {@link Constants#DEFAULT_GROUP};
- */
- String groupId() default DEFAULT_GROUP;
-
- /**
- * Nacos Data ID
- *
- * @return required value.
- */
- String dataId();
-
- /**
- * It indicates the property source is auto-refreshed when Nacos configuration is changed.
- *
- * @return default value is false
- */
- boolean autoRefreshed() default DEFAULT_BOOLEAN_ATTRIBUTE_VALUE;
-
- /**
- * Indicates current Nacos {@link PropertySource} is first order or not
- * If specified , {@link #before()} and {@link #after()} will be ignored, or
- * last order.
- *
- * @return default value is false
- */
- boolean first() default DEFAULT_BOOLEAN_ATTRIBUTE_VALUE;
-
- /**
- * The relative order before specified {@link PropertySource}
- *
- * If not specified , current Nacos {@link PropertySource} will be added last.
- *
- * If {@link #first()} specified , current attribute will be ignored.
- *
- * @return the name of {@link PropertySource}
- */
- String before() default DEFAULT_STRING_ATTRIBUTE_VALUE;
-
- /**
- * The relative order after specified {@link PropertySource}
- *
- * If not specified , current Nacos {@link PropertySource} will be added last.
- *
- * If {@link #first()} specified , current attribute will be ignored.
- *
- * @return the name of {@link PropertySource}
- */
- String after() default DEFAULT_STRING_ATTRIBUTE_VALUE;
-
- /**
- * The type of config
- *
- * @return the type of config
- */
- ConfigType type() default ConfigType.PROPERTIES;
-
- /**
- * The {@link NacosProperties} attribute, If not specified, it will use
- * {@link EnableNacos#globalProperties() global Nacos Properties}.
- *
- * @return the default value is {@link NacosProperties}
- * @see EnableNacos#globalProperties()
- */
- NacosProperties properties() default @NacosProperties;
-
+ /**
+ * The attribute name of {@link NacosPropertySource#name()}
+ */
+ String NAME_ATTRIBUTE_NAME = "name";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#groupId()}
+ */
+ String GROUP_ID_ATTRIBUTE_NAME = "groupId";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#dataId()}
+ */
+ String DATA_ID_ATTRIBUTE_NAME = "dataId";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#autoRefreshed()}
+ */
+ String AUTO_REFRESHED_ATTRIBUTE_NAME = "autoRefreshed";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#first()}
+ */
+ String FIRST_ATTRIBUTE_NAME = "first";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#before()}
+ */
+ String BEFORE_ATTRIBUTE_NAME = "before";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#after()}
+ */
+ String AFTER_ATTRIBUTE_NAME = "after";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#properties()}
+ */
+ String PROPERTIES_ATTRIBUTE_NAME = "properties";
+
+ /**
+ * The attribute name of {@link NacosPropertySource#type()} ()}
+ */
+ String CONFIG_TYPE_ATTRIBUTE_NAME = "type";
+
+ /**
+ * The name of Nacos {@link PropertySource} If absent , the default name will be built
+ * from {@link #dataId() dataId}, {@link #groupId() groupid} and {@link #properties()
+ * properties} by
+ * {@link NacosUtils#buildDefaultPropertySourceName(String, String, Map)} method
+ *
+ * @return default value is ""
+ */
+ String name() default DEFAULT_STRING_ATTRIBUTE_VALUE;
+
+ /**
+ * Nacos Group ID
+ *
+ * @return default value {@link Constants#DEFAULT_GROUP};
+ */
+ String groupId() default DEFAULT_GROUP;
+
+ /**
+ * Nacos Data ID
+ *
+ * @return required value.
+ */
+ String dataId();
+
+ /**
+ * It indicates the property source is auto-refreshed when Nacos configuration is
+ * changed.
+ *
+ * @return default value is false
+ */
+ boolean autoRefreshed() default DEFAULT_BOOLEAN_ATTRIBUTE_VALUE;
+
+ /**
+ * Indicates current Nacos {@link PropertySource} is first order or not If specified ,
+ * {@link #before()} and {@link #after()} will be ignored, or last order.
+ *
+ * @return default value is false
+ */
+ boolean first() default DEFAULT_BOOLEAN_ATTRIBUTE_VALUE;
+
+ /**
+ * The relative order before specified {@link PropertySource}
+ *
+ * If not specified , current Nacos {@link PropertySource} will be added last.
+ *
+ * If {@link #first()} specified , current attribute will be ignored.
+ *
+ * @return the name of {@link PropertySource}
+ */
+ String before() default DEFAULT_STRING_ATTRIBUTE_VALUE;
+
+ /**
+ * The relative order after specified {@link PropertySource}
+ *
+ * If not specified , current Nacos {@link PropertySource} will be added last.
+ *
+ * If {@link #first()} specified , current attribute will be ignored.
+ *
+ * @return the name of {@link PropertySource}
+ */
+ String after() default DEFAULT_STRING_ATTRIBUTE_VALUE;
+
+ /**
+ * The type of config
+ *
+ * @return the type of config
+ */
+ ConfigType type() default ConfigType.PROPERTIES;
+
+ /**
+ * The {@link NacosProperties} attribute, If not specified, it will use
+ * {@link EnableNacos#globalProperties() global Nacos Properties}.
+ *
+ * @return the default value is {@link NacosProperties}
+ * @see EnableNacos#globalProperties()
+ */
+ NacosProperties properties() default @NacosProperties;
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceBuilder.java
index 05515739..9b447124 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceBuilder.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceBuilder.java
@@ -16,18 +16,19 @@
*/
package com.alibaba.nacos.spring.context.annotation.config;
+import java.util.Properties;
+
import com.alibaba.nacos.spring.factory.NacosServiceFactory;
import com.alibaba.nacos.spring.util.config.NacosConfigLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;
-import java.util.Properties;
-
import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosServiceFactoryBean;
import static com.alibaba.nacos.spring.util.NacosUtils.buildDefaultPropertySourceName;
import static com.alibaba.nacos.spring.util.NacosUtils.toProperties;
@@ -42,95 +43,94 @@
*/
class NacosPropertySourceBuilder {
- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());
- private String name;
+ private String name;
- private String dataId;
+ private String dataId;
- private String groupId;
+ private String groupId;
- private String type;
+ private String type;
- private Properties properties;
+ private Properties properties;
- private ConfigurableEnvironment environment;
+ private ConfigurableEnvironment environment;
- private BeanFactory beanFactory;
+ private BeanFactory beanFactory;
- private NacosConfigLoader nacosConfigLoader;
+ private NacosConfigLoader nacosConfigLoader;
- public NacosPropertySourceBuilder name(String name) {
- this.name = name;
- return this;
- }
+ public NacosPropertySourceBuilder name(String name) {
+ this.name = name;
+ return this;
+ }
- public NacosPropertySourceBuilder dataId(String dataId) {
- this.dataId = dataId;
- return this;
- }
+ public NacosPropertySourceBuilder dataId(String dataId) {
+ this.dataId = dataId;
+ return this;
+ }
- public NacosPropertySourceBuilder groupId(String groupId) {
- this.groupId = groupId;
- return this;
- }
+ public NacosPropertySourceBuilder groupId(String groupId) {
+ this.groupId = groupId;
+ return this;
+ }
- public NacosPropertySourceBuilder properties(Properties properties) {
- this.properties = properties;
- return this;
- }
+ public NacosPropertySourceBuilder properties(Properties properties) {
+ this.properties = properties;
+ return this;
+ }
- public NacosPropertySourceBuilder type(String type) {
- this.type = type;
- return this;
- }
+ public NacosPropertySourceBuilder type(String type) {
+ this.type = type;
+ return this;
+ }
- public NacosPropertySourceBuilder environment(ConfigurableEnvironment environment) {
- this.environment = environment;
- return this;
- }
+ public NacosPropertySourceBuilder environment(ConfigurableEnvironment environment) {
+ this.environment = environment;
+ return this;
+ }
- public NacosPropertySourceBuilder beanFactory(BeanFactory beanFactory) {
- this.beanFactory = beanFactory;
- return this;
- }
+ public NacosPropertySourceBuilder beanFactory(BeanFactory beanFactory) {
+ this.beanFactory = beanFactory;
+ return this;
+ }
- /**
- * Build Nacos {@link PropertySource}
- *
- * @return if Nacos config is absent , return null
- */
- public PropertySource build() {
+ /**
+ * Build Nacos {@link PropertySource}
+ *
+ * @return if Nacos config is absent , return null
+ */
+ public PropertySource build() {
- nacosConfigLoader = new NacosConfigLoader(environment);
+ nacosConfigLoader = new NacosConfigLoader(environment);
- NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory);
+ NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory);
- nacosConfigLoader.setNacosServiceFactory(nacosServiceFactory);
+ nacosConfigLoader.setNacosServiceFactory(nacosServiceFactory);
- String config = nacosConfigLoader.load(dataId, groupId, properties);
+ String config = nacosConfigLoader.load(dataId, groupId, properties);
- if (!StringUtils.hasText(config)) {
- if (logger.isWarnEnabled()) {
- logger.warn(format("There is no content for Nacos PropertySource from dataId[%s] , groupId[%s] , properties[%s].",
- dataId,
- groupId,
- properties));
- }
- return null;
- }
+ if (!StringUtils.hasText(config)) {
+ if (logger.isWarnEnabled()) {
+ logger.warn(format(
+ "There is no content for Nacos PropertySource from dataId[%s] , groupId[%s] , properties[%s].",
+ dataId, groupId, properties));
+ }
+ return null;
+ }
- Properties properties = toProperties(dataId, groupId, config, type);
+ Properties properties = toProperties(dataId, groupId, config, type);
- if (!StringUtils.hasText(name)) {
- name = buildDefaultPropertySourceName(dataId, groupId, properties);
- }
+ if (!StringUtils.hasText(name)) {
+ name = buildDefaultPropertySourceName(dataId, groupId, properties);
+ }
- return new PropertiesPropertySource(name, properties);
- }
+ return new PropertiesPropertySource(name, properties);
+ }
- public NacosConfigLoader getNacosConfigLoader() {
- return nacosConfigLoader;
- }
+ public NacosConfigLoader getNacosConfigLoader() {
+ return nacosConfigLoader;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySources.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySources.java
index efc3ab86..29b8a0fc 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySources.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySources.java
@@ -16,7 +16,11 @@
*/
package com.alibaba.nacos.spring.context.annotation.config;
-import java.lang.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;
/**
* Multiple {@link NacosPropertySource @NacosPropertySource} annotations.
@@ -24,15 +28,15 @@
* @author Mercy
* @since 0.1.0
*/
-@Target({ElementType.TYPE})
+@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosPropertySources {
- /**
- * Multiple {@link NacosPropertySource @NacosPropertySource}
- *
- * @return {@link NacosPropertySource @NacosPropertySource} array
- */
- NacosPropertySource[] value();
+ /**
+ * Multiple {@link NacosPropertySource @NacosPropertySource}
+ *
+ * @return {@link NacosPropertySource @NacosPropertySource} array
+ */
+ NacosPropertySource[] value();
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosRefresh.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosRefresh.java
new file mode 100644
index 00000000..a827f951
--- /dev/null
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosRefresh.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.nacos.spring.context.annotation.config;
+
+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;
+
+/**
+ * @author liaochuntao
+ * @since 0.3.5
+ */
+@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface NacosRefresh {
+}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosValueAnnotationBeanPostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosValueAnnotationBeanPostProcessor.java
index 31cb2f26..c7025ea9 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosValueAnnotationBeanPostProcessor.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosValueAnnotationBeanPostProcessor.java
@@ -16,37 +16,19 @@
*/
package com.alibaba.nacos.spring.context.annotation.config;
-import com.alibaba.nacos.api.config.annotation.NacosValue;
-import com.alibaba.nacos.client.config.utils.MD5;
-import com.alibaba.nacos.spring.context.event.config.NacosConfigReceivedEvent;
-import com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.BeansException;
-import org.springframework.beans.TypeConverter;
-import org.springframework.beans.factory.BeanFactory;
-import org.springframework.beans.factory.BeanFactoryAware;
-import org.springframework.beans.factory.annotation.InjectionMetadata;
-import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.EnvironmentAware;
-import org.springframework.core.MethodParameter;
-import org.springframework.core.env.Environment;
-import org.springframework.util.ReflectionUtils;
-
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import static com.alibaba.nacos.spring.util.NacosUtils.toProperties;
-import static org.springframework.core.annotation.AnnotationUtils.getAnnotation;
+import com.alibaba.nacos.api.config.annotation.NacosValue;
+import com.alibaba.nacos.spring.util.ObjectUtils;
+import com.alibaba.nacos.spring.util.Tuple;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.InjectionMetadata;
/**
* {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
@@ -55,276 +37,77 @@
* @see NacosValue
* @since 0.1.0
*/
-public class NacosValueAnnotationBeanPostProcessor extends AnnotationInjectedBeanPostProcessor
- implements BeanFactoryAware, EnvironmentAware, ApplicationListener {
-
- private final Logger logger = LoggerFactory.getLogger(getClass());
-
- /**
- * The name of {@link NacosValueAnnotationBeanPostProcessor} bean
- */
- public static final String BEAN_NAME = "nacosValueAnnotationBeanPostProcessor";
-
- private static final String PLACEHOLDER_PREFIX = "${";
-
- private static final String PLACEHOLDER_SUFFIX = "}";
-
- private static final String VALUE_SEPARATOR = ":";
-
- /**
- * placeholder, nacosValueTarget
- */
- private Map> placeholderNacosValueTargetMap
- = new HashMap>();
-
- private ConfigurableListableBeanFactory beanFactory;
-
- private Environment environment;
-
- @Override
- protected Object doGetInjectedBean(NacosValue annotation, Object bean, String beanName, Class> injectedType,
- InjectionMetadata.InjectedElement injectedElement) {
- String annotationValue = annotation.value();
- String value = beanFactory.resolveEmbeddedValue(annotationValue);
-
- Member member = injectedElement.getMember();
- if (member instanceof Field) {
- return convertIfNecessary((Field) member, value);
- }
-
- if (member instanceof Method) {
- return convertIfNecessary((Method) member, value);
- }
-
- return null;
- }
-
- @Override
- protected String buildInjectedObjectCacheKey(NacosValue annotation, Object bean, String beanName,
- Class> injectedType,
- InjectionMetadata.InjectedElement injectedElement) {
- return bean.getClass().getName() + annotation;
- }
-
- @Override
- public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
- if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
- throw new IllegalArgumentException(
- "NacosValueAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
- }
- this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
- }
-
- @Override
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
-
- @Override
- public Object postProcessBeforeInitialization(Object bean, final String beanName)
- throws BeansException {
-
- doWithFields(bean, beanName);
-
- doWithMethods(bean, beanName);
-
- return super.postProcessBeforeInitialization(bean, beanName);
- }
-
- @Override
- public void onApplicationEvent(NacosConfigReceivedEvent event) {
- // In to this event receiver, the environment has been updated the
- // latest configuration information, pull directly from the environment
- // fix issue #142
- for (Map.Entry> entry : placeholderNacosValueTargetMap.entrySet()) {
- String key = environment.resolvePlaceholders(entry.getKey());
- String newValue = environment.getProperty(key);
- if (newValue == null) {
- continue;
- }
- List beanPropertyList = entry.getValue();
- for (NacosValueTarget target : beanPropertyList) {
- String md5String = MD5.getInstance().getMD5String(newValue);
- boolean isUpdate = !target.lastMD5.equals(md5String);
- if (isUpdate) {
- target.updateLastMD5(md5String);
- if (target.method == null) {
- setField(target, newValue);
- } else {
- setMethod(target, newValue);
- }
- }
- }
- }
- }
-
- private Object convertIfNecessary(Field field, Object value) {
- TypeConverter converter = beanFactory.getTypeConverter();
- return converter.convertIfNecessary(value, field.getType(), field);
- }
-
- private Object convertIfNecessary(Method method, Object value) {
- Class>[] paramTypes = method.getParameterTypes();
- Object[] arguments = new Object[paramTypes.length];
-
- TypeConverter converter = beanFactory.getTypeConverter();
-
- if (arguments.length == 1) {
- return converter.convertIfNecessary(value, paramTypes[0], new MethodParameter(method, 0));
- }
-
- for (int i = 0; i < arguments.length; i++) {
- arguments[i] = converter.convertIfNecessary(value, paramTypes[i], new MethodParameter(method, i));
- }
-
- return arguments;
- }
-
- private void doWithFields(final Object bean, final String beanName) {
- ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
- @Override
- public void doWith(Field field) throws IllegalArgumentException {
- NacosValue annotation = getAnnotation(field, NacosValue.class);
- doWithAnnotation(beanName, bean, annotation, field.getModifiers(), null, field);
- }
- });
- }
-
- private void doWithMethods(final Object bean, final String beanName) {
- ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
- @Override
- public void doWith(Method method) throws IllegalArgumentException {
- NacosValue annotation = getAnnotation(method, NacosValue.class);
- doWithAnnotation(beanName, bean, annotation, method.getModifiers(), method, null);
- }
- });
- }
-
- private void doWithAnnotation(String beanName, Object bean, NacosValue annotation, int modifiers, Method method,
- Field field) {
- if (annotation != null) {
- if (Modifier.isStatic(modifiers)) {
- return;
- }
-
- if (annotation.autoRefreshed()) {
- String placeholder = resolvePlaceholder(annotation.value());
-
- if (placeholder == null) {
- return;
- }
-
- NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName, method, field);
- put2ListMap(placeholderNacosValueTargetMap, placeholder, nacosValueTarget);
- }
- }
- }
-
- private String resolvePlaceholder(String placeholder) {
- if (!placeholder.startsWith(PLACEHOLDER_PREFIX)) {
- return null;
- }
-
- if (!placeholder.endsWith(PLACEHOLDER_SUFFIX)) {
- return null;
- }
-
- if (placeholder.length() <= PLACEHOLDER_PREFIX.length() + PLACEHOLDER_SUFFIX.length()) {
- return null;
- }
-
- int beginIndex = PLACEHOLDER_PREFIX.length();
- int endIndex = placeholder.length() - PLACEHOLDER_PREFIX.length() + 1;
- placeholder = placeholder.substring(beginIndex, endIndex);
-
- int separatorIndex = placeholder.indexOf(VALUE_SEPARATOR);
- if (separatorIndex != -1) {
- return placeholder.substring(0, separatorIndex);
- }
-
- return placeholder;
- }
-
- private void put2ListMap(Map> map, K key, V value) {
- List valueList = map.get(key);
- if (valueList == null) {
- valueList = new ArrayList();
- }
- valueList.add(value);
- map.put(key, valueList);
- }
-
- private void setMethod(NacosValueTarget nacosValueTarget, String propertyValue) {
- Method method = nacosValueTarget.method;
- ReflectionUtils.makeAccessible(method);
- try {
- method.invoke(nacosValueTarget.bean, convertIfNecessary(method, propertyValue));
-
- if (logger.isDebugEnabled()) {
- logger.debug("Update value with {} (method) in {} (bean) with {}",
- method.getName(), nacosValueTarget.beanName, propertyValue);
- }
- } catch (Throwable e) {
- if (logger.isErrorEnabled()) {
- logger.error(
- "Can't update value with " + method.getName() + " (method) in "
- + nacosValueTarget.beanName + " (bean)", e);
- }
- }
- }
-
- private void setField(final NacosValueTarget nacosValueTarget, final String propertyValue) {
- final Object bean = nacosValueTarget.bean;
-
- Field field = nacosValueTarget.field;
-
- String fieldName = field.getName();
-
- try {
- ReflectionUtils.makeAccessible(field);
- field.set(bean, convertIfNecessary(field, propertyValue));
-
- if (logger.isDebugEnabled()) {
- logger.debug("Update value of the {}" + " (field) in {} (bean) with {}",
- fieldName, nacosValueTarget.beanName, propertyValue);
- }
- } catch (Throwable e) {
- if (logger.isErrorEnabled()) {
- logger.error(
- "Can't update value of the " + fieldName + " (field) in "
- + nacosValueTarget.beanName + " (bean)", e);
- }
- }
- }
-
- private static class NacosValueTarget {
-
- private final Object bean;
-
- private final String beanName;
-
- private final Method method;
-
- private final Field field;
-
- private String lastMD5;
-
- NacosValueTarget(Object bean, String beanName, Method method, Field field) {
- this.bean = bean;
-
- this.beanName = beanName;
-
- this.method = method;
-
- this.field = field;
-
- this.lastMD5 = "";
- }
-
- protected void updateLastMD5(String newMD5) {
- this.lastMD5 = newMD5;
- }
-
- }
+public class NacosValueAnnotationBeanPostProcessor
+ extends ValueAnnotationBeanPostProcessor {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ /**
+ * The name of {@link NacosValueAnnotationBeanPostProcessor} bean
+ */
+ public static final String BEAN_NAME = "nacosValueAnnotationBeanPostProcessor";
+
+ @Override
+ protected Object doGetInjectedBean(NacosValue annotation, Object bean,
+ String beanName, Class> injectedType,
+ InjectionMetadata.InjectedElement injectedElement) {
+ String annotationValue = annotation.value();
+ String value = beanFactory.resolveEmbeddedValue(annotationValue);
+
+ Member member = injectedElement.getMember();
+ if (member instanceof Field) {
+ return ObjectUtils.convertIfNecessary(beanFactory, (Field) member, value);
+ }
+
+ if (member instanceof Method) {
+ return ObjectUtils.convertIfNecessary(beanFactory, (Method) member, value);
+ }
+
+ return null;
+ }
+
+ @Override
+ protected String buildInjectedObjectCacheKey(NacosValue annotation, Object bean,
+ String beanName, Class> injectedType,
+ InjectionMetadata.InjectedElement injectedElement) {
+ return bean.getClass().getName() + annotation;
+ }
+
+ @Override
+ protected Tuple doWithAnnotation(String beanName,
+ Object bean, NacosValue annotation, int modifiers, Method method,
+ Field field) {
+ if (annotation != null) {
+ if (Modifier.isStatic(modifiers)) {
+ return Tuple.empty();
+ }
+
+ if (annotation.autoRefreshed()) {
+ String placeholder = resolvePlaceholder(annotation.value());
+
+ if (placeholder == null) {
+ return Tuple.empty();
+ }
+
+ NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName,
+ method, field);
+ nacosValueTarget.setAnnotationType(getAnnotationType().getSimpleName());
+ logger.debug("@NacosValue register auto refresh");
+ return Tuple.of(placeholder, nacosValueTarget);
+ }
+ }
+ return Tuple.empty();
+ }
+
+ @Override
+ public Object postProcessBeforeInitialization(Object bean, final String beanName)
+ throws BeansException {
+
+ doWithFields(bean, beanName, NacosValue.class);
+
+ doWithMethods(bean, beanName, NacosValue.class);
+
+ return super.postProcessBeforeInitialization(bean, beanName);
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/SpringValueAnnotationBeanPostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/SpringValueAnnotationBeanPostProcessor.java
new file mode 100644
index 00000000..618d008c
--- /dev/null
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/SpringValueAnnotationBeanPostProcessor.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.nacos.spring.context.annotation.config;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import com.alibaba.nacos.spring.util.ObjectUtils;
+import com.alibaba.nacos.spring.util.Tuple;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.InjectionMetadata;
+import org.springframework.beans.factory.annotation.Value;
+
+/**
+ * Support @ Value automatically refresh
+ *
+ * @author liaochuntao
+ * @since 0.3.4
+ */
+public class SpringValueAnnotationBeanPostProcessor
+ extends ValueAnnotationBeanPostProcessor {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ /**
+ * The name of {@link SpringValueAnnotationBeanPostProcessor} bean
+ */
+ public static final String BEAN_NAME = "springValueAnnotationBeanPostProcessor";
+
+ @Override
+ protected Object doGetInjectedBean(Value value, Object bean, String beanName,
+ Class> injectedType, InjectionMetadata.InjectedElement injectedElement)
+ throws Exception {
+ String annotationValue = value.value();
+ String placeHolder = beanFactory.resolveEmbeddedValue(annotationValue);
+
+ Member member = injectedElement.getMember();
+ if (member instanceof Field) {
+ return ObjectUtils.convertIfNecessary(beanFactory, (Field) member,
+ placeHolder);
+ }
+
+ if (member instanceof Method) {
+ return ObjectUtils.convertIfNecessary(beanFactory, (Method) member,
+ placeHolder);
+ }
+
+ return null;
+ }
+
+ @Override
+ protected String buildInjectedObjectCacheKey(Value value, Object bean,
+ String beanName, Class> injectedType,
+ InjectionMetadata.InjectedElement injectedElement) {
+ return bean.getClass().getName() + value;
+ }
+
+ @Override
+ protected Tuple doWithAnnotation(String beanName,
+ Object bean, Value annotation, int modifiers, Method method, Field field) {
+ if (annotation != null) {
+ if (Modifier.isStatic(modifiers)) {
+ return Tuple.empty();
+ }
+
+ if (bean.getClass().isAnnotationPresent(NacosRefresh.class)) {
+ String placeholder = resolvePlaceholder(annotation.value());
+
+ if (placeholder == null) {
+ return Tuple.empty();
+ }
+
+ NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName,
+ method, field);
+ nacosValueTarget.setAnnotationType(getAnnotationType().getSimpleName());
+ logger.debug("@Value register auto refresh");
+ return Tuple.of(placeholder, nacosValueTarget);
+ }
+ }
+ return Tuple.empty();
+ }
+
+ @Override
+ public Object postProcessBeforeInitialization(Object bean, String beanName)
+ throws BeansException {
+
+ doWithFields(bean, beanName, Value.class);
+
+ doWithMethods(bean, beanName, Value.class);
+
+ return super.postProcessBeforeInitialization(bean, beanName);
+ }
+}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/ValueAnnotationBeanPostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/ValueAnnotationBeanPostProcessor.java
new file mode 100644
index 00000000..42103256
--- /dev/null
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/ValueAnnotationBeanPostProcessor.java
@@ -0,0 +1,295 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.alibaba.nacos.spring.context.annotation.config;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.alibaba.nacos.client.config.utils.MD5;
+import com.alibaba.nacos.spring.context.event.config.NacosConfigReceivedEvent;
+import com.alibaba.nacos.spring.util.ObjectUtils;
+import com.alibaba.nacos.spring.util.Tuple;
+import com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor;
+import com.google.common.base.Objects;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.BeanFactoryAware;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.EnvironmentAware;
+import org.springframework.core.env.Environment;
+import org.springframework.util.ReflectionUtils;
+
+import static org.springframework.core.annotation.AnnotationUtils.getAnnotation;
+
+/**
+ * Abstract @*Value annotation injection and refresh
+ *
+ * @author liaochuntao
+ * @since 0.3.4
+ */
+public abstract class ValueAnnotationBeanPostProcessor
+ extends AnnotationInjectedBeanPostProcessor implements BeanFactoryAware,
+ EnvironmentAware, ApplicationListener {
+
+ private final Logger logger = LoggerFactory.getLogger(getClass());
+
+ private static final String PLACEHOLDER_PREFIX = "${";
+
+ private static final String PLACEHOLDER_SUFFIX = "}";
+
+ private static final String VALUE_SEPARATOR = ":";
+
+ protected Map> placeholderNacosValueTargetMap = new HashMap>();
+
+ protected ConfigurableListableBeanFactory beanFactory;
+ protected Environment environment;
+
+ @Override
+ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+ if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
+ throw new IllegalArgumentException(
+ "ValueAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
+ }
+ this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
+ }
+
+ @Override
+ public void setEnvironment(Environment environment) {
+ this.environment = environment;
+ }
+
+ private void put2ListMap(String key, NacosValueTarget value) {
+ if (key == null || value == null) {
+ return;
+ }
+ List valueList = placeholderNacosValueTargetMap.get(key);
+ if (valueList == null) {
+ valueList = new ArrayList();
+ }
+ valueList.add(value);
+ placeholderNacosValueTargetMap.put(key, valueList);
+ }
+
+ protected void setMethod(NacosValueTarget nacosValueTarget, String propertyValue) {
+ Method method = nacosValueTarget.method;
+ ReflectionUtils.makeAccessible(method);
+ try {
+ method.invoke(nacosValueTarget.bean,
+ ObjectUtils.convertIfNecessary(beanFactory, method, propertyValue));
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("Update value with {} (method) in {} (bean) with {}",
+ method.getName(), nacosValueTarget.beanName, propertyValue);
+ }
+ }
+ catch (Throwable e) {
+ if (logger.isErrorEnabled()) {
+ logger.error("Can't update value with " + method.getName()
+ + " (method) in " + nacosValueTarget.beanName + " (bean)", e);
+ }
+ }
+ }
+
+ protected void setField(final NacosValueTarget nacosValueTarget,
+ final String propertyValue) {
+ final Object bean = nacosValueTarget.bean;
+
+ Field field = nacosValueTarget.field;
+
+ String fieldName = field.getName();
+
+ try {
+ ReflectionUtils.makeAccessible(field);
+ field.set(bean,
+ ObjectUtils.convertIfNecessary(beanFactory, field, propertyValue));
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("Update value of the {}" + " (field) in {} (bean) with {}",
+ fieldName, nacosValueTarget.beanName, propertyValue);
+ }
+ }
+ catch (Throwable e) {
+ if (logger.isErrorEnabled()) {
+ logger.error("Can't update value of the " + fieldName + " (field) in "
+ + nacosValueTarget.beanName + " (bean)", e);
+ }
+ }
+ }
+
+ protected void doWithFields(final Object bean, final String beanName,
+ final Class aClass) {
+ ReflectionUtils.doWithFields(bean.getClass(),
+ new ReflectionUtils.FieldCallback() {
+ @Override
+ public void doWith(Field field) throws IllegalArgumentException {
+ A annotation = getAnnotation(field, aClass);
+ Tuple tuple = doWithAnnotation(beanName,
+ bean, annotation, field.getModifiers(), null, field);
+ put2ListMap(tuple.getFirst(), tuple.getSecond());
+ }
+ });
+ }
+
+ protected void doWithMethods(final Object bean, final String beanName,
+ final Class aClass) {
+ ReflectionUtils.doWithMethods(bean.getClass(),
+ new ReflectionUtils.MethodCallback() {
+ @Override
+ public void doWith(Method method) throws IllegalArgumentException {
+ A annotation = getAnnotation(method, aClass);
+ Tuple tuple = doWithAnnotation(beanName,
+ bean, annotation, method.getModifiers(), method, null);
+ put2ListMap(tuple.getFirst(), tuple.getSecond());
+ }
+ });
+ }
+
+ protected abstract Tuple doWithAnnotation(String beanName,
+ Object bean, A annotation, int modifiers, Method method, Field field);
+
+ protected String resolvePlaceholder(String placeholder) {
+ if (!placeholder.startsWith(PLACEHOLDER_PREFIX)) {
+ return null;
+ }
+
+ if (!placeholder.endsWith(PLACEHOLDER_SUFFIX)) {
+ return null;
+ }
+
+ if (placeholder.length() <= PLACEHOLDER_PREFIX.length()
+ + PLACEHOLDER_SUFFIX.length()) {
+ return null;
+ }
+
+ int beginIndex = PLACEHOLDER_PREFIX.length();
+ int endIndex = placeholder.length() - PLACEHOLDER_PREFIX.length() + 1;
+ placeholder = placeholder.substring(beginIndex, endIndex);
+
+ int separatorIndex = placeholder.indexOf(VALUE_SEPARATOR);
+ if (separatorIndex != -1) {
+ return placeholder.substring(0, separatorIndex);
+ }
+
+ return placeholder;
+ }
+
+ @Override
+ public void onApplicationEvent(NacosConfigReceivedEvent event) {
+ // In to this event receiver, the environment has been updated the
+ // latest configuration information, pull directly from the environment
+ // fix issue #142
+ for (Map.Entry> entry : placeholderNacosValueTargetMap
+ .entrySet()) {
+ String key = environment.resolvePlaceholders(entry.getKey());
+ String newValue = environment.getProperty(key);
+ if (newValue == null) {
+ continue;
+ }
+ List beanPropertyList = entry.getValue();
+ for (NacosValueTarget target : beanPropertyList) {
+ String md5String = MD5.getInstance().getMD5String(newValue);
+ if (isChange(md5String, target)) {
+ target.updateLastMD5(md5String);
+ if (target.getMethod() == null) {
+ setField(target, newValue);
+ }
+ else {
+ setMethod(target, newValue);
+ }
+ }
+ }
+ }
+ }
+
+ public static class NacosValueTarget {
+
+ private final Object bean;
+
+ private final String beanName;
+
+ private final Method method;
+
+ private final Field field;
+
+ private String lastMD5;
+
+ private String annotationType;
+
+ public Object getBean() {
+ return bean;
+ }
+
+ public String getBeanName() {
+ return beanName;
+ }
+
+ public Method getMethod() {
+ return method;
+ }
+
+ public Field getField() {
+ return field;
+ }
+
+ public String getLastMD5() {
+ return lastMD5;
+ }
+
+ public void setLastMD5(String lastMD5) {
+ this.lastMD5 = lastMD5;
+ }
+
+ public String getAnnotationType() {
+ return annotationType;
+ }
+
+ public void setAnnotationType(String annotationType) {
+ this.annotationType = annotationType;
+ }
+
+ NacosValueTarget(Object bean, String beanName, Method method, Field field) {
+ this.bean = bean;
+
+ this.beanName = beanName;
+
+ this.method = method;
+
+ this.field = field;
+
+ this.lastMD5 = "";
+ }
+
+ protected void updateLastMD5(String newMD5) {
+ this.lastMD5 = newMD5;
+ }
+
+ }
+
+ protected static boolean isChange(String newMd5, NacosValueTarget target) {
+ return !Objects.equal(newMd5, target.lastMD5);
+ }
+
+}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscovery.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscovery.java
index 76a6afa2..f3041bf1 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscovery.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscovery.java
@@ -16,14 +16,26 @@
*/
package com.alibaba.nacos.spring.context.annotation.discovery;
+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 com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.NacosBeanDefinitionRegistrar;
-import org.springframework.context.annotation.Import;
-import java.lang.annotation.*;
+import org.springframework.context.annotation.Import;
-import static com.alibaba.nacos.api.annotation.NacosProperties.*;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ACCESS_KEY;
+import static com.alibaba.nacos.api.annotation.NacosProperties.CLUSTER_NAME;
+import static com.alibaba.nacos.api.annotation.NacosProperties.CONTEXT_PATH;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ENCODE;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ENDPOINT;
+import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE;
+import static com.alibaba.nacos.api.annotation.NacosProperties.SECRET_KEY;
+import static com.alibaba.nacos.api.annotation.NacosProperties.SERVER_ADDR;
/**
* Annotation for enabling Nacos discovery features.
@@ -32,81 +44,78 @@
* @see NacosBeanDefinitionRegistrar
* @since 0.1.0
*/
-@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
+@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(NacosDiscoveryBeanDefinitionRegistrar.class)
public @interface EnableNacosDiscovery {
- /**
- * The prefix of property name of Nacos discovery
- */
- String DISCOVERY_PREFIX = NacosProperties.PREFIX + "discovery.";
-
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.endpoint:${nacos.endpoint:}}"
- */
- String ENDPOINT_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ENDPOINT + ":" + NacosProperties.ENDPOINT_PLACEHOLDER + "}";
+ /**
+ * The prefix of property name of Nacos discovery
+ */
+ String DISCOVERY_PREFIX = NacosProperties.PREFIX + "discovery.";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.namespace:${nacos.namespace:}}"
- */
- String NAMESPACE_PLACEHOLDER = "${" + DISCOVERY_PREFIX + NAMESPACE + ":" + NacosProperties.NAMESPACE_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.endpoint:${nacos.endpoint:}}"
+ */
+ String ENDPOINT_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ENDPOINT + ":"
+ + NacosProperties.ENDPOINT_PLACEHOLDER + "}";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.access-key:${nacos.access-key:}}"
- */
- String ACCESS_KEY_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ACCESS_KEY +":" + NacosProperties.ACCESS_KEY_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.namespace:${nacos.namespace:}}"
+ */
+ String NAMESPACE_PLACEHOLDER = "${" + DISCOVERY_PREFIX + NAMESPACE + ":"
+ + NacosProperties.NAMESPACE_PLACEHOLDER + "}";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.secret-key:${nacos.secret-key:}}"
- */
- String SECRET_KEY_PLACEHOLDER = "${" + DISCOVERY_PREFIX + SECRET_KEY + ":" + NacosProperties.SECRET_KEY_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.access-key:${nacos.access-key:}}"
+ */
+ String ACCESS_KEY_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ACCESS_KEY + ":"
+ + NacosProperties.ACCESS_KEY_PLACEHOLDER + "}";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.server-addr:${nacos.server-addr:}}"
- */
- String SERVER_ADDR_PLACEHOLDER = "${" + DISCOVERY_PREFIX + SERVER_ADDR + ":" + NacosProperties.SERVER_ADDR_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.secret-key:${nacos.secret-key:}}"
+ */
+ String SECRET_KEY_PLACEHOLDER = "${" + DISCOVERY_PREFIX + SECRET_KEY + ":"
+ + NacosProperties.SECRET_KEY_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.server-addr:${nacos.server-addr:}}"
+ */
+ String SERVER_ADDR_PLACEHOLDER = "${" + DISCOVERY_PREFIX + SERVER_ADDR + ":"
+ + NacosProperties.SERVER_ADDR_PLACEHOLDER + "}";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.context-path:${nacos.context-path:}}"
- */
- String CONTEXT_PATH_PLACEHOLDER = "${" + DISCOVERY_PREFIX + CONTEXT_PATH + ":" + NacosProperties.CONTEXT_PATH_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.context-path:${nacos.context-path:}}"
+ */
+ String CONTEXT_PATH_PLACEHOLDER = "${" + DISCOVERY_PREFIX + CONTEXT_PATH + ":"
+ + NacosProperties.CONTEXT_PATH_PLACEHOLDER + "}";
- /**
- * The placeholder of endpoint, the value is
- * "${nacos.discovery.cluster-name:${nacos.cluster-name:}}"
- */
- String CLUSTER_NAME_PLACEHOLDER = "${" + DISCOVERY_PREFIX + CLUSTER_NAME + ":" + NacosProperties.CLUSTER_NAME_PLACEHOLDER + "}";
+ /**
+ * The placeholder of endpoint, the value is
+ * "${nacos.discovery.cluster-name:${nacos.cluster-name:}}"
+ */
+ String CLUSTER_NAME_PLACEHOLDER = "${" + DISCOVERY_PREFIX + CLUSTER_NAME + ":"
+ + NacosProperties.CLUSTER_NAME_PLACEHOLDER + "}";
- /**
- * The placeholder of {@link NacosProperties#ENCODE encode}, the value is
- * "${nacos.discovery.encode:${nacos.encode:UTF-8}}"
- */
- String ENCODE_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ENCODE + ":" + NacosProperties.ENCODE_PLACEHOLDER + "}";
+ /**
+ * The placeholder of {@link NacosProperties#ENCODE encode}, the value is
+ * "${nacos.discovery.encode:${nacos.encode:UTF-8}}"
+ */
+ String ENCODE_PLACEHOLDER = "${" + DISCOVERY_PREFIX + ENCODE + ":"
+ + NacosProperties.ENCODE_PLACEHOLDER + "}";
- /**
- * Global {@link NacosProperties Nacos Properties}
- *
- * @return required
- * @see NacosInjected#properties()
- */
- NacosProperties globalProperties() default
- @NacosProperties(
- endpoint = ENDPOINT_PLACEHOLDER,
- namespace = NAMESPACE_PLACEHOLDER,
- accessKey = ACCESS_KEY_PLACEHOLDER,
- secretKey = SECRET_KEY_PLACEHOLDER,
- serverAddr = SERVER_ADDR_PLACEHOLDER,
- contextPath = CONTEXT_PATH_PLACEHOLDER,
- clusterName = CLUSTER_NAME_PLACEHOLDER,
- encode = ENCODE_PLACEHOLDER
- );
+ /**
+ * Global {@link NacosProperties Nacos Properties}
+ *
+ * @return required
+ * @see NacosInjected#properties()
+ */
+ NacosProperties globalProperties() default @NacosProperties(endpoint = ENDPOINT_PLACEHOLDER, namespace = NAMESPACE_PLACEHOLDER, accessKey = ACCESS_KEY_PLACEHOLDER, secretKey = SECRET_KEY_PLACEHOLDER, serverAddr = SERVER_ADDR_PLACEHOLDER, contextPath = CONTEXT_PATH_PLACEHOLDER, clusterName = CLUSTER_NAME_PLACEHOLDER, encode = ENCODE_PLACEHOLDER);
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/NacosDiscoveryBeanDefinitionRegistrar.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/NacosDiscoveryBeanDefinitionRegistrar.java
index 11d93338..a93cd8a8 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/NacosDiscoveryBeanDefinitionRegistrar.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/discovery/NacosDiscoveryBeanDefinitionRegistrar.java
@@ -18,6 +18,7 @@
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import com.alibaba.nacos.spring.util.NacosBeanUtils;
+
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
@@ -26,36 +27,46 @@
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.type.AnnotationMetadata;
-import static com.alibaba.nacos.spring.util.NacosBeanUtils.*;
+import static com.alibaba.nacos.spring.util.NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
+import static com.alibaba.nacos.spring.util.NacosBeanUtils.MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
+import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerGlobalNacosProperties;
+import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerNacosCommonBeans;
+import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerNacosDiscoveryBeans;
/**
* Nacos Discovery {@link ImportBeanDefinitionRegistrar BeanDefinition Registrar}
*
* @author Mercy
* @see EnableNacosConfig
- * @see NacosBeanUtils#registerGlobalNacosProperties(AnnotationAttributes, BeanDefinitionRegistry, PropertyResolver, String)
+ * @see NacosBeanUtils#registerGlobalNacosProperties(AnnotationAttributes,
+ * BeanDefinitionRegistry, PropertyResolver, String)
* @see NacosBeanUtils#registerNacosCommonBeans(BeanDefinitionRegistry)
- * @see NacosBeanUtils#registerNacosConfigBeans(BeanDefinitionRegistry, Environment)
* @since 0.1.0
*/
-public class NacosDiscoveryBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
+public class NacosDiscoveryBeanDefinitionRegistrar
+ implements ImportBeanDefinitionRegistrar, EnvironmentAware {
- private Environment environment;
+ private Environment environment;
- @Override
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- AnnotationAttributes attributes = AnnotationAttributes.fromMap(
- importingClassMetadata.getAnnotationAttributes(EnableNacosDiscovery.class.getName()));
- // Register Global Nacos Properties Bean
- registerGlobalNacosProperties(attributes, registry, environment, DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
- // Register Nacos Common Beans
- registerNacosCommonBeans(registry);
- // Register Nacos Discovery Beans
- registerNacosDiscoveryBeans(registry);
- }
+ @Override
+ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
+ BeanDefinitionRegistry registry) {
+ AnnotationAttributes attributes = AnnotationAttributes
+ .fromMap(importingClassMetadata
+ .getAnnotationAttributes(EnableNacosDiscovery.class.getName()));
+ // Register Global Nacos Properties Bean
+ registerGlobalNacosProperties(attributes, registry, environment,
+ DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
+ registerGlobalNacosProperties(attributes, registry, environment,
+ MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
+ // Register Nacos Common Beans
+ registerNacosCommonBeans(registry);
+ // Register Nacos Discovery Beans
+ registerNacosDiscoveryBeans(registry);
+ }
- @Override
- public void setEnvironment(Environment environment) {
- this.environment = environment;
- }
+ @Override
+ public void setEnvironment(Environment environment) {
+ this.environment = environment;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java
index 563842e3..e8935c66 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParser.java
@@ -16,24 +16,32 @@
*/
package com.alibaba.nacos.spring.context.config.xml;
+import java.util.Properties;
+
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.util.NacosBeanUtils;
+import org.w3c.dom.Element;
+
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.env.Environment;
-import org.w3c.dom.Element;
-
-import java.util.Properties;
-import static com.alibaba.nacos.api.annotation.NacosProperties.*;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ACCESS_KEY;
+import static com.alibaba.nacos.api.annotation.NacosProperties.CLUSTER_NAME;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ENCODE;
+import static com.alibaba.nacos.api.annotation.NacosProperties.ENDPOINT;
+import static com.alibaba.nacos.api.annotation.NacosProperties.NAMESPACE;
+import static com.alibaba.nacos.api.annotation.NacosProperties.SECRET_KEY;
+import static com.alibaba.nacos.api.annotation.NacosProperties.SERVER_ADDR;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerGlobalNacosProperties;
/**
- * Nacos Global {@link Properties} {@link BeanDefinitionParser} for <nacos:global-properties ...>
+ * Nacos Global {@link Properties} {@link BeanDefinitionParser} for
+ * <nacos:global-properties ...>
*
* @author Mercy
* @see NacosBeanUtils#GLOBAL_NACOS_PROPERTIES_BEAN_NAME
@@ -43,27 +51,34 @@
*/
public class GlobalNacosPropertiesBeanDefinitionParser implements BeanDefinitionParser {
- @Override
- public BeanDefinition parse(Element element, ParserContext parserContext) {
+ @Override
+ public BeanDefinition parse(Element element, ParserContext parserContext) {
- Properties properties = new Properties();
+ Properties properties = new Properties();
- Environment environment = parserContext.getDelegate().getReaderContext().getReader().getEnvironment();
+ Environment environment = parserContext.getDelegate().getReaderContext()
+ .getReader().getEnvironment();
- properties.setProperty(PropertyKeyConst.ENDPOINT, element.getAttribute(ENDPOINT));
- properties.setProperty(PropertyKeyConst.NAMESPACE, element.getAttribute(NAMESPACE));
- properties.setProperty(PropertyKeyConst.ACCESS_KEY, element.getAttribute(ACCESS_KEY));
- properties.setProperty(PropertyKeyConst.SECRET_KEY, element.getAttribute(SECRET_KEY));
- properties.setProperty(PropertyKeyConst.SERVER_ADDR, element.getAttribute(SERVER_ADDR));
- properties.setProperty(PropertyKeyConst.CLUSTER_NAME, element.getAttribute(CLUSTER_NAME));
- properties.setProperty(PropertyKeyConst.ENCODE, element.getAttribute(ENCODE));
+ properties.setProperty(PropertyKeyConst.ENDPOINT, element.getAttribute(ENDPOINT));
+ properties.setProperty(PropertyKeyConst.NAMESPACE,
+ element.getAttribute(NAMESPACE));
+ properties.setProperty(PropertyKeyConst.ACCESS_KEY,
+ element.getAttribute(ACCESS_KEY));
+ properties.setProperty(PropertyKeyConst.SECRET_KEY,
+ element.getAttribute(SECRET_KEY));
+ properties.setProperty(PropertyKeyConst.SERVER_ADDR,
+ element.getAttribute(SERVER_ADDR));
+ properties.setProperty(PropertyKeyConst.CLUSTER_NAME,
+ element.getAttribute(CLUSTER_NAME));
+ properties.setProperty(PropertyKeyConst.ENCODE, element.getAttribute(ENCODE));
- BeanDefinitionRegistry registry = parserContext.getRegistry();
+ BeanDefinitionRegistry registry = parserContext.getRegistry();
- // Register Global Nacos Properties as Spring singleton bean
- registerGlobalNacosProperties(properties, registry, environment, GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
+ // Register Global Nacos Properties as Spring singleton bean
+ registerGlobalNacosProperties(properties, registry, environment,
+ GLOBAL_NACOS_PROPERTIES_BEAN_NAME);
- return null;
- }
+ return null;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParser.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParser.java
index db0a935c..66be7be1 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParser.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParser.java
@@ -17,15 +17,17 @@
package com.alibaba.nacos.spring.context.config.xml;
import com.alibaba.nacos.spring.context.annotation.NacosBeanDefinitionRegistrar;
+import org.w3c.dom.Element;
+
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.env.Environment;
-import org.w3c.dom.Element;
/**
- * Nacos Annotation Driven {@link BeanDefinitionParser} for XML element <nacos:annotation-driven/>
+ * Nacos Annotation Driven {@link BeanDefinitionParser} for XML element
+ * <nacos:annotation-driven/>
*
* @author Mercy
* @see BeanDefinitionParser
@@ -33,16 +35,17 @@
*/
public class NacosAnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
- @Override
- public BeanDefinition parse(Element element, ParserContext parserContext) {
- // Get Environment
- Environment environment = parserContext.getDelegate().getReaderContext().getReader().getEnvironment();
- // Get BeanDefinitionRegistry
- BeanDefinitionRegistry registry = parserContext.getRegistry();
- // Register Nacos Annotation Beans
- NacosBeanDefinitionRegistrar registrar = new NacosBeanDefinitionRegistrar();
- registrar.setEnvironment(environment);
- registrar.registerNacosAnnotationBeans(registry);
- return null;
- }
+ @Override
+ public BeanDefinition parse(Element element, ParserContext parserContext) {
+ // Get Environment
+ Environment environment = parserContext.getDelegate().getReaderContext()
+ .getReader().getEnvironment();
+ // Get BeanDefinitionRegistry
+ BeanDefinitionRegistry registry = parserContext.getRegistry();
+ // Register Nacos Annotation Beans
+ NacosBeanDefinitionRegistrar registrar = new NacosBeanDefinitionRegistrar();
+ registrar.setEnvironment(environment);
+ registrar.registerNacosAnnotationBeans(registry);
+ return null;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosNamespaceHandler.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosNamespaceHandler.java
index c806b50c..14691f57 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosNamespaceHandler.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosNamespaceHandler.java
@@ -28,10 +28,13 @@
*/
public class NacosNamespaceHandler extends NamespaceHandlerSupport {
- @Override
- public void init() {
- registerBeanDefinitionParser("annotation-driven", new NacosAnnotationDrivenBeanDefinitionParser());
- registerBeanDefinitionParser("global-properties", new GlobalNacosPropertiesBeanDefinitionParser());
- registerBeanDefinitionParser("property-source", new NacosPropertySourceBeanDefinitionParser());
- }
+ @Override
+ public void init() {
+ registerBeanDefinitionParser("annotation-driven",
+ new NacosAnnotationDrivenBeanDefinitionParser());
+ registerBeanDefinitionParser("global-properties",
+ new GlobalNacosPropertiesBeanDefinitionParser());
+ registerBeanDefinitionParser("property-source",
+ new NacosPropertySourceBeanDefinitionParser());
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParser.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParser.java
index fd4d1a10..62c9f7c7 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParser.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParser.java
@@ -19,46 +19,50 @@
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
-import org.w3c.dom.Element;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerNacosPropertySourcePostProcessor;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.registerXmlNacosPropertySourceBuilder;
/**
- * Nacos Property Source {@link BeanDefinitionParser} for <nacos:property-source ...>
+ * Nacos Property Source {@link BeanDefinitionParser} for <nacos:property-source
+ * ...>
*
* @author hxy1991
* @author Mercy
* @see NacosPropertySource
* @since 0.1.0
*/
-public class NacosPropertySourceBeanDefinitionParser extends AbstractBeanDefinitionParser {
+public class NacosPropertySourceBeanDefinitionParser
+ extends AbstractBeanDefinitionParser {
- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());
- @Override
- protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
+ @Override
+ protected AbstractBeanDefinition parseInternal(Element element,
+ ParserContext parserContext) {
- BeanDefinitionRegistry registry = parserContext.getRegistry();
- // Register Dependent Beans
- registerNacosPropertySourcePostProcessor(registry);
- registerXmlNacosPropertySourceBuilder(registry);
+ BeanDefinitionRegistry registry = parserContext.getRegistry();
+ // Register Dependent Beans
+ registerNacosPropertySourcePostProcessor(registry);
+ registerXmlNacosPropertySourceBuilder(registry);
- NacosPropertySourceXmlBeanDefinition beanDefinition = new NacosPropertySourceXmlBeanDefinition();
- beanDefinition.setElement(element);
- beanDefinition.setXmlReaderContext(parserContext.getReaderContext());
+ NacosPropertySourceXmlBeanDefinition beanDefinition = new NacosPropertySourceXmlBeanDefinition();
+ beanDefinition.setElement(element);
+ beanDefinition.setXmlReaderContext(parserContext.getReaderContext());
- return beanDefinition;
- }
+ return beanDefinition;
+ }
- @Override
- protected boolean shouldGenerateId() {
- return true;
- }
+ @Override
+ protected boolean shouldGenerateId() {
+ return true;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceXmlBeanDefinition.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceXmlBeanDefinition.java
index 7b37fed3..bcc9c4ae 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceXmlBeanDefinition.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceXmlBeanDefinition.java
@@ -16,11 +16,12 @@
*/
package com.alibaba.nacos.spring.context.config.xml;
+import org.w3c.dom.Element;
+
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.xml.XmlReaderContext;
import org.springframework.context.annotation.PropertySource;
-import org.w3c.dom.Element;
/**
* Nacos {@link PropertySource} XML {@link BeanDefinition}
@@ -30,29 +31,29 @@
*/
public class NacosPropertySourceXmlBeanDefinition extends GenericBeanDefinition {
- private Element element;
+ private Element element;
- private XmlReaderContext xmlReaderContext;
+ private XmlReaderContext xmlReaderContext;
- public NacosPropertySourceXmlBeanDefinition() {
- // Self type as Bean Class
- setBeanClass(getClass());
- }
+ public NacosPropertySourceXmlBeanDefinition() {
+ // Self type as Bean Class
+ setBeanClass(getClass());
+ }
- void setXmlReaderContext(XmlReaderContext xmlReaderContext) {
- this.xmlReaderContext = xmlReaderContext;
- }
+ void setXmlReaderContext(XmlReaderContext xmlReaderContext) {
+ this.xmlReaderContext = xmlReaderContext;
+ }
- void setElement(Element element) {
- this.element = element;
- }
+ void setElement(Element element) {
+ this.element = element;
+ }
- public Element getElement() {
- return element;
- }
+ public Element getElement() {
+ return element;
+ }
- public XmlReaderContext getXmlReaderContext() {
- return xmlReaderContext;
- }
+ public XmlReaderContext getXmlReaderContext() {
+ return xmlReaderContext;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/constants/NacosConstants.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/constants/NacosConstants.java
index 08e50831..550592ce 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/constants/NacosConstants.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/constants/NacosConstants.java
@@ -26,14 +26,16 @@
*/
public interface NacosConstants {
- /**
- * The parallelism of Nacos Config Listener
- */
- String NACOS_CONFIG_LISTENER_PARALLELISM = NacosProperties.PREFIX + "config.listener.parallelism";
+ /**
+ * The parallelism of Nacos Config Listener
+ */
+ String NACOS_CONFIG_LISTENER_PARALLELISM = NacosProperties.PREFIX
+ + "config.listener.parallelism";
- /**
- * The default parallelism of Nacos Config Listener (available processors)
- */
- int DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM = Runtime.getRuntime().availableProcessors();
+ /**
+ * The default parallelism of Nacos Config Listener (available processors)
+ */
+ int DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM = Runtime.getRuntime()
+ .availableProcessors();
}
\ No newline at end of file
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/AnnotationListenerMethodProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/AnnotationListenerMethodProcessor.java
index 3f30b5ad..11ee4026 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/AnnotationListenerMethodProcessor.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/AnnotationListenerMethodProcessor.java
@@ -16,8 +16,13 @@
*/
package com.alibaba.nacos.spring.context.event;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.Map;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
@@ -25,13 +30,11 @@
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.Map;
-
import static com.alibaba.nacos.spring.util.NacosUtils.resolveGenericType;
-import static java.lang.reflect.Modifier.*;
-
+import static java.lang.reflect.Modifier.isAbstract;
+import static java.lang.reflect.Modifier.isNative;
+import static java.lang.reflect.Modifier.isPublic;
+import static java.lang.reflect.Modifier.isStatic;
/**
* Listener {@link Method method} Processor
@@ -49,125 +52,130 @@
* @see Method
* @since 0.1.0
*/
-public abstract class AnnotationListenerMethodProcessor implements ApplicationListener {
-
- protected final Log logger = LogFactory.getLog(getClass());
- private final Class annotationType;
-
- public AnnotationListenerMethodProcessor() {
- this.annotationType = resolveGenericType(getClass());
- }
-
- /**
- * Must be
- *
- * public
- * - not
static
- * - not
abstract
- * - not
native
- * void
- *
- *
- * @param method {@link Method}
- * @return if obey above rules , return true
- */
- static boolean isListenerMethod(Method method) {
-
- int modifiers = method.getModifiers();
-
- Class> returnType = method.getReturnType();
-
- return isPublic(modifiers)
- && !isStatic(modifiers)
- && !isNative(modifiers)
- && !isAbstract(modifiers)
- && void.class.equals(returnType)
- ;
- }
-
- @Override
- public final void onApplicationEvent(ContextRefreshedEvent event) {
- // Retrieve ApplicationContext from ContextRefreshedEvent
- ApplicationContext applicationContext = event.getApplicationContext();
- // Select those methods from all beans that annotated
- processBeans(applicationContext);
- }
-
- private void processBeans(ApplicationContext applicationContext) {
-
- Map beansMap = applicationContext.getBeansOfType(Object.class);
-
- processBeans(beansMap, applicationContext);
-
- }
-
- private void processBeans(Map beansMap, ApplicationContext applicationContext) {
-
- for (Map.Entry entry : beansMap.entrySet()) {
- String beanName = entry.getKey();
- Object bean = entry.getValue();
- // Bean type
- if (bean != null) {
- Class> beanClass = AopUtils.getTargetClass(bean);
- processBean(beanName, bean, beanClass, applicationContext);
- }
- }
-
- }
-
- /**
- * Select those methods from bean that annotated
- *
- * @param beanName Bean name
- * @param bean Bean object
- * @param beanClass the {@link Class} of Bean
- * @param applicationContext
- */
- private void processBean(final String beanName, final Object bean, final Class> beanClass, final ApplicationContext applicationContext) {
-
- ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
- @Override
- public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
- A annotation = AnnotationUtils.getAnnotation(method, annotationType);
- if (annotation != null && isCandidateMethod(bean, beanClass, annotation, method, applicationContext)) {
- processListenerMethod(beanName, bean, beanClass, annotation, method, applicationContext);
- }
- }
-
- }, new ReflectionUtils.MethodFilter() {
- @Override
- public boolean matches(Method method) {
- return isListenerMethod(method);
- }
- });
-
- }
-
- /**
- * Process Listener Method when {@link #isCandidateMethod(Object, Class, Annotation, Method, ApplicationContext)} returns true
- *
- * @param beanName Bean name
- * @param bean Bean object
- * @param beanClass Bean Class
- * @param annotation Annotation object
- * @param method Method
- * @param applicationContext ApplicationContext
- */
- protected abstract void processListenerMethod(String beanName, Object bean, Class> beanClass, A annotation, Method method,
- ApplicationContext applicationContext);
-
- /**
- * Subclass could override this method to determine current method is candidate or not
- *
- * @param bean Bean object
- * @param beanClass Bean Class
- * @param annotation Annotation object
- * @param method Method
- * @param applicationContext ApplicationContext
- * @return true
as default
- */
- protected boolean isCandidateMethod(Object bean, Class> beanClass, A annotation, Method method,
- ApplicationContext applicationContext) {
- return true;
- }
+public abstract class AnnotationListenerMethodProcessor
+ implements ApplicationListener {
+
+ protected final Log logger = LogFactory.getLog(getClass());
+ private final Class annotationType;
+
+ public AnnotationListenerMethodProcessor() {
+ this.annotationType = resolveGenericType(getClass());
+ }
+
+ /**
+ * Must be
+ *
+ * public
+ * - not
static
+ * - not
abstract
+ * - not
native
+ * void
+ *
+ *
+ * @param method {@link Method}
+ * @return if obey above rules , return true
+ */
+ static boolean isListenerMethod(Method method) {
+
+ int modifiers = method.getModifiers();
+
+ Class> returnType = method.getReturnType();
+
+ return isPublic(modifiers) && !isStatic(modifiers) && !isNative(modifiers)
+ && !isAbstract(modifiers) && void.class.equals(returnType);
+ }
+
+ @Override
+ public final void onApplicationEvent(ContextRefreshedEvent event) {
+ // Retrieve ApplicationContext from ContextRefreshedEvent
+ ApplicationContext applicationContext = event.getApplicationContext();
+ // Select those methods from all beans that annotated
+ processBeans(applicationContext);
+ }
+
+ private void processBeans(ApplicationContext applicationContext) {
+
+ Map beansMap = applicationContext.getBeansOfType(Object.class);
+
+ processBeans(beansMap, applicationContext);
+
+ }
+
+ private void processBeans(Map beansMap,
+ ApplicationContext applicationContext) {
+
+ for (Map.Entry entry : beansMap.entrySet()) {
+ String beanName = entry.getKey();
+ Object bean = entry.getValue();
+ // Bean type
+ if (bean != null) {
+ Class> beanClass = AopUtils.getTargetClass(bean);
+ processBean(beanName, bean, beanClass, applicationContext);
+ }
+ }
+
+ }
+
+ /**
+ * Select those methods from bean that annotated
+ *
+ * @param beanName Bean name
+ * @param bean Bean object
+ * @param beanClass the {@link Class} of Bean
+ * @param applicationContext
+ */
+ private void processBean(final String beanName, final Object bean,
+ final Class> beanClass, final ApplicationContext applicationContext) {
+
+ ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
+ @Override
+ public void doWith(Method method)
+ throws IllegalArgumentException, IllegalAccessException {
+ A annotation = AnnotationUtils.getAnnotation(method, annotationType);
+ if (annotation != null && isCandidateMethod(bean, beanClass, annotation,
+ method, applicationContext)) {
+ processListenerMethod(beanName, bean, beanClass, annotation, method,
+ applicationContext);
+ }
+ }
+
+ }, new ReflectionUtils.MethodFilter() {
+ @Override
+ public boolean matches(Method method) {
+ return isListenerMethod(method);
+ }
+ });
+
+ }
+
+ /**
+ * Process Listener Method when
+ * {@link #isCandidateMethod(Object, Class, Annotation, Method, ApplicationContext)}
+ * returns true
+ *
+ * @param beanName Bean name
+ * @param bean Bean object
+ * @param beanClass Bean Class
+ * @param annotation Annotation object
+ * @param method Method
+ * @param applicationContext ApplicationContext
+ */
+ protected abstract void processListenerMethod(String beanName, Object bean,
+ Class> beanClass, A annotation, Method method,
+ ApplicationContext applicationContext);
+
+ /**
+ * Subclass could override this method to determine current method is candidate or not
+ *
+ * @param bean Bean object
+ * @param beanClass Bean Class
+ * @param annotation Annotation object
+ * @param method Method
+ * @param applicationContext ApplicationContext
+ * @return true
as default
+ */
+ protected boolean isCandidateMethod(Object bean, Class> beanClass, A annotation,
+ Method method, ApplicationContext applicationContext) {
+ return true;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/DeferredApplicationEventPublisher.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/DeferredApplicationEventPublisher.java
index 3d83a2f1..5da61308 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/DeferredApplicationEventPublisher.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/DeferredApplicationEventPublisher.java
@@ -16,70 +16,77 @@
*/
package com.alibaba.nacos.spring.context.event;
-import org.springframework.context.*;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.context.support.AbstractApplicationContext;
-
import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationEvent;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.context.support.AbstractApplicationContext;
+
/**
- * Deferred {@link ApplicationEventPublisher} to resolve {@link #publishEvent(ApplicationEvent)} too early to publish
- * {@link ApplicationEvent} when {@link AbstractApplicationContext#initApplicationEventMulticaster()
- * Spring ApplicationContexts' ApplicationEventMulticaster} is not ready, thus current class will hold
- * all early {@link ApplicationEvent events} temporary until {@link ConfigurableApplicationContext#isRunning() Spring
- * ApplicationContext is active}, and then those {@link ApplicationEvent events} will be replayed.
+ * Deferred {@link ApplicationEventPublisher} to resolve
+ * {@link #publishEvent(ApplicationEvent)} too early to publish {@link ApplicationEvent}
+ * when {@link AbstractApplicationContext#initApplicationEventMulticaster() Spring
+ * ApplicationContexts' ApplicationEventMulticaster} is not ready, thus current class will
+ * hold all early {@link ApplicationEvent events} temporary until
+ * {@link ConfigurableApplicationContext#isRunning() Spring ApplicationContext is active},
+ * and then those {@link ApplicationEvent events} will be replayed.
*
* @author Mercy
* @since 0.1.0
*/
-public class DeferredApplicationEventPublisher implements ApplicationEventPublisher, ApplicationListener {
+public class DeferredApplicationEventPublisher
+ implements ApplicationEventPublisher, ApplicationListener {
- private final ConfigurableApplicationContext context;
+ private final ConfigurableApplicationContext context;
- // fix issue #85
- private final ConcurrentLinkedQueue deferredEvents = new ConcurrentLinkedQueue();
+ // fix issue #85
+ private final ConcurrentLinkedQueue deferredEvents = new ConcurrentLinkedQueue();
- public DeferredApplicationEventPublisher(ConfigurableApplicationContext context) {
- this.context = context;
- this.context.addApplicationListener(this);
- }
+ public DeferredApplicationEventPublisher(ConfigurableApplicationContext context) {
+ this.context = context;
+ this.context.addApplicationListener(this);
+ }
- @Override
- public void publishEvent(ApplicationEvent event) {
+ @Override
+ public void publishEvent(ApplicationEvent event) {
- try {
- if (context.isRunning()) {
- context.publishEvent(event);
- } else {
- deferredEvents.add(event);
- }
- } catch (Exception ignore) {
- deferredEvents.add(event);
- }
- }
+ try {
+ if (context.isRunning()) {
+ context.publishEvent(event);
+ }
+ else {
+ deferredEvents.add(event);
+ }
+ }
+ catch (Exception ignore) {
+ deferredEvents.add(event);
+ }
+ }
- @Override
- public void onApplicationEvent(ContextRefreshedEvent event) {
+ @Override
+ public void onApplicationEvent(ContextRefreshedEvent event) {
- ApplicationContext currentContext = event.getApplicationContext();
+ ApplicationContext currentContext = event.getApplicationContext();
- if (!currentContext.equals(context)) {
- // prevent multiple event multi-casts in hierarchical contexts
- return;
- }
+ if (!currentContext.equals(context)) {
+ // prevent multiple event multi-casts in hierarchical contexts
+ return;
+ }
- replayDeferredEvents();
- }
+ replayDeferredEvents();
+ }
- private void replayDeferredEvents() {
- Iterator iterator = deferredEvents.iterator();
- while (iterator.hasNext()) {
- ApplicationEvent event = iterator.next();
- publishEvent(event);
- iterator.remove(); // remove if published
- }
- }
+ private void replayDeferredEvents() {
+ Iterator iterator = deferredEvents.iterator();
+ while (iterator.hasNext()) {
+ ApplicationEvent event = iterator.next();
+ publishEvent(event);
+ iterator.remove(); // remove if published
+ }
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/LoggingNacosConfigMetadataEventListener.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/LoggingNacosConfigMetadataEventListener.java
index b02b548e..01cce6ee 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/LoggingNacosConfigMetadataEventListener.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/LoggingNacosConfigMetadataEventListener.java
@@ -19,6 +19,7 @@
import com.alibaba.nacos.spring.context.event.config.NacosConfigMetadataEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.context.ApplicationListener;
/**
@@ -27,44 +28,30 @@
* @author Mercy
* @since 0.1.0
*/
-public class LoggingNacosConfigMetadataEventListener implements ApplicationListener {
+public class LoggingNacosConfigMetadataEventListener
+ implements ApplicationListener {
- /**
- * The bean name of {@link LoggingNacosConfigMetadataEventListener}
- */
- public static final String BEAN_NAME = "loggingNacosConfigMetadataEventListener";
+ /**
+ * The bean name of {@link LoggingNacosConfigMetadataEventListener}
+ */
+ public static final String BEAN_NAME = "loggingNacosConfigMetadataEventListener";
- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());
- private final static String LOGGING_MESSAGE = "Nacos Config Metadata : " +
- "dataId='{}'" +
- ", groupId='{}'" +
- ", beanName='{}'" +
- ", bean='{}'" +
- ", beanType='{}'" +
- ", annotatedElement='{}'" +
- ", xmlResource='{}'" +
- ", nacosProperties='{}'" +
- ", nacosPropertiesAttributes='{}'" +
- ", source='{}'" +
- ", timestamp='{}'";
+ private final static String LOGGING_MESSAGE = "Nacos Config Metadata : "
+ + "dataId='{}'" + ", groupId='{}'" + ", beanName='{}'" + ", bean='{}'"
+ + ", beanType='{}'" + ", annotatedElement='{}'" + ", xmlResource='{}'"
+ + ", nacosProperties='{}'" + ", nacosPropertiesAttributes='{}'"
+ + ", source='{}'" + ", timestamp='{}'";
- @Override
- public void onApplicationEvent(NacosConfigMetadataEvent event) {
- if (logger.isInfoEnabled()) {
- logger.info(LOGGING_MESSAGE,
- event.getDataId(),
- event.getGroupId(),
- event.getBeanName(),
- event.getBean(),
- event.getBeanType(),
- event.getAnnotatedElement(),
- event.getXmlResource(),
- event.getNacosProperties(),
- event.getNacosPropertiesAttributes(),
- event.getSource(),
- event.getTimestamp()
- );
- }
- }
+ @Override
+ public void onApplicationEvent(NacosConfigMetadataEvent event) {
+ if (logger.isInfoEnabled()) {
+ logger.info(LOGGING_MESSAGE, event.getDataId(), event.getGroupId(),
+ event.getBeanName(), event.getBean(), event.getBeanType(),
+ event.getAnnotatedElement(), event.getXmlResource(),
+ event.getNacosProperties(), event.getNacosPropertiesAttributes(),
+ event.getSource(), event.getTimestamp());
+ }
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/DelegatingEventPublishingListener.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/DelegatingEventPublishingListener.java
index 18423a01..935429e1 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/DelegatingEventPublishingListener.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/DelegatingEventPublishingListener.java
@@ -16,17 +16,19 @@
*/
package com.alibaba.nacos.spring.context.event.config;
+import java.util.concurrent.Executor;
+
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.listener.Listener;
-import org.springframework.context.ApplicationEventPublisher;
-import java.util.concurrent.Executor;
+import org.springframework.context.ApplicationEventPublisher;
/**
- * A Delegating {@link NacosConfigReceivedEvent Event} Publishing {@link Listener} of Nacos Config {@link Listener} with
- * dataId, groupId and {@link ConfigService} instance. A {@link NacosConfigReceivedEvent Nacos config received event}
- * will be published when a new Nacos config received.
+ * A Delegating {@link NacosConfigReceivedEvent Event} Publishing {@link Listener} of
+ * Nacos Config {@link Listener} with dataId, groupId and {@link ConfigService} instance.
+ * A {@link NacosConfigReceivedEvent Nacos config received event} will be published when a
+ * new Nacos config received.
*
* @author Mercy
* @see NacosConfigReceivedEvent
@@ -36,64 +38,67 @@
*/
public final class DelegatingEventPublishingListener implements Listener {
- private final ConfigService configService;
-
- private final String dataId;
-
- private final String groupId;
-
- private final ApplicationEventPublisher applicationEventPublisher;
-
- private final String configType;
-
- private final Executor executor;
-
- private final Listener delegate;
-
- DelegatingEventPublishingListener(ConfigService configService, String dataId, String groupId,
- ApplicationEventPublisher applicationEventPublisher,
- Executor executor, Listener delegate) {
- this(configService, dataId, groupId, ConfigType.PROPERTIES.getType(), applicationEventPublisher, executor, delegate);
- }
-
- DelegatingEventPublishingListener(ConfigService configService, String dataId, String groupId, String configType,
- ApplicationEventPublisher applicationEventPublisher,
- Executor executor, Listener delegate) {
- this.configService = configService;
- this.dataId = dataId;
- this.groupId = groupId;
- this.configType = configType;
- this.applicationEventPublisher = applicationEventPublisher;
- this.executor = executor;
- this.delegate = delegate;
- }
-
- @Override
- public Executor getExecutor() {
- Executor executor = delegate.getExecutor();
- if (executor == null) {
- executor = this.executor;
- }
- return executor;
- }
-
- /**
- * Callback method on Nacos config received
- *
- * @param content Nacos config
- */
- @Override
- public void receiveConfigInfo(String content) {
- onReceived(content);
- publishEvent(content);
- }
-
- private void publishEvent(String content) {
- NacosConfigReceivedEvent event = new NacosConfigReceivedEvent(configService, dataId, groupId, content, configType);
- applicationEventPublisher.publishEvent(event);
- }
-
- private void onReceived(String content) {
- delegate.receiveConfigInfo(content);
- }
+ private final ConfigService configService;
+
+ private final String dataId;
+
+ private final String groupId;
+
+ private final ApplicationEventPublisher applicationEventPublisher;
+
+ private final String configType;
+
+ private final Executor executor;
+
+ private final Listener delegate;
+
+ DelegatingEventPublishingListener(ConfigService configService, String dataId,
+ String groupId, ApplicationEventPublisher applicationEventPublisher,
+ Executor executor, Listener delegate) {
+ this(configService, dataId, groupId, ConfigType.PROPERTIES.getType(),
+ applicationEventPublisher, executor, delegate);
+ }
+
+ DelegatingEventPublishingListener(ConfigService configService, String dataId,
+ String groupId, String configType,
+ ApplicationEventPublisher applicationEventPublisher, Executor executor,
+ Listener delegate) {
+ this.configService = configService;
+ this.dataId = dataId;
+ this.groupId = groupId;
+ this.configType = configType;
+ this.applicationEventPublisher = applicationEventPublisher;
+ this.executor = executor;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Executor getExecutor() {
+ Executor executor = delegate.getExecutor();
+ if (executor == null) {
+ executor = this.executor;
+ }
+ return executor;
+ }
+
+ /**
+ * Callback method on Nacos config received
+ *
+ * @param content Nacos config
+ */
+ @Override
+ public void receiveConfigInfo(String content) {
+ onReceived(content);
+ publishEvent(content);
+ }
+
+ private void publishEvent(String content) {
+ NacosConfigReceivedEvent event = new NacosConfigReceivedEvent(configService,
+ dataId, groupId, content, configType);
+ applicationEventPublisher.publishEvent(event);
+ }
+
+ private void onReceived(String content) {
+ delegate.receiveConfigInfo(content);
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigService.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigService.java
index 5f6bab1e..588c9650 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigService.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigService.java
@@ -16,18 +16,18 @@
*/
package com.alibaba.nacos.spring.context.event.config;
+import java.util.Properties;
+import java.util.concurrent.Executor;
+
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.spring.context.event.DeferredApplicationEventPublisher;
import com.alibaba.nacos.spring.metadata.NacosServiceMetaData;
+
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ConfigurableApplicationContext;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Executor;
-
/**
* {@link NacosConfigEvent Event} publishing {@link ConfigService}
*
@@ -36,91 +36,106 @@
*/
public class EventPublishingConfigService implements ConfigService, NacosServiceMetaData {
- private final ConfigService configService;
-
- private final ApplicationEventPublisher applicationEventPublisher;
-
- private final Executor executor;
-
- private final Properties properties;
-
- public EventPublishingConfigService(ConfigService configService, Properties properties, ConfigurableApplicationContext context,
- Executor executor) {
- this.configService = configService;
- this.properties = properties;
- this.applicationEventPublisher = new DeferredApplicationEventPublisher(context);
- this.executor = executor;
- }
-
- @Override
- public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
- try {
- return configService.getConfig(dataId, group, timeoutMs);
- } catch (NacosException e) {
- if (NacosException.SERVER_ERROR == e.getErrCode()) { // timeout error
- publishEvent(new NacosConfigTimeoutEvent(configService, dataId, group, timeoutMs, e.getErrMsg()));
- }
- throw e; // re-throw NacosException
- }
- }
-
- @Override
- public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException {
- Listener listenerAdapter = new DelegatingEventPublishingListener(configService, dataId, group, applicationEventPublisher, executor, listener);
- return configService.getConfigAndSignListener(dataId, group, timeoutMs, listenerAdapter);
- }
-
- /**
- * Implementation of the new version of support for multiple configuration file type resolution
- *
- * @param dataId dataId
- * @param group group
- * @param type config's type
- * @param listener listener
- * @throws NacosException
- */
- public void addListener(String dataId, String group, String type, Listener listener) throws NacosException {
- Listener listenerAdapter = new DelegatingEventPublishingListener(configService, dataId, group, type, applicationEventPublisher, executor, listener);
- addListener(dataId, group, listenerAdapter);
- }
-
- @Override
- public void addListener(String dataId, String group, Listener listener) throws NacosException {
- configService.addListener(dataId, group, listener);
- publishEvent(new NacosConfigListenerRegisteredEvent(configService, dataId, group, listener, true));
- }
-
- @Override
- public boolean publishConfig(String dataId, String group, String content) throws NacosException {
- boolean published = configService.publishConfig(dataId, group, content);
- publishEvent(new NacosConfigPublishedEvent(configService, dataId, group, content, published));
- return published;
- }
-
- @Override
- public boolean removeConfig(String dataId, String group) throws NacosException {
- boolean removed = configService.removeConfig(dataId, group);
- publishEvent(new NacosConfigRemovedEvent(configService, dataId, group, removed));
- return removed;
- }
-
- @Override
- public void removeListener(String dataId, String group, Listener listener) {
- configService.removeListener(dataId, group, listener);
- publishEvent(new NacosConfigListenerRegisteredEvent(configService, dataId, group, listener, false));
- }
-
- @Override
- public String getServerStatus() {
- return configService.getServerStatus();
- }
-
- private void publishEvent(NacosConfigEvent nacosConfigEvent) {
- applicationEventPublisher.publishEvent(nacosConfigEvent);
- }
-
- @Override
- public Properties getProperties() {
- return properties;
- }
+ private final ConfigService configService;
+
+ private final ApplicationEventPublisher applicationEventPublisher;
+
+ private final Executor executor;
+
+ private final Properties properties;
+
+ public EventPublishingConfigService(ConfigService configService,
+ Properties properties, ConfigurableApplicationContext context,
+ Executor executor) {
+ this.configService = configService;
+ this.properties = properties;
+ this.applicationEventPublisher = new DeferredApplicationEventPublisher(context);
+ this.executor = executor;
+ }
+
+ @Override
+ public String getConfig(String dataId, String group, long timeoutMs)
+ throws NacosException {
+ try {
+ return configService.getConfig(dataId, group, timeoutMs);
+ }
+ catch (NacosException e) {
+ if (NacosException.SERVER_ERROR == e.getErrCode()) { // timeout error
+ publishEvent(new NacosConfigTimeoutEvent(configService, dataId, group,
+ timeoutMs, e.getErrMsg()));
+ }
+ throw e; // re-throw NacosException
+ }
+ }
+
+ @Override
+ public String getConfigAndSignListener(String dataId, String group, long timeoutMs,
+ Listener listener) throws NacosException {
+ Listener listenerAdapter = new DelegatingEventPublishingListener(configService,
+ dataId, group, applicationEventPublisher, executor, listener);
+ return configService.getConfigAndSignListener(dataId, group, timeoutMs,
+ listenerAdapter);
+ }
+
+ /**
+ * Implementation of the new version of support for multiple configuration file type
+ * resolution
+ *
+ * @param dataId dataId
+ * @param group group
+ * @param type config's type
+ * @param listener listener
+ * @throws NacosException
+ */
+ public void addListener(String dataId, String group, String type, Listener listener)
+ throws NacosException {
+ Listener listenerAdapter = new DelegatingEventPublishingListener(configService,
+ dataId, group, type, applicationEventPublisher, executor, listener);
+ addListener(dataId, group, listenerAdapter);
+ }
+
+ @Override
+ public void addListener(String dataId, String group, Listener listener)
+ throws NacosException {
+ configService.addListener(dataId, group, listener);
+ publishEvent(new NacosConfigListenerRegisteredEvent(configService, dataId, group,
+ listener, true));
+ }
+
+ @Override
+ public boolean publishConfig(String dataId, String group, String content)
+ throws NacosException {
+ boolean published = configService.publishConfig(dataId, group, content);
+ publishEvent(new NacosConfigPublishedEvent(configService, dataId, group, content,
+ published));
+ return published;
+ }
+
+ @Override
+ public boolean removeConfig(String dataId, String group) throws NacosException {
+ boolean removed = configService.removeConfig(dataId, group);
+ publishEvent(new NacosConfigRemovedEvent(configService, dataId, group, removed));
+ return removed;
+ }
+
+ @Override
+ public void removeListener(String dataId, String group, Listener listener) {
+ configService.removeListener(dataId, group, listener);
+ publishEvent(new NacosConfigListenerRegisteredEvent(configService, dataId, group,
+ listener, false));
+ }
+
+ @Override
+ public String getServerStatus() {
+ return configService.getServerStatus();
+ }
+
+ private void publishEvent(NacosConfigEvent nacosConfigEvent) {
+ applicationEventPublisher.publishEvent(nacosConfigEvent);
+ }
+
+ @Override
+ public Properties getProperties() {
+ return properties;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigEvent.java
index 153e1139..1764d437 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigEvent.java
@@ -17,6 +17,7 @@
package com.alibaba.nacos.spring.context.event.config;
import com.alibaba.nacos.api.config.ConfigService;
+
import org.springframework.context.ApplicationEvent;
/**
@@ -27,40 +28,40 @@
*/
public abstract class NacosConfigEvent extends ApplicationEvent {
- private final String dataId;
+ private final String dataId;
- private final String groupId;
+ private final String groupId;
- /**
- * @param configService Nacos {@link ConfigService}
- * @param dataId data ID
- * @param groupId group ID
- */
- public NacosConfigEvent(ConfigService configService, String dataId, String groupId) {
- super(configService);
- this.dataId = dataId;
- this.groupId = groupId;
- }
+ /**
+ * @param configService Nacos {@link ConfigService}
+ * @param dataId data ID
+ * @param groupId group ID
+ */
+ public NacosConfigEvent(ConfigService configService, String dataId, String groupId) {
+ super(configService);
+ this.dataId = dataId;
+ this.groupId = groupId;
+ }
- @Override
- public final ConfigService getSource() {
- return (ConfigService) super.getSource();
- }
+ @Override
+ public final ConfigService getSource() {
+ return (ConfigService) super.getSource();
+ }
- /**
- * Get {@link ConfigService}
- *
- * @return {@link ConfigService}
- */
- public final ConfigService getConfigService() {
- return getSource();
- }
+ /**
+ * Get {@link ConfigService}
+ *
+ * @return {@link ConfigService}
+ */
+ public final ConfigService getConfigService() {
+ return getSource();
+ }
- public final String getDataId() {
- return dataId;
- }
+ public final String getDataId() {
+ return dataId;
+ }
- public final String getGroupId() {
- return groupId;
- }
+ public final String getGroupId() {
+ return groupId;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigListenerRegisteredEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigListenerRegisteredEvent.java
index 1eb24c6a..62e43582 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigListenerRegisteredEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigListenerRegisteredEvent.java
@@ -28,29 +28,29 @@
*/
public class NacosConfigListenerRegisteredEvent extends NacosConfigEvent {
- private final Listener listener;
+ private final Listener listener;
- private final boolean registered;
+ private final boolean registered;
- /**
- * @param configService Nacos {@link ConfigService}
- * @param dataId data ID
- * @param groupId group ID
- * @param listener {@link Listener} instance
- * @param registered registered or not unregistered
- */
- public NacosConfigListenerRegisteredEvent(ConfigService configService, String dataId, String groupId,
- Listener listener, boolean registered) {
- super(configService, dataId, groupId);
- this.listener = listener;
- this.registered = registered;
- }
+ /**
+ * @param configService Nacos {@link ConfigService}
+ * @param dataId data ID
+ * @param groupId group ID
+ * @param listener {@link Listener} instance
+ * @param registered registered or not unregistered
+ */
+ public NacosConfigListenerRegisteredEvent(ConfigService configService, String dataId,
+ String groupId, Listener listener, boolean registered) {
+ super(configService, dataId, groupId);
+ this.listener = listener;
+ this.registered = registered;
+ }
- public Listener getListener() {
- return listener;
- }
+ public Listener getListener() {
+ return listener;
+ }
- public boolean isRegistered() {
- return registered;
- }
+ public boolean isRegistered() {
+ return registered;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigMetadataEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigMetadataEvent.java
index d5cbbdbc..4abfd8b2 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigMetadataEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigMetadataEvent.java
@@ -16,19 +16,20 @@
*/
package com.alibaba.nacos.spring.context.event.config;
-import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
-import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
-import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
-import org.springframework.context.ApplicationEvent;
-import org.springframework.core.io.Resource;
-import org.w3c.dom.Element;
-
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;
+import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
+import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
+import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
+import org.w3c.dom.Element;
+
+import org.springframework.context.ApplicationEvent;
+import org.springframework.core.io.Resource;
+
/**
* Nacos Config Meta-Data {@link NacosConfigEvent event}
*
@@ -37,129 +38,131 @@
*/
public class NacosConfigMetadataEvent extends ApplicationEvent {
- private String dataId;
+ private String dataId;
- private String groupId;
-
- private String beanName;
-
- private Object bean;
-
- private Class> beanType;
-
- private AnnotatedElement annotatedElement;
-
- private Resource xmlResource;
-
- private Properties nacosProperties;
-
- private Map nacosPropertiesAttributes;
-
- /**
- * Create a new ApplicationEvent.
- *
- * @param source maybe {@link Annotation} or {@link Element XML element}
- * @see NacosConfigListener
- * @see NacosConfigurationProperties
- * @see NacosPropertySource
- * @see Element
- */
- public NacosConfigMetadataEvent(Object source) {
- super(source);
- }
-
- public String getDataId() {
- return dataId;
- }
-
- public void setDataId(String dataId) {
- this.dataId = dataId;
- }
-
- public String getGroupId() {
- return groupId;
- }
-
- public void setGroupId(String groupId) {
- this.groupId = groupId;
- }
-
- public String getBeanName() {
- return beanName;
- }
-
- public void setBeanName(String beanName) {
- this.beanName = beanName;
- }
-
- public Object getBean() {
- return bean;
- }
-
- public void setBean(Object bean) {
- this.bean = bean;
- }
-
- public Class> getBeanType() {
- return beanType;
- }
-
- public void setBeanType(Class> beanType) {
- this.beanType = beanType;
- }
-
- /**
- * {@link AnnotatedElement} maybe {@link Class}, {@link Method}
- *
- * @return maybe null
if source from XML configuration
- * @see NacosConfigListener
- * @see NacosConfigurationProperties
- * @see NacosPropertySource
- */
- public AnnotatedElement getAnnotatedElement() {
- return annotatedElement;
- }
-
- public void setAnnotatedElement(AnnotatedElement annotatedElement) {
- this.annotatedElement = annotatedElement;
- }
-
- /**
- * {@link Resource} for XML configuration
- *
- * @return maybe null
if Annotated by somewhere
- */
- public Resource getXmlResource() {
- return xmlResource;
- }
-
- public void setXmlResource(Resource xmlResource) {
- this.xmlResource = xmlResource;
- }
-
- /**
- * Actual effective Nacos {@link Properties}
- *
- * @return non-null
- */
- public Properties getNacosProperties() {
- return nacosProperties;
- }
-
- public void setNacosProperties(Properties nacosProperties) {
- this.nacosProperties = nacosProperties;
- }
-
- /**
- * Nacos {@link Properties}'s attributes that may come frome {@link Annotation} or {@link Element XML element}
- *
- * @return non-null
- */
- public Map getNacosPropertiesAttributes() {
- return nacosPropertiesAttributes;
- }
-
- public void setNacosPropertiesAttributes(Map nacosPropertiesAttributes) {
- this.nacosPropertiesAttributes = nacosPropertiesAttributes;
- }
+ private String groupId;
+
+ private String beanName;
+
+ private Object bean;
+
+ private Class> beanType;
+
+ private AnnotatedElement annotatedElement;
+
+ private Resource xmlResource;
+
+ private Properties nacosProperties;
+
+ private Map nacosPropertiesAttributes;
+
+ /**
+ * Create a new ApplicationEvent.
+ *
+ * @param source maybe {@link Annotation} or {@link Element XML element}
+ * @see NacosConfigListener
+ * @see NacosConfigurationProperties
+ * @see NacosPropertySource
+ * @see Element
+ */
+ public NacosConfigMetadataEvent(Object source) {
+ super(source);
+ }
+
+ public String getDataId() {
+ return dataId;
+ }
+
+ public void setDataId(String dataId) {
+ this.dataId = dataId;
+ }
+
+ public String getGroupId() {
+ return groupId;
+ }
+
+ public void setGroupId(String groupId) {
+ this.groupId = groupId;
+ }
+
+ public String getBeanName() {
+ return beanName;
+ }
+
+ public void setBeanName(String beanName) {
+ this.beanName = beanName;
+ }
+
+ public Object getBean() {
+ return bean;
+ }
+
+ public void setBean(Object bean) {
+ this.bean = bean;
+ }
+
+ public Class> getBeanType() {
+ return beanType;
+ }
+
+ public void setBeanType(Class> beanType) {
+ this.beanType = beanType;
+ }
+
+ /**
+ * {@link AnnotatedElement} maybe {@link Class}, {@link Method}
+ *
+ * @return maybe null
if source from XML configuration
+ * @see NacosConfigListener
+ * @see NacosConfigurationProperties
+ * @see NacosPropertySource
+ */
+ public AnnotatedElement getAnnotatedElement() {
+ return annotatedElement;
+ }
+
+ public void setAnnotatedElement(AnnotatedElement annotatedElement) {
+ this.annotatedElement = annotatedElement;
+ }
+
+ /**
+ * {@link Resource} for XML configuration
+ *
+ * @return maybe null
if Annotated by somewhere
+ */
+ public Resource getXmlResource() {
+ return xmlResource;
+ }
+
+ public void setXmlResource(Resource xmlResource) {
+ this.xmlResource = xmlResource;
+ }
+
+ /**
+ * Actual effective Nacos {@link Properties}
+ *
+ * @return non-null
+ */
+ public Properties getNacosProperties() {
+ return nacosProperties;
+ }
+
+ public void setNacosProperties(Properties nacosProperties) {
+ this.nacosProperties = nacosProperties;
+ }
+
+ /**
+ * Nacos {@link Properties}'s attributes that may come frome {@link Annotation} or
+ * {@link Element XML element}
+ *
+ * @return non-null
+ */
+ public Map getNacosPropertiesAttributes() {
+ return nacosPropertiesAttributes;
+ }
+
+ public void setNacosPropertiesAttributes(
+ Map nacosPropertiesAttributes) {
+ this.nacosPropertiesAttributes = nacosPropertiesAttributes;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigPublishedEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigPublishedEvent.java
index 6a6e0c7b..d3c4ec7b 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigPublishedEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigPublishedEvent.java
@@ -26,32 +26,34 @@
*/
public class NacosConfigPublishedEvent extends NacosConfigEvent {
- private final String content;
+ private final String content;
- private final boolean published;
+ private final boolean published;
- public NacosConfigPublishedEvent(ConfigService configService, String dataId, String groupId, String content,
- boolean published) {
- super(configService, dataId, groupId);
- this.content = content;
- this.published = published;
- }
+ public NacosConfigPublishedEvent(ConfigService configService, String dataId,
+ String groupId, String content, boolean published) {
+ super(configService, dataId, groupId);
+ this.content = content;
+ this.published = published;
+ }
- /**
- * Get Content of published Nacos Configuration
- *
- * @return content
- */
- public String getContent() {
- return content;
- }
+ /**
+ * Get Content of published Nacos Configuration
+ *
+ * @return content
+ */
+ public String getContent() {
+ return content;
+ }
- /**
- * Is published or not from {@link ConfigService#publishConfig(String, String, String)} method executing result.
- *
- * @return if published , return true
- */
- public boolean isPublished() {
- return published;
- }
+ /**
+ * Is published or not from
+ * {@link ConfigService#publishConfig(String, String, String)} method executing
+ * result.
+ *
+ * @return if published , return true
+ */
+ public boolean isPublished() {
+ return published;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigReceivedEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigReceivedEvent.java
index cc8bb511..51de09ac 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigReceivedEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigReceivedEvent.java
@@ -26,25 +26,27 @@
*/
public class NacosConfigReceivedEvent extends NacosConfigEvent {
- private final String content;
- private final String type;
+ private final String content;
+ private final String type;
- public NacosConfigReceivedEvent(ConfigService configService, String dataId, String groupId, String content, String type) {
- super(configService, dataId, groupId);
- this.content = content;
- this.type = type;
- }
+ public NacosConfigReceivedEvent(ConfigService configService, String dataId,
+ String groupId, String content, String type) {
+ super(configService, dataId, groupId);
+ this.content = content;
+ this.type = type;
+ }
- /**
- * Get Content of published Nacos Configuration
- *
- * @return content
- */
- public String getContent() {
- return content;
- }
+ /**
+ * Get Content of published Nacos Configuration
+ *
+ * @return content
+ */
+ public String getContent() {
+ return content;
+ }
+
+ public String getType() {
+ return type;
+ }
- public String getType() {
- return type;
- }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigRemovedEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigRemovedEvent.java
index 0785e9b6..5ae00c56 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigRemovedEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigRemovedEvent.java
@@ -26,19 +26,21 @@
*/
public class NacosConfigRemovedEvent extends NacosConfigEvent {
- private final boolean removed;
+ private final boolean removed;
- public NacosConfigRemovedEvent(ConfigService configService, String dataId, String groupId, boolean removed) {
- super(configService, dataId, groupId);
- this.removed = removed;
- }
+ public NacosConfigRemovedEvent(ConfigService configService, String dataId,
+ String groupId, boolean removed) {
+ super(configService, dataId, groupId);
+ this.removed = removed;
+ }
- /**
- * Is removed or not from {@link ConfigService#removeConfig(String, String)} method executing result.
- *
- * @return if removed , return true
- */
- public boolean isRemoved() {
- return removed;
- }
+ /**
+ * Is removed or not from {@link ConfigService#removeConfig(String, String)} method
+ * executing result.
+ *
+ * @return if removed , return true
+ */
+ public boolean isRemoved() {
+ return removed;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigTimeoutEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigTimeoutEvent.java
index 44b3dd66..bb69a381 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigTimeoutEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigTimeoutEvent.java
@@ -19,45 +19,47 @@
import com.alibaba.nacos.api.config.ConfigService;
/**
- * {@link NacosConfigEvent Nacos config event} for {@link ConfigService#getConfig(String, String, long) getting} timeout.
+ * {@link NacosConfigEvent Nacos config event} for
+ * {@link ConfigService#getConfig(String, String, long) getting} timeout.
*
* @author Mercy
* @since 0.1.0
*/
public class NacosConfigTimeoutEvent extends NacosConfigEvent {
- private final long timeout;
+ private final long timeout;
- private final String errorMessage;
+ private final String errorMessage;
- /**
- * @param configService Nacos {@link ConfigService}
- * @param dataId data ID
- * @param groupId group ID
- * @param timeout timeout in Millis.
- * @param errorMessage error message
- */
- public NacosConfigTimeoutEvent(ConfigService configService, String dataId, String groupId, long timeout, String errorMessage) {
- super(configService, dataId, groupId);
- this.timeout = timeout;
- this.errorMessage = errorMessage;
- }
+ /**
+ * @param configService Nacos {@link ConfigService}
+ * @param dataId data ID
+ * @param groupId group ID
+ * @param timeout timeout in Millis.
+ * @param errorMessage error message
+ */
+ public NacosConfigTimeoutEvent(ConfigService configService, String dataId,
+ String groupId, long timeout, String errorMessage) {
+ super(configService, dataId, groupId);
+ this.timeout = timeout;
+ this.errorMessage = errorMessage;
+ }
- /**
- * Get timeout in Millis.
- *
- * @return timeout in Millis
- */
- public long getTimeout() {
- return timeout;
- }
+ /**
+ * Get timeout in Millis.
+ *
+ * @return timeout in Millis
+ */
+ public long getTimeout() {
+ return timeout;
+ }
- /**
- * get error message
- *
- * @return error message
- */
- public String getErrorMessage() {
- return errorMessage;
- }
+ /**
+ * get error message
+ *
+ * @return error message
+ */
+ public String getErrorMessage() {
+ return errorMessage;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigurationPropertiesBeanBoundEvent.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigurationPropertiesBeanBoundEvent.java
index bd6e71ad..3a1826bf 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigurationPropertiesBeanBoundEvent.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/NacosConfigurationPropertiesBeanBoundEvent.java
@@ -16,11 +16,11 @@
*/
package com.alibaba.nacos.spring.context.event.config;
+import java.util.EventObject;
+
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
-import java.util.EventObject;
-
/**
* {@link NacosConfigurationProperties} Bean Bound {@link EventObject event}.
*
@@ -29,50 +29,46 @@
*/
public class NacosConfigurationPropertiesBeanBoundEvent extends NacosConfigEvent {
- private final Object bean;
+ private final Object bean;
- private final String beanName;
+ private final String beanName;
- private final NacosConfigurationProperties properties;
+ private final NacosConfigurationProperties properties;
- private final String content;
+ private final String content;
- /**
- * @param configService Nacos {@link ConfigService}
- * @param dataId data ID
- * @param groupId group ID
- * @param bean annotated {@link NacosConfigurationProperties} bean
- * @param beanName the name of annotated {@link NacosConfigurationProperties} bean
- * @param properties {@link NacosConfigurationProperties} object
- * @param content the Nacos content for binding
- */
- public NacosConfigurationPropertiesBeanBoundEvent(ConfigService configService,
- String dataId,
- String groupId,
- Object bean,
- String beanName,
- NacosConfigurationProperties properties,
- String content) {
- super(configService, dataId, groupId);
- this.bean = bean;
- this.beanName = beanName;
- this.properties = properties;
- this.content = content;
- }
+ /**
+ * @param configService Nacos {@link ConfigService}
+ * @param dataId data ID
+ * @param groupId group ID
+ * @param bean annotated {@link NacosConfigurationProperties} bean
+ * @param beanName the name of annotated {@link NacosConfigurationProperties} bean
+ * @param properties {@link NacosConfigurationProperties} object
+ * @param content the Nacos content for binding
+ */
+ public NacosConfigurationPropertiesBeanBoundEvent(ConfigService configService,
+ String dataId, String groupId, Object bean, String beanName,
+ NacosConfigurationProperties properties, String content) {
+ super(configService, dataId, groupId);
+ this.bean = bean;
+ this.beanName = beanName;
+ this.properties = properties;
+ this.content = content;
+ }
- public Object getBean() {
- return bean;
- }
+ public Object getBean() {
+ return bean;
+ }
- public String getBeanName() {
- return beanName;
- }
+ public String getBeanName() {
+ return beanName;
+ }
- public NacosConfigurationProperties getProperties() {
- return properties;
- }
+ public NacosConfigurationProperties getProperties() {
+ return properties;
+ }
- public String getContent() {
- return content;
- }
+ public String getContent() {
+ return content;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListener.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListener.java
index 33beeb6a..5cc888fd 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListener.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListener.java
@@ -16,14 +16,20 @@
*/
package com.alibaba.nacos.spring.context.event.config;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.config.listener.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.*;
-import java.util.concurrent.atomic.AtomicInteger;
-
/**
* Timeout {@link Listener Nacos Config Listener}
*
@@ -32,67 +38,74 @@
*/
public abstract class TimeoutNacosConfigListener extends AbstractListener {
- private static AtomicInteger id = new AtomicInteger(0);
+ private static AtomicInteger id = new AtomicInteger(0);
- private static ExecutorService executorService = Executors.newScheduledThreadPool(8, new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- Thread t = new Thread(r);
- t.setDaemon(true);
- t.setName("com.alibaba.nacos.spring.configListener-" + id.incrementAndGet());
- return t;
- }
- });
+ private static ExecutorService executorService = Executors.newScheduledThreadPool(8,
+ new ThreadFactory() {
+ @Override
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(r);
+ t.setDaemon(true);
+ t.setName("com.alibaba.nacos.spring.configListener-"
+ + id.incrementAndGet());
+ return t;
+ }
+ });
- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());
- private final String dataId;
+ private final String dataId;
- private final String groupId;
+ private final String groupId;
- private final long timeout;
+ private final long timeout;
- public TimeoutNacosConfigListener(String dataId, String groupId, long timeout) {
- this.dataId = dataId;
- this.groupId = groupId;
- this.timeout = timeout;
- }
+ public TimeoutNacosConfigListener(String dataId, String groupId, long timeout) {
+ this.dataId = dataId;
+ this.groupId = groupId;
+ this.timeout = timeout;
+ }
- @Override
- public void receiveConfigInfo(final String content) {
- Future future = executorService.submit(new Runnable() {
- @Override
- public void run() {
- onReceived(content);
- }
- });
- try {
- future.get(timeout, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new RuntimeException(e);
- } catch (ExecutionException e) {
- throw new RuntimeException(e);
- } catch (TimeoutException e) {
- future.cancel(true);
- logger.warn("Listening on Nacos Config exceeds timeout {} ms " +
- "[dataId : {}, groupId : {}, data : {}]", timeout, dataId, groupId, content);
- }
- }
+ @Override
+ public void receiveConfigInfo(final String content) {
+ Future future = executorService.submit(new Runnable() {
+ @Override
+ public void run() {
+ onReceived(content);
+ }
+ });
+ try {
+ future.get(timeout, TimeUnit.MILLISECONDS);
+ }
+ catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ catch (ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ catch (TimeoutException e) {
+ future.cancel(true);
+ logger.warn(
+ "Listening on Nacos Config exceeds timeout {} ms "
+ + "[dataId : {}, groupId : {}, data : {}]",
+ timeout, dataId, groupId, content);
+ }
+ }
- /**
- * process Nacos Config when received.
- *
- * @param content Nacos Config
- */
- protected abstract void onReceived(String content);
+ /**
+ * process Nacos Config when received.
+ *
+ * @param content Nacos Config
+ */
+ protected abstract void onReceived(String content);
- /**
- * Get timeout in milliseconds
- *
- * @return timeout in milliseconds
- */
- public long getTimeout() {
- return timeout;
- }
+ /**
+ * Get timeout in milliseconds
+ *
+ * @return timeout in milliseconds
+ */
+ public long getTimeout() {
+ return timeout;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinder.java
index fdc24f4a..916b539f 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinder.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinder.java
@@ -16,12 +16,13 @@
*/
package com.alibaba.nacos.spring.context.properties.config;
+import java.util.Map;
+import java.util.Properties;
+
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
-import com.alibaba.nacos.api.config.annotation.NacosIgnore;
-import com.alibaba.nacos.api.config.annotation.NacosProperty;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
@@ -35,26 +36,18 @@
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.MutablePropertyValues;
+
import org.springframework.beans.PropertyValues;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.Assert;
-import org.springframework.util.ReflectionUtils;
import org.springframework.validation.DataBinder;
-import java.lang.reflect.Field;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Map;
-import java.util.Properties;
-import java.util.regex.Pattern;
-
import static com.alibaba.nacos.spring.util.NacosBeanUtils.getConfigServiceBeanBuilder;
import static com.alibaba.nacos.spring.util.NacosUtils.getContent;
-import static com.alibaba.nacos.spring.util.NacosUtils.toProperties;
-import static org.springframework.core.annotation.AnnotationUtils.*;
+import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
+import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes;
import static org.springframework.util.StringUtils.hasText;
/**
@@ -65,127 +58,149 @@
*/
public class NacosConfigurationPropertiesBinder {
- public static final String BEAN_NAME = "nacosConfigurationPropertiesBinder";
-
- private static final Logger logger = LoggerFactory.getLogger(NacosConfigurationPropertiesBinder.class);
-
- private final ConfigurableApplicationContext applicationContext;
-
- private final Environment environment;
-
- private final ApplicationEventPublisher applicationEventPublisher;
-
- private final ConfigServiceBeanBuilder configServiceBeanBuilder;
-
- protected NacosConfigurationPropertiesBinder(ConfigurableApplicationContext applicationContext) {
- Assert.notNull(applicationContext, "ConfigurableApplicationContext must not be null!");
- this.applicationContext = applicationContext;
- this.environment = applicationContext.getEnvironment();
- this.applicationEventPublisher = applicationContext;
- this.configServiceBeanBuilder = getConfigServiceBeanBuilder(applicationContext);
- }
-
- protected void bind(Object bean, String beanName) {
-
- NacosConfigurationProperties properties = findAnnotation(bean.getClass(), NacosConfigurationProperties.class);
-
- bind(bean, beanName, properties);
-
- }
-
- protected void bind(final Object bean, final String beanName, final NacosConfigurationProperties properties) {
-
- Assert.notNull(bean, "Bean must not be null!");
-
- Assert.notNull(properties, "NacosConfigurationProperties must not be null!");
-
- // support read data-id and group-id from spring environment
- final String dataId = NacosUtils.readFromEnvironment(properties.dataId(), environment);
- final String groupId = NacosUtils.readFromEnvironment(properties.groupId(), environment);
- String fileType = NacosUtils.readTypeFromDataId(dataId);
- final String type = StringUtils.isEmpty(fileType) ? (properties.yaml() ? ConfigType.YAML.getType() : properties.type().getType()) : fileType;
-
- final ConfigService configService = configServiceBeanBuilder.build(properties.properties());
-
- // Add a Listener if auto-refreshed
- if (properties.autoRefreshed()) {
-
- Listener listener = new AbstractListener() {
- @Override
- public void receiveConfigInfo(String config) {
- doBind(bean, beanName, dataId, groupId, type, properties, config, configService);
- }
- };
- try {//
- if (configService instanceof EventPublishingConfigService) {
- ((EventPublishingConfigService) configService).addListener(dataId, groupId, type, listener);
- } else {
- configService.addListener(dataId, groupId, listener);
- }
- } catch (NacosException e) {
- if (logger.isErrorEnabled()) {
- logger.error(e.getMessage(), e);
- }
- }
- }
-
- String content = getContent(configService, dataId, groupId);
-
- if (hasText(content)) {
- doBind(bean, beanName, dataId, groupId, type, properties, content, configService);
- }
- }
-
- protected void doBind(Object bean, String beanName, String dataId, String groupId, String type,
- NacosConfigurationProperties properties, String content, ConfigService configService) {
- final String prefix = properties.prefix();
- PropertyValues propertyValues = NacosUtils.resolvePropertyValues(bean, prefix, dataId, groupId, content, type);
- doBind(bean, properties, propertyValues);
- publishBoundEvent(bean, beanName, dataId, groupId, properties, content, configService);
- publishMetadataEvent(bean, beanName, dataId, groupId, properties);
- }
-
- protected void publishMetadataEvent(Object bean, String beanName, String dataId, String groupId,
- NacosConfigurationProperties properties) {
-
- NacosProperties nacosProperties = properties.properties();
-
- NacosConfigMetadataEvent metadataEvent = new NacosConfigMetadataEvent(properties);
-
- // Nacos Metadata
- metadataEvent.setDataId(dataId);
- metadataEvent.setGroupId(groupId);
- Properties resolvedNacosProperties = configServiceBeanBuilder.resolveProperties(nacosProperties);
- Map nacosPropertiesAttributes = getAnnotationAttributes(nacosProperties);
- metadataEvent.setNacosPropertiesAttributes(nacosPropertiesAttributes);
- metadataEvent.setNacosProperties(resolvedNacosProperties);
-
- // Bean Metadata
- Class> beanClass = bean.getClass();
- metadataEvent.setBeanName(beanName);
- metadataEvent.setBean(bean);
- metadataEvent.setBeanType(beanClass);
- metadataEvent.setAnnotatedElement(beanClass);
-
- // Publish event
- applicationEventPublisher.publishEvent(metadataEvent);
- }
-
- protected void publishBoundEvent(Object bean, String beanName, String dataId, String groupId,
- NacosConfigurationProperties properties, String content, ConfigService configService) {
- NacosConfigEvent event = new NacosConfigurationPropertiesBeanBoundEvent(configService, dataId, groupId, bean,
- beanName, properties, content);
- applicationEventPublisher.publishEvent(event);
- }
-
- private void doBind(Object bean, NacosConfigurationProperties properties,
- PropertyValues propertyValues) {
- ObjectUtils.cleanMapOrCollectionField(bean);
- DataBinder dataBinder = new DataBinder(bean);
- dataBinder.setAutoGrowNestedPaths(properties.ignoreNestedProperties());
- dataBinder.setIgnoreInvalidFields(properties.ignoreInvalidFields());
- dataBinder.setIgnoreUnknownFields(properties.ignoreUnknownFields());
- dataBinder.bind(propertyValues);
- }
+ public static final String BEAN_NAME = "nacosConfigurationPropertiesBinder";
+
+ private static final Logger logger = LoggerFactory
+ .getLogger(NacosConfigurationPropertiesBinder.class);
+
+ private final ConfigurableApplicationContext applicationContext;
+
+ private final Environment environment;
+
+ private final ApplicationEventPublisher applicationEventPublisher;
+
+ private final ConfigServiceBeanBuilder configServiceBeanBuilder;
+
+ protected NacosConfigurationPropertiesBinder(
+ ConfigurableApplicationContext applicationContext) {
+ Assert.notNull(applicationContext,
+ "ConfigurableApplicationContext must not be null!");
+ this.applicationContext = applicationContext;
+ this.environment = applicationContext.getEnvironment();
+ this.applicationEventPublisher = applicationContext;
+ this.configServiceBeanBuilder = getConfigServiceBeanBuilder(applicationContext);
+ }
+
+ protected void bind(Object bean, String beanName) {
+
+ NacosConfigurationProperties properties = findAnnotation(bean.getClass(),
+ NacosConfigurationProperties.class);
+
+ bind(bean, beanName, properties);
+
+ }
+
+ protected void bind(final Object bean, final String beanName,
+ final NacosConfigurationProperties properties) {
+
+ Assert.notNull(bean, "Bean must not be null!");
+
+ Assert.notNull(properties, "NacosConfigurationProperties must not be null!");
+
+ // support read data-id and group-id from spring environment
+ final String dataId = NacosUtils.readFromEnvironment(properties.dataId(),
+ environment);
+ final String groupId = NacosUtils.readFromEnvironment(properties.groupId(),
+ environment);
+ String fileType = NacosUtils.readTypeFromDataId(dataId);
+ final String type = StringUtils.isEmpty(fileType)
+ ? (properties.yaml() ? ConfigType.YAML.getType()
+ : properties.type().getType())
+ : fileType;
+
+ final ConfigService configService = configServiceBeanBuilder
+ .build(properties.properties());
+
+ // Add a Listener if auto-refreshed
+ if (properties.autoRefreshed()) {
+
+ Listener listener = new AbstractListener() {
+ @Override
+ public void receiveConfigInfo(String config) {
+ doBind(bean, beanName, dataId, groupId, type, properties, config,
+ configService);
+ }
+ };
+ try {//
+ if (configService instanceof EventPublishingConfigService) {
+ ((EventPublishingConfigService) configService).addListener(dataId,
+ groupId, type, listener);
+ }
+ else {
+ configService.addListener(dataId, groupId, listener);
+ }
+ }
+ catch (NacosException e) {
+ if (logger.isErrorEnabled()) {
+ logger.error(e.getMessage(), e);
+ }
+ }
+ }
+
+ String content = getContent(configService, dataId, groupId);
+
+ if (hasText(content)) {
+ doBind(bean, beanName, dataId, groupId, type, properties, content,
+ configService);
+ }
+ }
+
+ protected void doBind(Object bean, String beanName, String dataId, String groupId,
+ String type, NacosConfigurationProperties properties, String content,
+ ConfigService configService) {
+ final String prefix = properties.prefix();
+ PropertyValues propertyValues = NacosUtils.resolvePropertyValues(bean, prefix,
+ dataId, groupId, content, type);
+ doBind(bean, properties, propertyValues);
+ publishBoundEvent(bean, beanName, dataId, groupId, properties, content,
+ configService);
+ publishMetadataEvent(bean, beanName, dataId, groupId, properties);
+ }
+
+ protected void publishMetadataEvent(Object bean, String beanName, String dataId,
+ String groupId, NacosConfigurationProperties properties) {
+
+ NacosProperties nacosProperties = properties.properties();
+
+ NacosConfigMetadataEvent metadataEvent = new NacosConfigMetadataEvent(properties);
+
+ // Nacos Metadata
+ metadataEvent.setDataId(dataId);
+ metadataEvent.setGroupId(groupId);
+ Properties resolvedNacosProperties = configServiceBeanBuilder
+ .resolveProperties(nacosProperties);
+ Map nacosPropertiesAttributes = getAnnotationAttributes(
+ nacosProperties);
+ metadataEvent.setNacosPropertiesAttributes(nacosPropertiesAttributes);
+ metadataEvent.setNacosProperties(resolvedNacosProperties);
+
+ // Bean Metadata
+ Class> beanClass = bean.getClass();
+ metadataEvent.setBeanName(beanName);
+ metadataEvent.setBean(bean);
+ metadataEvent.setBeanType(beanClass);
+ metadataEvent.setAnnotatedElement(beanClass);
+
+ // Publish event
+ applicationEventPublisher.publishEvent(metadataEvent);
+ }
+
+ protected void publishBoundEvent(Object bean, String beanName, String dataId,
+ String groupId, NacosConfigurationProperties properties, String content,
+ ConfigService configService) {
+ NacosConfigEvent event = new NacosConfigurationPropertiesBeanBoundEvent(
+ configService, dataId, groupId, bean, beanName, properties, content);
+ applicationEventPublisher.publishEvent(event);
+ }
+
+ private void doBind(Object bean, NacosConfigurationProperties properties,
+ PropertyValues propertyValues) {
+ ObjectUtils.cleanMapOrCollectionField(bean);
+ DataBinder dataBinder = new DataBinder(bean);
+ dataBinder.setAutoGrowNestedPaths(properties.ignoreNestedProperties());
+ dataBinder.setIgnoreInvalidFields(properties.ignoreInvalidFields());
+ dataBinder.setIgnoreUnknownFields(properties.ignoreUnknownFields());
+ dataBinder.bind(propertyValues);
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessor.java
index 91cb5e79..e6f8a22d 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessor.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessor.java
@@ -16,8 +16,11 @@
*/
package com.alibaba.nacos.spring.context.properties.config;
+import java.util.Properties;
+
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import com.alibaba.nacos.spring.factory.NacosServiceFactory;
+
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
@@ -26,8 +29,6 @@
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
-import java.util.Properties;
-
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
/**
@@ -38,61 +39,68 @@
* @see BeanPostProcessor
* @since 0.1.0
*/
-public class NacosConfigurationPropertiesBindingPostProcessor implements BeanPostProcessor, ApplicationContextAware {
-
- /**
- * The name of {@link NacosConfigurationPropertiesBindingPostProcessor} Bean
- */
- public static final String BEAN_NAME = "nacosConfigurationPropertiesBindingPostProcessor";
+public class NacosConfigurationPropertiesBindingPostProcessor
+ implements BeanPostProcessor, ApplicationContextAware {
- private Properties globalNacosProperties;
+ /**
+ * The name of {@link NacosConfigurationPropertiesBindingPostProcessor} Bean
+ */
+ public static final String BEAN_NAME = "nacosConfigurationPropertiesBindingPostProcessor";
- private NacosServiceFactory nacosServiceFactory;
+ private Properties globalNacosProperties;
- private Environment environment;
+ private NacosServiceFactory nacosServiceFactory;
- private ApplicationEventPublisher applicationEventPublisher;
+ private Environment environment;
- private ConfigurableApplicationContext applicationContext;
+ private ApplicationEventPublisher applicationEventPublisher;
- @Override
- public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
+ private ConfigurableApplicationContext applicationContext;
- NacosConfigurationProperties nacosConfigurationProperties = findAnnotation(bean.getClass(), NacosConfigurationProperties.class);
+ @Override
+ public Object postProcessBeforeInitialization(Object bean, String beanName)
+ throws BeansException {
- if (nacosConfigurationProperties != null) {
- bind(bean, beanName, nacosConfigurationProperties);
- }
+ NacosConfigurationProperties nacosConfigurationProperties = findAnnotation(
+ bean.getClass(), NacosConfigurationProperties.class);
- return bean;
- }
+ if (nacosConfigurationProperties != null) {
+ bind(bean, beanName, nacosConfigurationProperties);
+ }
- private void bind(Object bean, String beanName, NacosConfigurationProperties nacosConfigurationProperties) {
+ return bean;
+ }
- NacosConfigurationPropertiesBinder binder;
- try {
- binder = applicationContext
- .getBean(NacosConfigurationPropertiesBinder.BEAN_NAME, NacosConfigurationPropertiesBinder.class);
- if (binder == null) {
- binder = new NacosConfigurationPropertiesBinder(applicationContext);
- }
+ private void bind(Object bean, String beanName,
+ NacosConfigurationProperties nacosConfigurationProperties) {
- } catch (Exception e) {
- binder = new NacosConfigurationPropertiesBinder(applicationContext);
- }
+ NacosConfigurationPropertiesBinder binder;
+ try {
+ binder = applicationContext.getBean(
+ NacosConfigurationPropertiesBinder.BEAN_NAME,
+ NacosConfigurationPropertiesBinder.class);
+ if (binder == null) {
+ binder = new NacosConfigurationPropertiesBinder(applicationContext);
+ }
- binder.bind(bean, beanName, nacosConfigurationProperties);
+ }
+ catch (Exception e) {
+ binder = new NacosConfigurationPropertiesBinder(applicationContext);
+ }
- }
+ binder.bind(bean, beanName, nacosConfigurationProperties);
+ }
- @Override
- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
- return bean;
- }
+ @Override
+ public Object postProcessAfterInitialization(Object bean, String beanName)
+ throws BeansException {
+ return bean;
+ }
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- this.applicationContext = (ConfigurableApplicationContext) applicationContext;
- }
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext)
+ throws BeansException {
+ this.applicationContext = (ConfigurableApplicationContext) applicationContext;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/convert/converter/config/DefaultNacosConfigConverter.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/convert/converter/config/DefaultNacosConfigConverter.java
index 98443332..551a60b8 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/convert/converter/config/DefaultNacosConfigConverter.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/convert/converter/config/DefaultNacosConfigConverter.java
@@ -17,6 +17,7 @@
package com.alibaba.nacos.spring.convert.converter.config;
import com.alibaba.nacos.api.config.convert.NacosConfigConverter;
+
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
@@ -28,32 +29,33 @@
*/
public class DefaultNacosConfigConverter implements NacosConfigConverter {
- private final Class targetType;
+ private final Class targetType;
- private final ConversionService conversionService;
+ private final ConversionService conversionService;
- private final String type;
+ private final String type;
- public DefaultNacosConfigConverter(Class targetType) {
- this(targetType, new DefaultFormattingConversionService(), "properties");
- }
+ public DefaultNacosConfigConverter(Class targetType) {
+ this(targetType, new DefaultFormattingConversionService(), "properties");
+ }
- public DefaultNacosConfigConverter(Class targetType, ConversionService conversionService, String type) {
- this.targetType = targetType;
- this.conversionService = conversionService;
- this.type = type;
- }
+ public DefaultNacosConfigConverter(Class targetType,
+ ConversionService conversionService, String type) {
+ this.targetType = targetType;
+ this.conversionService = conversionService;
+ this.type = type;
+ }
- @Override
- public T convert(String source) {
- if (conversionService.canConvert(source.getClass(), targetType)) {
- return conversionService.convert(source, targetType);
- }
- return null;
- }
+ @Override
+ public T convert(String source) {
+ if (conversionService.canConvert(source.getClass(), targetType)) {
+ return conversionService.convert(source, targetType);
+ }
+ return null;
+ }
- @Override
- public boolean canConvert(Class targetType) {
- return conversionService.canConvert(String.class, targetType);
- }
+ @Override
+ public boolean canConvert(Class targetType) {
+ return conversionService.canConvert(String.class, targetType);
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AbstractNacosPropertySourceBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AbstractNacosPropertySourceBuilder.java
index ada62145..a7732a5f 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AbstractNacosPropertySourceBuilder.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AbstractNacosPropertySourceBuilder.java
@@ -16,6 +16,12 @@
*/
package com.alibaba.nacos.spring.core.env;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.spring.context.event.DeferredApplicationEventPublisher;
import com.alibaba.nacos.spring.context.event.config.NacosConfigMetadataEvent;
@@ -23,28 +29,34 @@
import com.alibaba.nacos.spring.util.config.NacosConfigLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
-import org.springframework.context.*;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
-import java.util.*;
-
-import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.*;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.CONFIG_TYPE_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.DATA_ID_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.GROUP_ID_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.NAME_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.PROPERTIES_ATTRIBUTE_NAME;
import static com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource.CONFIG;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosServiceFactoryBean;
import static com.alibaba.nacos.spring.util.NacosUtils.buildDefaultPropertySourceName;
import static com.alibaba.nacos.spring.util.NacosUtils.resolveProperties;
import static com.alibaba.spring.util.ClassUtils.resolveGenericType;
import static java.lang.String.format;
-import static java.lang.String.valueOf;
import static org.springframework.util.ClassUtils.resolveClassName;
/**
@@ -54,205 +66,218 @@
* @author Mercy
* @since 0.1.0
*/
-public abstract class AbstractNacosPropertySourceBuilder implements EnvironmentAware,
- BeanFactoryAware, BeanClassLoaderAware, ApplicationContextAware, InitializingBean {
-
- protected final Logger logger = LoggerFactory.getLogger(this.getClass());
-
- protected ConfigurableEnvironment environment;
-
- protected BeanFactory beanFactory;
-
- private NacosConfigLoader nacosConfigLoader;
-
- private Properties globalNacosProperties;
-
- private final Class beanDefinitionType;
-
- private ClassLoader classLoader;
-
- private ApplicationEventPublisher applicationEventPublisher;
-
- public AbstractNacosPropertySourceBuilder() {
- beanDefinitionType = resolveGenericType(getClass());
- }
-
- /**
- * Build {@link NacosPropertySource} from {@link BeanDefinition}
- *
- * @param beanName Bean name
- * @param beanDefinition {@link BeanDefinition}
- * @return a {@link NacosPropertySource} instance
- */
- public List build(String beanName, T beanDefinition) {
+public abstract class AbstractNacosPropertySourceBuilder
+ implements EnvironmentAware, BeanFactoryAware, BeanClassLoaderAware,
+ ApplicationContextAware, InitializingBean {
- Map[] attributesArray = resolveRuntimeAttributesArray(beanDefinition, globalNacosProperties);
+ protected final Logger logger = LoggerFactory.getLogger(this.getClass());
- int size = attributesArray == null ? 0 : attributesArray.length;
+ protected ConfigurableEnvironment environment;
- if (size == 0) {
- return Collections.emptyList();
- }
+ protected BeanFactory beanFactory;
- List nacosPropertySources = new ArrayList(size);
+ private NacosConfigLoader nacosConfigLoader;
- for (int i = 0; i < size; i++) {
- Map attributes = attributesArray[i];
- if (!CollectionUtils.isEmpty(attributes)) {
+ private Properties globalNacosProperties;
- NacosPropertySource nacosPropertySource = doBuild(beanName, beanDefinition, attributesArray[i]);
+ private final Class beanDefinitionType;
- NacosConfigMetadataEvent metadataEvent = createMetaEvent(nacosPropertySource, beanDefinition);
+ private ClassLoader classLoader;
- initMetadataEvent(nacosPropertySource, beanDefinition, metadataEvent);
+ private ApplicationEventPublisher applicationEventPublisher;
- publishMetadataEvent(metadataEvent);
+ public AbstractNacosPropertySourceBuilder() {
+ beanDefinitionType = resolveGenericType(getClass());
+ }
- nacosPropertySources.add(nacosPropertySource);
+ /**
+ * Build {@link NacosPropertySource} from {@link BeanDefinition}
+ *
+ * @param beanName Bean name
+ * @param beanDefinition {@link BeanDefinition}
+ * @return a {@link NacosPropertySource} instance
+ */
+ public List build(String beanName, T beanDefinition) {
- }
- }
+ Map[] attributesArray = resolveRuntimeAttributesArray(
+ beanDefinition, globalNacosProperties);
- return nacosPropertySources;
- }
+ int size = attributesArray == null ? 0 : attributesArray.length;
- protected abstract NacosConfigMetadataEvent createMetaEvent(NacosPropertySource nacosPropertySource, T beanDefinition);
+ if (size == 0) {
+ return Collections.emptyList();
+ }
- private void initMetadataEvent(NacosPropertySource nacosPropertySource, T beanDefinition,
- NacosConfigMetadataEvent metadataEvent) {
- metadataEvent.setDataId(nacosPropertySource.getDataId());
- metadataEvent.setGroupId(nacosPropertySource.getGroupId());
- metadataEvent.setBeanName(nacosPropertySource.getBeanName());
- metadataEvent.setBeanType(nacosPropertySource.getBeanType());
- metadataEvent.setNacosProperties(nacosPropertySource.getProperties());
- Map attributesMetadata = nacosPropertySource.getAttributesMetadata();
- Map nacosPropertiesAttributes = (Map) attributesMetadata.get(PROPERTIES_ATTRIBUTE_NAME);
- metadataEvent.setNacosPropertiesAttributes(nacosPropertiesAttributes);
- doInitMetadataEvent(nacosPropertySource, beanDefinition, metadataEvent);
- }
+ List nacosPropertySources = new ArrayList(
+ size);
- private void publishMetadataEvent(NacosConfigMetadataEvent metadataEvent) {
- applicationEventPublisher.publishEvent(metadataEvent);
- }
+ for (int i = 0; i < size; i++) {
+ Map attributes = attributesArray[i];
+ if (!CollectionUtils.isEmpty(attributes)) {
+ NacosPropertySource nacosPropertySource = doBuild(beanName,
+ beanDefinition, attributesArray[i]);
- protected abstract void doInitMetadataEvent(NacosPropertySource nacosPropertySource, T beanDefinition,
- NacosConfigMetadataEvent metadataEvent);
+ NacosConfigMetadataEvent metadataEvent = createMetaEvent(
+ nacosPropertySource, beanDefinition);
+ initMetadataEvent(nacosPropertySource, beanDefinition, metadataEvent);
- protected NacosPropertySource doBuild(String beanName, T beanDefinition, Map runtimeAttributes) {
+ publishMetadataEvent(metadataEvent);
- // Get annotation metadata
- String name = (String) runtimeAttributes.get(NAME_ATTRIBUTE_NAME);
- String dataId = (String) runtimeAttributes.get(DATA_ID_ATTRIBUTE_NAME);
- String groupId = (String) runtimeAttributes.get(GROUP_ID_ATTRIBUTE_NAME);
- String type = ((ConfigType) runtimeAttributes.get(CONFIG_TYPE_ATTRIBUTE_NAME)).getType();
+ nacosPropertySources.add(nacosPropertySource);
- dataId = NacosUtils.readFromEnvironment(dataId, environment);
- groupId = NacosUtils.readFromEnvironment(groupId, environment);
- type = StringUtils.isEmpty(NacosUtils.readTypeFromDataId(dataId)) ? type : NacosUtils.readTypeFromDataId(dataId);
- Map nacosPropertiesAttributes = (Map) runtimeAttributes.get(PROPERTIES_ATTRIBUTE_NAME);
+ }
+ }
- Properties nacosProperties = resolveProperties(nacosPropertiesAttributes, environment, globalNacosProperties);
+ return nacosPropertySources;
+ }
- String nacosConfig = nacosConfigLoader.load(dataId, groupId, nacosProperties);
+ protected abstract NacosConfigMetadataEvent createMetaEvent(
+ NacosPropertySource nacosPropertySource, T beanDefinition);
- if (!StringUtils.hasText(nacosConfig)) {
- if (logger.isWarnEnabled()) {
- logger.warn(format("There is no content for NacosPropertySource from dataId[%s] , groupId[%s] , properties[%s].",
- dataId,
- groupId,
- valueOf(nacosPropertiesAttributes)));
- }
- }
-
- if (!StringUtils.hasText(name)) {
- name = buildDefaultPropertySourceName(dataId, groupId, nacosProperties);
- }
-
- NacosPropertySource nacosPropertySource = new NacosPropertySource(dataId, groupId, name, nacosConfig, type);
-
- nacosPropertySource.setBeanName(beanName);
-
- String beanClassName = beanDefinition.getBeanClassName();
- if (StringUtils.hasText(beanClassName)) {
- nacosPropertySource.setBeanType(resolveClassName(beanClassName, classLoader));
- }
- nacosPropertySource.setGroupId(groupId);
- nacosPropertySource.setDataId(dataId);
- nacosPropertySource.setProperties(nacosProperties);
-
- initNacosPropertySource(nacosPropertySource, beanDefinition, runtimeAttributes);
-
- return nacosPropertySource;
-
- }
-
- /**
- * Runtime attributes must contain those:
- *
- * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#NAME_ATTRIBUTE_NAME}
- * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#DATA_ID_ATTRIBUTE_NAME}
- * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#GROUP_ID_ATTRIBUTE_NAME}
- * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#PROPERTIES_ATTRIBUTE_NAME}
- *
- *
- * @param beanDefinition Bean Definition
- * @param globalNacosProperties Global Nacos {@link Properties}
- * @return a non-null attributes array
- */
- protected abstract Map[] resolveRuntimeAttributesArray(T beanDefinition, Properties globalNacosProperties);
-
- protected abstract void initNacosPropertySource(NacosPropertySource nacosPropertySource, T beanDefinition,
- Map attributes);
-
- /**
- * Whether target {@link BeanDefinition} supports or not
- *
- * @param beanDefinition {@link BeanDefinition}
- * @return If supports, return true
, or false
- */
- public boolean supports(BeanDefinition beanDefinition) {
- Class> beanDefinitionClass = beanDefinition.getClass();
- return beanDefinitionType.isAssignableFrom(beanDefinitionClass);
- }
-
- @Override
- public void setEnvironment(Environment environment) {
- if (environment instanceof ConfigurableEnvironment) {
- this.environment = (ConfigurableEnvironment) environment;
- }
- }
-
- @Override
- public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
- this.beanFactory = beanFactory;
- }
-
- @Override
- public void setBeanClassLoader(ClassLoader classLoader) {
- this.classLoader = classLoader;
- }
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) {
- ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
- this.applicationEventPublisher = new DeferredApplicationEventPublisher(context);
- }
-
- @Override
- public void afterPropertiesSet() throws Exception {
- nacosConfigLoader = new NacosConfigLoader(environment);
- nacosConfigLoader.setNacosServiceFactory(getNacosServiceFactoryBean(beanFactory));
- globalNacosProperties = CONFIG.getMergedGlobalProperties(beanFactory);
- }
-
- /**
- * The type of {@link T Bean Definition}
- *
- * @return type of {@link T Bean Definition}
- */
- public final Class getBeanDefinitionType() {
- return beanDefinitionType;
- }
+ private void initMetadataEvent(NacosPropertySource nacosPropertySource,
+ T beanDefinition, NacosConfigMetadataEvent metadataEvent) {
+ metadataEvent.setDataId(nacosPropertySource.getDataId());
+ metadataEvent.setGroupId(nacosPropertySource.getGroupId());
+ metadataEvent.setBeanName(nacosPropertySource.getBeanName());
+ metadataEvent.setBeanType(nacosPropertySource.getBeanType());
+ metadataEvent.setNacosProperties(nacosPropertySource.getProperties());
+ Map attributesMetadata = nacosPropertySource
+ .getAttributesMetadata();
+ Map nacosPropertiesAttributes = (Map) attributesMetadata
+ .get(PROPERTIES_ATTRIBUTE_NAME);
+ metadataEvent.setNacosPropertiesAttributes(nacosPropertiesAttributes);
+ doInitMetadataEvent(nacosPropertySource, beanDefinition, metadataEvent);
+ }
+
+ private void publishMetadataEvent(NacosConfigMetadataEvent metadataEvent) {
+ applicationEventPublisher.publishEvent(metadataEvent);
+ }
+
+ protected abstract void doInitMetadataEvent(NacosPropertySource nacosPropertySource,
+ T beanDefinition, NacosConfigMetadataEvent metadataEvent);
+
+ protected NacosPropertySource doBuild(String beanName, T beanDefinition,
+ Map runtimeAttributes) {
+
+ // Get annotation metadata
+ String name = (String) runtimeAttributes.get(NAME_ATTRIBUTE_NAME);
+ String dataId = (String) runtimeAttributes.get(DATA_ID_ATTRIBUTE_NAME);
+ String groupId = (String) runtimeAttributes.get(GROUP_ID_ATTRIBUTE_NAME);
+ String type = ((ConfigType) runtimeAttributes.get(CONFIG_TYPE_ATTRIBUTE_NAME))
+ .getType();
+
+ dataId = NacosUtils.readFromEnvironment(dataId, environment);
+ groupId = NacosUtils.readFromEnvironment(groupId, environment);
+ type = StringUtils.isEmpty(NacosUtils.readTypeFromDataId(dataId)) ? type
+ : NacosUtils.readTypeFromDataId(dataId);
+ Map nacosPropertiesAttributes = (Map) runtimeAttributes
+ .get(PROPERTIES_ATTRIBUTE_NAME);
+
+ Properties nacosProperties = resolveProperties(nacosPropertiesAttributes,
+ environment, globalNacosProperties);
+
+ String nacosConfig = nacosConfigLoader.load(dataId, groupId, nacosProperties);
+
+ if (!StringUtils.hasText(nacosConfig)) {
+ if (logger.isWarnEnabled()) {
+ logger.warn(format(
+ "There is no content for NacosPropertySource from dataId[%s] , groupId[%s] , properties[%s].",
+ dataId, groupId, nacosPropertiesAttributes));
+ }
+ }
+
+ if (!StringUtils.hasText(name)) {
+ name = buildDefaultPropertySourceName(dataId, groupId, nacosProperties);
+ }
+
+ NacosPropertySource nacosPropertySource = new NacosPropertySource(dataId, groupId,
+ name, nacosConfig, type);
+
+ nacosPropertySource.setBeanName(beanName);
+
+ String beanClassName = beanDefinition.getBeanClassName();
+ if (StringUtils.hasText(beanClassName)) {
+ nacosPropertySource.setBeanType(resolveClassName(beanClassName, classLoader));
+ }
+ nacosPropertySource.setGroupId(groupId);
+ nacosPropertySource.setDataId(dataId);
+ nacosPropertySource.setProperties(nacosProperties);
+
+ initNacosPropertySource(nacosPropertySource, beanDefinition, runtimeAttributes);
+
+ return nacosPropertySource;
+
+ }
+
+ /**
+ * Runtime attributes must contain those:
+ *
+ * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#NAME_ATTRIBUTE_NAME}
+ * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#DATA_ID_ATTRIBUTE_NAME}
+ * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#GROUP_ID_ATTRIBUTE_NAME}
+ * - {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource#PROPERTIES_ATTRIBUTE_NAME}
+ *
+ *
+ * @param beanDefinition Bean Definition
+ * @param globalNacosProperties Global Nacos {@link Properties}
+ * @return a non-null attributes array
+ */
+ protected abstract Map[] resolveRuntimeAttributesArray(
+ T beanDefinition, Properties globalNacosProperties);
+
+ protected abstract void initNacosPropertySource(
+ NacosPropertySource nacosPropertySource, T beanDefinition,
+ Map attributes);
+
+ /**
+ * Whether target {@link BeanDefinition} supports or not
+ *
+ * @param beanDefinition {@link BeanDefinition}
+ * @return If supports, return true
, or false
+ */
+ public boolean supports(BeanDefinition beanDefinition) {
+ Class> beanDefinitionClass = beanDefinition.getClass();
+ return beanDefinitionType.isAssignableFrom(beanDefinitionClass);
+ }
+
+ @Override
+ public void setEnvironment(Environment environment) {
+ if (environment instanceof ConfigurableEnvironment) {
+ this.environment = (ConfigurableEnvironment) environment;
+ }
+ }
+
+ @Override
+ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+ this.beanFactory = beanFactory;
+ }
+
+ @Override
+ public void setBeanClassLoader(ClassLoader classLoader) {
+ this.classLoader = classLoader;
+ }
+
+ @Override
+ public void setApplicationContext(ApplicationContext applicationContext) {
+ ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
+ this.applicationEventPublisher = new DeferredApplicationEventPublisher(context);
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ nacosConfigLoader = new NacosConfigLoader(environment);
+ nacosConfigLoader.setNacosServiceFactory(getNacosServiceFactoryBean(beanFactory));
+ globalNacosProperties = CONFIG.getMergedGlobalProperties(beanFactory);
+ }
+
+ /**
+ * The type of {@link T Bean Definition}
+ *
+ * @return type of {@link T Bean Definition}
+ */
+ public final Class getBeanDefinitionType() {
+ return beanDefinitionType;
+ }
}
diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AnnotationNacosPropertySourceBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AnnotationNacosPropertySourceBuilder.java
index 79c6f726..4ca3a9d6 100644
--- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AnnotationNacosPropertySourceBuilder.java
+++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/AnnotationNacosPropertySourceBuilder.java
@@ -16,17 +16,27 @@
*/
package com.alibaba.nacos.spring.core.env;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySources;
import com.alibaba.nacos.spring.context.event.config.NacosConfigMetadataEvent;
+
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.core.type.AnnotationMetadata;
-import java.util.*;
-
-import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.*;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.AFTER_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.AUTO_REFRESHED_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.BEFORE_ATTRIBUTE_NAME;
+import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.FIRST_ATTRIBUTE_NAME;
/**
- * Annotation {@link NacosPropertySource @NacosPropertySource} {@link AbstractNacosPropertySourceBuilder Builder}
+ * Annotation {@link NacosPropertySource @NacosPropertySource}
+ * {@link AbstractNacosPropertySourceBuilder Builder}
*
* @author Mercy
* @see NacosPropertySource
@@ -34,91 +44,109 @@
* @see AnnotatedBeanDefinition
* @since 0.1.0
*/
-public class AnnotationNacosPropertySourceBuilder extends AbstractNacosPropertySourceBuilder {
-
- /**
- * The bean name of {@link AnnotationNacosPropertySourceBuilder}
- */
- public static final String BEAN_NAME = "annotationNacosPropertySourceBuilder";
-
- @Override
- protected Map[] resolveRuntimeAttributesArray(AnnotatedBeanDefinition beanDefinition, Properties globalNacosProperties) {
- // Get AnnotationMetadata
- AnnotationMetadata metadata = beanDefinition.getMetadata();
-
- Set annotationTypes = metadata.getAnnotationTypes();
-
- List