diff --git a/eclipse/eclipse-code-formatter.xml b/eclipse/eclipse-code-formatter.xml new file mode 100644 index 00000000..27699187 --- /dev/null +++ b/eclipse/eclipse-code-formatter.xml @@ -0,0 +1,755 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AbstractNacosServiceBeanBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AbstractNacosServiceBeanBuilder.java index 61ad316e..4aaa4a35 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AbstractNacosServiceBeanBuilder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AbstractNacosServiceBeanBuilder.java @@ -16,20 +16,21 @@ */ package com.alibaba.nacos.spring.beans.factory.annotation; +import java.util.Map; +import java.util.Properties; + import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource; import com.alibaba.nacos.spring.util.NacosUtils; + import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; -import java.util.Map; -import java.util.Properties; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosServiceFactoryBean; import static com.alibaba.spring.util.ClassUtils.resolveGenericType; import static java.lang.String.format; @@ -42,91 +43,97 @@ * @author Mercy * @since 0.1.0 */ -public abstract class AbstractNacosServiceBeanBuilder implements BeanFactoryAware, EnvironmentAware { - - private BeanFactory beanFactory; - - private Environment environment; - - private final Class type; - - private final GlobalNacosPropertiesSource source; - - protected AbstractNacosServiceBeanBuilder(GlobalNacosPropertiesSource source) { - type = resolveGenericType(getClass()); - this.source = source; - } - - public S build(NacosProperties nacosProperties) { - return build(getAnnotationAttributes(nacosProperties)); - } - - public S build(Map nacosPropertiesAttributes) { - - NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory); - Properties properties = resolveProperties(nacosPropertiesAttributes); - - if (properties.isEmpty()) { - throw new BeanCreationException( - format("The @%s attributes must be configured", - NacosProperties.class.getSimpleName())); - } - - try { - return createService(nacosServiceFactory, properties); - } catch (NacosException e) { - throw new BeanCreationException(e.getErrMsg(), e); - } - } - - /** - * Subtype would implement this method to create target Nacos Service - * - * @param nacosServiceFactory {@link NacosServiceFactory} - * @param properties {@link Properties} - * @return target Nacos Service instance - * @throws NacosException When Nacos Service creation is failed - */ - protected abstract S createService(NacosServiceFactory nacosServiceFactory, Properties properties) throws NacosException; - - /** - * Resolve Nacos {@link Properties} from {@link NacosProperties @NacosProperties} - * - * @param nacosProperties {@link NacosProperties @NacosProperties} - * @return non-null - */ - public final Properties resolveProperties(NacosProperties nacosProperties) { - Properties globalNacosProperties = resolveGlobalNacosProperties(); - return NacosUtils.resolveProperties(nacosProperties, environment, globalNacosProperties); - } - - /** - * Resolve Nacos {@link Properties} from {@link NacosProperties @NacosProperties} - * - * @param nacosPropertiesAttributes {@link NacosProperties Nacos Properties}'s attributes - * @return non-null - */ - public final Properties resolveProperties(Map nacosPropertiesAttributes) { - Properties globalNacosProperties = resolveGlobalNacosProperties(); - return NacosUtils.resolveProperties(nacosPropertiesAttributes, environment, globalNacosProperties); - } - - private Properties resolveGlobalNacosProperties() { - return source.getMergedGlobalProperties(beanFactory); - } - - - final Class getType() { - return type; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } +public abstract class AbstractNacosServiceBeanBuilder + implements BeanFactoryAware, EnvironmentAware { + + private BeanFactory beanFactory; + + private Environment environment; + + private final Class type; + + private final GlobalNacosPropertiesSource source; + + protected AbstractNacosServiceBeanBuilder(GlobalNacosPropertiesSource source) { + type = resolveGenericType(getClass()); + this.source = source; + } + + public S build(NacosProperties nacosProperties) { + return build(getAnnotationAttributes(nacosProperties)); + } + + public S build(Map nacosPropertiesAttributes) { + + NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory); + Properties properties = resolveProperties(nacosPropertiesAttributes); + + if (properties.isEmpty()) { + throw new BeanCreationException( + format("The @%s attributes must be configured", + NacosProperties.class.getSimpleName())); + } + + try { + return createService(nacosServiceFactory, properties); + } + catch (NacosException e) { + throw new BeanCreationException(e.getErrMsg(), e); + } + } + + /** + * Subtype would implement this method to create target Nacos Service + * + * @param nacosServiceFactory {@link NacosServiceFactory} + * @param properties {@link Properties} + * @return target Nacos Service instance + * @throws NacosException When Nacos Service creation is failed + */ + protected abstract S createService(NacosServiceFactory nacosServiceFactory, + Properties properties) throws NacosException; + + /** + * Resolve Nacos {@link Properties} from {@link NacosProperties @NacosProperties} + * + * @param nacosProperties {@link NacosProperties @NacosProperties} + * @return non-null + */ + public final Properties resolveProperties(NacosProperties nacosProperties) { + Properties globalNacosProperties = resolveGlobalNacosProperties(); + return NacosUtils.resolveProperties(nacosProperties, environment, + globalNacosProperties); + } + + /** + * Resolve Nacos {@link Properties} from {@link NacosProperties @NacosProperties} + * + * @param nacosPropertiesAttributes {@link NacosProperties Nacos Properties}'s + * attributes + * @return non-null + */ + public final Properties resolveProperties( + Map nacosPropertiesAttributes) { + Properties globalNacosProperties = resolveGlobalNacosProperties(); + return NacosUtils.resolveProperties(nacosPropertiesAttributes, environment, + globalNacosProperties); + } + + private Properties resolveGlobalNacosProperties() { + return source.getMergedGlobalProperties(beanFactory); + } + + final Class getType() { + return type; + } + + @Override + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessor.java index 9795063d..504c8b1b 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessor.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessor.java @@ -16,113 +16,123 @@ */ package com.alibaba.nacos.spring.beans.factory.annotation; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.spring.beans.factory.annotation.AnnotationInjectedBeanPostProcessor; import com.alibaba.spring.util.BeanUtils; + import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - import static java.lang.String.format; import static java.util.Collections.unmodifiableMap; /** - * {@link AnnotationInjectedBeanPostProcessor} implementation is used to - * inject {@link ConfigService} or {@link NamingService} instance into a Spring Bean If it's attributes or properties annotated - * {@link NacosInjected @NacosInjected}. + * {@link AnnotationInjectedBeanPostProcessor} implementation is used to inject + * {@link ConfigService} or {@link NamingService} instance into a Spring Bean If it's + * attributes or properties annotated {@link NacosInjected @NacosInjected}. * * @author Mercy * @since 0.1.0 */ -public class AnnotationNacosInjectedBeanPostProcessor extends AnnotationInjectedBeanPostProcessor - implements InitializingBean { +public class AnnotationNacosInjectedBeanPostProcessor extends + AnnotationInjectedBeanPostProcessor implements InitializingBean { - /** - * The name of {@link AnnotationNacosInjectedBeanPostProcessor} - */ - public static final String BEAN_NAME = "annotationNacosInjectedBeanPostProcessor"; + /** + * The name of {@link AnnotationNacosInjectedBeanPostProcessor} + */ + public static final String BEAN_NAME = "annotationNacosInjectedBeanPostProcessor"; - private Map, AbstractNacosServiceBeanBuilder> nacosServiceBeanBuilderMap; + private Map, AbstractNacosServiceBeanBuilder> nacosServiceBeanBuilderMap; - @Override - public final void afterPropertiesSet() { - // Get beanFactory from super - ConfigurableListableBeanFactory beanFactory = getBeanFactory(); + @Override + public final void afterPropertiesSet() { + // Get beanFactory from super + ConfigurableListableBeanFactory beanFactory = getBeanFactory(); - initNacosServiceBeanBuilderMap(beanFactory); - } + initNacosServiceBeanBuilderMap(beanFactory); + } - private void initNacosServiceBeanBuilderMap(ConfigurableListableBeanFactory beanFactory) { + private void initNacosServiceBeanBuilderMap( + ConfigurableListableBeanFactory beanFactory) { - Class builderClass = AbstractNacosServiceBeanBuilder.class; + Class builderClass = AbstractNacosServiceBeanBuilder.class; - String[] beanNames = BeanUtils.getBeanNames(beanFactory, builderClass); - if (beanNames.length == 0) { - throw new NoSuchBeanDefinitionException(builderClass, - format("Please check the BeanDefinition of %s in Spring BeanFactory", builderClass)); - } + String[] beanNames = BeanUtils.getBeanNames(beanFactory, builderClass); + if (beanNames.length == 0) { + throw new NoSuchBeanDefinitionException(builderClass, + format("Please check the BeanDefinition of %s in Spring BeanFactory", + builderClass)); + } - Collection serviceBeanBuilders - = new ArrayList(beanNames.length); - for (String beanName : beanNames) { - serviceBeanBuilders.add(beanFactory.getBean(beanName, builderClass)); - } + Collection serviceBeanBuilders = new ArrayList( + beanNames.length); + for (String beanName : beanNames) { + serviceBeanBuilders.add(beanFactory.getBean(beanName, builderClass)); + } - if (serviceBeanBuilders.isEmpty()) { - throw new NoSuchBeanDefinitionException(builderClass, - format("Please check the BeanDefinition of %s in Spring BeanFactory", builderClass)); - } + if (serviceBeanBuilders.isEmpty()) { + throw new NoSuchBeanDefinitionException(builderClass, + format("Please check the BeanDefinition of %s in Spring BeanFactory", + builderClass)); + } - Map, AbstractNacosServiceBeanBuilder> builderMap = - new HashMap, AbstractNacosServiceBeanBuilder>(serviceBeanBuilders.size()); + Map, AbstractNacosServiceBeanBuilder> builderMap = new HashMap, AbstractNacosServiceBeanBuilder>( + serviceBeanBuilders.size()); - for (AbstractNacosServiceBeanBuilder serviceBeanBuilder : serviceBeanBuilders) { - Class type = serviceBeanBuilder.getType(); - builderMap.put(type, serviceBeanBuilder); - } + for (AbstractNacosServiceBeanBuilder serviceBeanBuilder : serviceBeanBuilders) { + Class type = serviceBeanBuilder.getType(); + builderMap.put(type, serviceBeanBuilder); + } - // Should not be modified in future - this.nacosServiceBeanBuilderMap = unmodifiableMap(builderMap); - } + // Should not be modified in future + this.nacosServiceBeanBuilderMap = unmodifiableMap(builderMap); + } - @Override - protected Object doGetInjectedBean(NacosInjected annotation, Object bean, String beanName, Class injectedType, - InjectionMetadata.InjectedElement injectedElement) { + @Override + protected Object doGetInjectedBean(NacosInjected annotation, Object bean, + String beanName, Class injectedType, + InjectionMetadata.InjectedElement injectedElement) { - AbstractNacosServiceBeanBuilder serviceBeanBuilder = nacosServiceBeanBuilderMap.get(injectedType); + AbstractNacosServiceBeanBuilder serviceBeanBuilder = nacosServiceBeanBuilderMap + .get(injectedType); - return serviceBeanBuilder.build(annotation.properties()); + return serviceBeanBuilder.build(annotation.properties()); - } + } - @Override - protected String buildInjectedObjectCacheKey(NacosInjected annotation, Object bean, String beanName, - Class injectedType, InjectionMetadata.InjectedElement injectedElement) { + @Override + protected String buildInjectedObjectCacheKey(NacosInjected annotation, Object bean, + String beanName, Class injectedType, + InjectionMetadata.InjectedElement injectedElement) { - StringBuilder keyBuilder = new StringBuilder(injectedType.getSimpleName()); + StringBuilder keyBuilder = new StringBuilder(injectedType.getSimpleName()); - AbstractNacosServiceBeanBuilder serviceBeanBuilder = nacosServiceBeanBuilderMap.get(injectedType); + AbstractNacosServiceBeanBuilder serviceBeanBuilder = nacosServiceBeanBuilderMap + .get(injectedType); - if (serviceBeanBuilder == null) { - throw new UnsupportedOperationException( - format("Only support to inject types[%s] instance , however actual injected type [%s] in member[%s]", - nacosServiceBeanBuilderMap.keySet(), injectedType, injectedElement.getMember())); - } + if (serviceBeanBuilder == null) { + throw new UnsupportedOperationException(format( + "Only support to inject types[%s] instance , however actual injected type [%s] in member[%s]", + nacosServiceBeanBuilderMap.keySet(), injectedType, + injectedElement.getMember())); + } - Properties properties = serviceBeanBuilder.resolveProperties(annotation.properties()); + Properties properties = serviceBeanBuilder + .resolveProperties(annotation.properties()); - keyBuilder.append(properties); + keyBuilder.append(properties); - return keyBuilder.toString(); + return keyBuilder.toString(); - } + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/ConfigServiceBeanBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/ConfigServiceBeanBuilder.java index 0f25c1c0..4ec025dd 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/ConfigServiceBeanBuilder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/ConfigServiceBeanBuilder.java @@ -16,33 +16,34 @@ */ package com.alibaba.nacos.spring.beans.factory.annotation; +import java.util.Properties; + import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource; -import java.util.Properties; - /** * {@link ConfigService} Bean Builder * * @author Mercy * @since 0.1.0 */ -public class ConfigServiceBeanBuilder extends AbstractNacosServiceBeanBuilder { +public class ConfigServiceBeanBuilder + extends AbstractNacosServiceBeanBuilder { - /** - * The bean name of {@link ConfigServiceBeanBuilder} - */ - public static final String BEAN_NAME = "configServiceBeanBuilder"; + /** + * The bean name of {@link ConfigServiceBeanBuilder} + */ + public static final String BEAN_NAME = "configServiceBeanBuilder"; - protected ConfigServiceBeanBuilder() { - super(GlobalNacosPropertiesSource.CONFIG); - } + protected ConfigServiceBeanBuilder() { + super(GlobalNacosPropertiesSource.CONFIG); + } - @Override - protected ConfigService createService(NacosServiceFactory nacosServiceFactory, Properties properties) - throws NacosException { - return nacosServiceFactory.createConfigService(properties); - } + @Override + protected ConfigService createService(NacosServiceFactory nacosServiceFactory, + Properties properties) throws NacosException { + return nacosServiceFactory.createConfigService(properties); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingMaintainServiceBeanBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingMaintainServiceBeanBuilder.java index 5bd68412..7efe22a0 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingMaintainServiceBeanBuilder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingMaintainServiceBeanBuilder.java @@ -16,31 +16,32 @@ */ package com.alibaba.nacos.spring.beans.factory.annotation; +import java.util.Properties; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource; -import java.util.Properties; - /** * @author liaochuntao * @since */ -public class NamingMaintainServiceBeanBuilder extends AbstractNacosServiceBeanBuilder { +public class NamingMaintainServiceBeanBuilder + extends AbstractNacosServiceBeanBuilder { - /** - * The bean name of {@link NamingServiceBeanBuilder} - */ - public static final String BEAN_NAME = "namingMaintainServiceBeanBuilder"; + /** + * The bean name of {@link NamingServiceBeanBuilder} + */ + public static final String BEAN_NAME = "namingMaintainServiceBeanBuilder"; - public NamingMaintainServiceBeanBuilder() { - super(GlobalNacosPropertiesSource.MAINTAIN); - } + public NamingMaintainServiceBeanBuilder() { + super(GlobalNacosPropertiesSource.MAINTAIN); + } - @Override - protected NamingMaintainService createService(NacosServiceFactory nacosServiceFactory, Properties properties) - throws NacosException { - return nacosServiceFactory.createNamingMaintainService(properties); - } + @Override + protected NamingMaintainService createService(NacosServiceFactory nacosServiceFactory, + Properties properties) throws NacosException { + return nacosServiceFactory.createNamingMaintainService(properties); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingServiceBeanBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingServiceBeanBuilder.java index 4027f683..b2d2da2c 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingServiceBeanBuilder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/beans/factory/annotation/NamingServiceBeanBuilder.java @@ -16,33 +16,34 @@ */ package com.alibaba.nacos.spring.beans.factory.annotation; +import java.util.Properties; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource; -import java.util.Properties; - /** * {@link NamingService} Bean Builder * * @author Mercy * @since 0.1.0 */ -public class NamingServiceBeanBuilder extends AbstractNacosServiceBeanBuilder { +public class NamingServiceBeanBuilder + extends AbstractNacosServiceBeanBuilder { - /** - * The bean name of {@link NamingServiceBeanBuilder} - */ - public static final String BEAN_NAME = "namingServiceBeanBuilder"; + /** + * The bean name of {@link NamingServiceBeanBuilder} + */ + public static final String BEAN_NAME = "namingServiceBeanBuilder"; - public NamingServiceBeanBuilder() { - super(GlobalNacosPropertiesSource.DISCOVERY); - } + public NamingServiceBeanBuilder() { + super(GlobalNacosPropertiesSource.DISCOVERY); + } - @Override - protected NamingService createService(NacosServiceFactory nacosServiceFactory, Properties properties) - throws NacosException { - return nacosServiceFactory.createNamingService(properties); - } + @Override + protected NamingService createService(NacosServiceFactory nacosServiceFactory, + Properties properties) throws NacosException { + return nacosServiceFactory.createNamingService(properties); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/EnableNacos.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/EnableNacos.java index 9cbdd3a6..97dbe6e0 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/EnableNacos.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/EnableNacos.java @@ -16,13 +16,18 @@ */ package com.alibaba.nacos.spring.context.annotation; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; -import org.springframework.context.annotation.Import; -import java.lang.annotation.*; +import org.springframework.context.annotation.Import; /** * Annotation for enabling Nacos features. @@ -31,19 +36,19 @@ * @see NacosBeanDefinitionRegistrar * @since 0.1.0 */ -@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(NacosBeanDefinitionRegistrar.class) public @interface EnableNacos { - /** - * Global {@link NacosProperties Nacos Properties} - * - * @return required - * @see NacosInjected#properties() - * @see NacosConfigListener#properties() - * @see NacosConfigurationProperties#properties() - */ - NacosProperties globalProperties(); + /** + * Global {@link NacosProperties Nacos Properties} + * + * @return required + * @see NacosInjected#properties() + * @see NacosConfigListener#properties() + * @see NacosConfigurationProperties#properties() + */ + NacosProperties globalProperties(); } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrar.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrar.java index 1365548a..481b08a0 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrar.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrar.java @@ -43,43 +43,50 @@ * @see EnableNacos * @since 0.1.0 */ -public class NacosBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware, BeanFactoryAware { +public class NacosBeanDefinitionRegistrar + implements ImportBeanDefinitionRegistrar, EnvironmentAware, BeanFactoryAware { - private Environment environment; + private Environment environment; - private BeanFactory beanFactory; + private BeanFactory beanFactory; - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition( - PropertySourcesPlaceholderConfigurer.class).getBeanDefinition(); - registry.registerBeanDefinition(PropertySourcesPlaceholderConfigurer.class.getName(), annotationProcessor); + @Override + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, + BeanDefinitionRegistry registry) { + BeanDefinition annotationProcessor = BeanDefinitionBuilder + .genericBeanDefinition(PropertySourcesPlaceholderConfigurer.class) + .getBeanDefinition(); + registry.registerBeanDefinition( + PropertySourcesPlaceholderConfigurer.class.getName(), + annotationProcessor); - AnnotationAttributes attributes = AnnotationAttributes.fromMap( - importingClassMetadata.getAnnotationAttributes(EnableNacos.class.getName())); + AnnotationAttributes attributes = AnnotationAttributes + .fromMap(importingClassMetadata + .getAnnotationAttributes(EnableNacos.class.getName())); - // Register Global Nacos Properties Bean - registerGlobalNacosProperties(attributes, registry, environment, GLOBAL_NACOS_PROPERTIES_BEAN_NAME); - // Register Nacos Annotation Beans - registerNacosAnnotationBeans(registry); - // Invoke NacosPropertySourcePostProcessor immediately - // in order to enhance the precedence of @NacosPropertySource process - invokeNacosPropertySourcePostProcessor(beanFactory); - } + // Register Global Nacos Properties Bean + registerGlobalNacosProperties(attributes, registry, environment, + GLOBAL_NACOS_PROPERTIES_BEAN_NAME); + // Register Nacos Annotation Beans + registerNacosAnnotationBeans(registry); + // Invoke NacosPropertySourcePostProcessor immediately + // in order to enhance the precedence of @NacosPropertySource process + invokeNacosPropertySourcePostProcessor(beanFactory); + } - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + } - public void registerNacosAnnotationBeans(BeanDefinitionRegistry registry) { - registerNacosCommonBeans(registry); - registerNacosConfigBeans(registry, environment); - registerNacosDiscoveryBeans(registry); - } + public void registerNacosAnnotationBeans(BeanDefinitionRegistry registry) { + registerNacosCommonBeans(registry); + registerNacosConfigBeans(registry, environment, beanFactory); + registerNacosDiscoveryBeans(registry); + } - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfig.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfig.java index c7b73b02..8183d1b4 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfig.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfig.java @@ -16,16 +16,29 @@ */ 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; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; 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.PREFIX; +import static com.alibaba.nacos.api.annotation.NacosProperties.SECRET_KEY; +import static com.alibaba.nacos.api.annotation.NacosProperties.SERVER_ADDR; /** * Annotation for enabling Nacos Config features. @@ -34,109 +47,111 @@ * @see NacosBeanDefinitionRegistrar * @since 0.1.0 */ -@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(NacosConfigBeanDefinitionRegistrar.class) public @interface EnableNacosConfig { - /** - * The prefix of property name of Nacos Config - */ - String CONFIG_PREFIX = NacosProperties.PREFIX + "config."; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.endpoint:${nacos.endpoint:}}" - */ - String ENDPOINT_PLACEHOLDER = "${" + CONFIG_PREFIX + ENDPOINT + ":" + NacosProperties.ENDPOINT_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.namespace:${nacos.namespace:}}" - */ - String NAMESPACE_PLACEHOLDER = "${" + CONFIG_PREFIX + NAMESPACE + ":" + NacosProperties.NAMESPACE_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.access-key:${nacos.access-key:}}" - */ - String ACCESS_KEY_PLACEHOLDER = "${" + CONFIG_PREFIX + ACCESS_KEY + ":" + NacosProperties.ACCESS_KEY_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.secret-key:${nacos.secret-key:}}" - */ - String SECRET_KEY_PLACEHOLDER = "${" + CONFIG_PREFIX + SECRET_KEY + ":" + NacosProperties.SECRET_KEY_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.server-addr:${nacos.server-addr:}}" - */ - String SERVER_ADDR_PLACEHOLDER = "${" + CONFIG_PREFIX + SERVER_ADDR + ":" + NacosProperties.SERVER_ADDR_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.context-path:${nacos.context-path:}}" - */ - String CONTEXT_PATH_PLACEHOLDER = "${" + CONFIG_PREFIX + CONTEXT_PATH + ":" + NacosProperties.CONTEXT_PATH_PLACEHOLDER + "}"; - - /** - * The placeholder of endpoint, the value is - * "${nacos.config.cluster-name:${nacos.cluster-name:}}" - */ - String CLUSTER_NAME_PLACEHOLDER = "${" + CONFIG_PREFIX + CLUSTER_NAME + ":" + NacosProperties.CLUSTER_NAME_PLACEHOLDER + "}"; - - /** - * The placeholder of {@link NacosProperties#ENCODE encode}, the value is - * "${nacos.config.encode:${nacos.encode:UTF-8}}" - */ - String ENCODE_PLACEHOLDER = "${" + CONFIG_PREFIX + ENCODE + ":" + NacosProperties.ENCODE_PLACEHOLDER + "}"; - - /** - * The placeholder of {@link NacosProperties#CONFIG_LONG_POLL_TIMEOUT configLongPollTimeout}, - * the value is "${nacos.configLongPollTimeout:}" - */ - String CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + NacosProperties.CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER + "}"; - - /** - * The placeholder of {@link NacosProperties#CONFIG_RETRY_TIME configRetryTime}, - * the value is "${nacos.configRetryTime:}" - */ - String CONFIG_RETRY_TIME_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + NacosProperties.CONFIG_RETRY_TIME_PLACEHOLDER + "}"; - - /** - * The placeholder of {@link NacosProperties#MAX_RETRY maxRetry}, the value is "${nacos.maxRetry:}" - */ - String MAX_RETRY_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + NacosProperties.MAX_RETRY_PLACEHOLDER + "}"; - - /** - * The placeholder of {@link NacosProperties#ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER enableRemoteSyncConfig} - * the value is "${nacos.enableRemoteSyncConfig:}" - */ -// String ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER = "${" + CONFIG_PREFIX + ENCODE + ":" + NacosProperties.ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER + "}"; - - /** - * Global {@link NacosProperties Nacos Properties} - * - * @return required - * @see NacosInjected#properties() - * @see NacosConfigListener#properties() - * @see NacosConfigurationProperties#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, - configLongPollTimeout = CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER, - configRetryTime = CONFIG_RETRY_TIME_PLACEHOLDER, - maxRetry = MAX_RETRY_PLACEHOLDER -// enableRemoteSyncConfig = ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER - ); + /** + * The prefix of property name of Nacos Config + */ + String CONFIG_PREFIX = NacosProperties.PREFIX + "config."; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.endpoint:${nacos.endpoint:}}" + */ + String ENDPOINT_PLACEHOLDER = "${" + CONFIG_PREFIX + ENDPOINT + ":" + + NacosProperties.ENDPOINT_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.namespace:${nacos.namespace:}}" + */ + String NAMESPACE_PLACEHOLDER = "${" + CONFIG_PREFIX + NAMESPACE + ":" + + NacosProperties.NAMESPACE_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.access-key:${nacos.access-key:}}" + */ + String ACCESS_KEY_PLACEHOLDER = "${" + CONFIG_PREFIX + ACCESS_KEY + ":" + + NacosProperties.ACCESS_KEY_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.secret-key:${nacos.secret-key:}}" + */ + String SECRET_KEY_PLACEHOLDER = "${" + CONFIG_PREFIX + SECRET_KEY + ":" + + NacosProperties.SECRET_KEY_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.server-addr:${nacos.server-addr:}}" + */ + String SERVER_ADDR_PLACEHOLDER = "${" + CONFIG_PREFIX + SERVER_ADDR + ":" + + NacosProperties.SERVER_ADDR_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.context-path:${nacos.context-path:}}" + */ + String CONTEXT_PATH_PLACEHOLDER = "${" + CONFIG_PREFIX + CONTEXT_PATH + ":" + + NacosProperties.CONTEXT_PATH_PLACEHOLDER + "}"; + + /** + * The placeholder of endpoint, the value is + * "${nacos.config.cluster-name:${nacos.cluster-name:}}" + */ + String CLUSTER_NAME_PLACEHOLDER = "${" + CONFIG_PREFIX + CLUSTER_NAME + ":" + + NacosProperties.CLUSTER_NAME_PLACEHOLDER + "}"; + + /** + * The placeholder of {@link NacosProperties#ENCODE encode}, the value is + * "${nacos.config.encode:${nacos.encode:UTF-8}}" + */ + String ENCODE_PLACEHOLDER = "${" + CONFIG_PREFIX + ENCODE + ":" + + NacosProperties.ENCODE_PLACEHOLDER + "}"; + + /** + * The placeholder of {@link NacosProperties#CONFIG_LONG_POLL_TIMEOUT + * configLongPollTimeout}, the value is "${nacos.configLongPollTimeout:}" + */ + String CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + + NacosProperties.CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER + "}"; + + /** + * The placeholder of {@link NacosProperties#CONFIG_RETRY_TIME configRetryTime}, the + * value is "${nacos.configRetryTime:}" + */ + String CONFIG_RETRY_TIME_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + + NacosProperties.CONFIG_RETRY_TIME_PLACEHOLDER + "}"; + + /** + * The placeholder of {@link NacosProperties#MAX_RETRY maxRetry}, the value is + * "${nacos.maxRetry:}" + */ + String MAX_RETRY_PLACEHOLDER = "${" + CONFIG_PREFIX + PREFIX + + NacosProperties.MAX_RETRY_PLACEHOLDER + "}"; + + /** + * The placeholder of {@link NacosProperties#ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER + * enableRemoteSyncConfig} the value is + * "${nacos.enableRemoteSyncConfig:}" + */ + // String ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER = "${" + CONFIG_PREFIX + ENCODE + ":" + // + NacosProperties.ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER + "}"; + + /** + * Global {@link NacosProperties Nacos Properties} + * + * @return required + * @see NacosInjected#properties() + * @see NacosConfigListener#properties() + * @see NacosConfigurationProperties#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, configLongPollTimeout = CONFIG_LONG_POLL_TIMEOUT_PLACEHOLDER, configRetryTime = CONFIG_RETRY_TIME_PLACEHOLDER, maxRetry = MAX_RETRY_PLACEHOLDER + // enableRemoteSyncConfig = ENABLE_REMOTE_SYNC_CONFIG_PLACEHOLDER + ); } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrar.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrar.java index 92d68533..55b267e3 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrar.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrar.java @@ -41,39 +41,45 @@ * * @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) + * @see NacosBeanUtils#registerNacosConfigBeans(BeanDefinitionRegistry, + * Environment,BeanFactory) * @since 0.1.0 */ -public class NacosConfigBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware, - BeanFactoryAware { +public class NacosConfigBeanDefinitionRegistrar + implements ImportBeanDefinitionRegistrar, EnvironmentAware, BeanFactoryAware { - private Environment environment; + private Environment environment; - private BeanFactory beanFactory; + private BeanFactory beanFactory; - @Override - public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { - AnnotationAttributes attributes = fromMap(metadata.getAnnotationAttributes(EnableNacosConfig.class.getName())); - // Register Global Nacos Properties Bean - registerGlobalNacosProperties(attributes, registry, environment, CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME); - // Register Nacos Common Beans - registerNacosCommonBeans(registry); - // Register Nacos Config Beans - registerNacosConfigBeans(registry, environment); - // Invoke NacosPropertySourcePostProcessor immediately - // in order to enhance the precedence of @NacosPropertySource process - invokeNacosPropertySourcePostProcessor(beanFactory); - } + @Override + public void registerBeanDefinitions(AnnotationMetadata metadata, + BeanDefinitionRegistry registry) { + AnnotationAttributes attributes = fromMap( + metadata.getAnnotationAttributes(EnableNacosConfig.class.getName())); + // Register Global Nacos Properties Bean + registerGlobalNacosProperties(attributes, registry, environment, + CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME); + // Register Nacos Common Beans + registerNacosCommonBeans(registry); + // Register Nacos Config Beans + registerNacosConfigBeans(registry, environment, beanFactory); + // Invoke NacosPropertySourcePostProcessor immediately + // in order to enhance the precedence of @NacosPropertySource process - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } + invokeNacosPropertySourcePostProcessor(beanFactory); + } - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } + @Override + public void setEnvironment(Environment environment) { + this.environment = environment; + } + + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessor.java index d15744d9..016b9b05 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessor.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessor.java @@ -16,6 +16,10 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.lang.reflect.Method; +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.annotation.NacosConfigListener; @@ -28,9 +32,14 @@ import com.alibaba.nacos.spring.convert.converter.config.DefaultNacosConfigConverter; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.NacosUtils; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; -import org.springframework.context.*; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.EnvironmentAware; import org.springframework.core.convert.ConversionService; import org.springframework.core.env.Environment; import org.springframework.format.support.DefaultFormattingConversionService; @@ -38,10 +47,6 @@ import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.Properties; - import static com.alibaba.nacos.spring.util.GlobalNacosPropertiesSource.CONFIG; import static com.alibaba.nacos.spring.util.NacosBeanUtils.getConfigServiceBeanBuilder; import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosServiceFactoryBean; @@ -57,183 +62,208 @@ * @see Method * @since 0.1.0 */ -public class NacosConfigListenerMethodProcessor extends AnnotationListenerMethodProcessor - implements ApplicationContextAware, ApplicationEventPublisherAware, EnvironmentAware { - - /** - * The bean name of {@link NacosConfigListenerMethodProcessor} - */ - public static final String BEAN_NAME = "nacosConfigListenerMethodProcessor"; - - /** - * The bean name of {@link ConversionService} for Nacos Configuration - */ - public static final String NACOS_CONFIG_CONVERSION_SERVICE_BEAN_NAME = "nacosConfigConversionService"; - - private Properties globalNacosProperties; - - private NacosServiceFactory nacosServiceFactory; - - private ConversionService conversionService; - - private ConfigServiceBeanBuilder configServiceBeanBuilder; - - 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); - } - - publishMetadataEvent(beanName, bean, beanClass, dataId, groupId, listener, method); - - } - - 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); - - // 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; +public class NacosConfigListenerMethodProcessor + extends AnnotationListenerMethodProcessor 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 - *

- * - * @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> annotationAttributesList = new LinkedList>(); - - for (String annotationType : annotationTypes) { - annotationAttributesList.addAll(getAnnotationAttributesList(metadata, annotationType)); - } - - return annotationAttributesList.toArray(new Map[0]); - } - - private List> getAnnotationAttributesList(AnnotationMetadata metadata, String annotationType) { - - List> annotationAttributesList = new LinkedList>(); - - if (NacosPropertySources.class.getName().equals(annotationType)) { - Map annotationAttributes = metadata.getAnnotationAttributes(annotationType); - if (annotationAttributes != null) { - annotationAttributesList.addAll(Arrays.asList((Map[]) annotationAttributes.get("value"))); - } - } else if (com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.class.getName().equals(annotationType)) { - annotationAttributesList.add(metadata.getAnnotationAttributes(annotationType)); - } - return annotationAttributesList; - } - - @Override - protected void initNacosPropertySource(NacosPropertySource nacosPropertySource, AnnotatedBeanDefinition beanDefinition, - Map annotationAttributes) { - // AttributesMetadata - initAttributesMetadata(nacosPropertySource, annotationAttributes); - // Auto-Refreshed - initAutoRefreshed(nacosPropertySource, annotationAttributes); - // Origin - initOrigin(nacosPropertySource, beanDefinition); - // Order - initOrder(nacosPropertySource, annotationAttributes); - - } - - private void initAttributesMetadata(NacosPropertySource nacosPropertySource, Map annotationAttributes) { - nacosPropertySource.setAttributesMetadata(annotationAttributes); - } - - private void initAutoRefreshed(NacosPropertySource nacosPropertySource, Map annotationAttributes) { - boolean autoRefreshed = Boolean.TRUE.equals(annotationAttributes.get(AUTO_REFRESHED_ATTRIBUTE_NAME)); - nacosPropertySource.setAutoRefreshed(autoRefreshed); - } - - private void initOrigin(NacosPropertySource nacosPropertySource, AnnotatedBeanDefinition beanDefinition) { - AnnotationMetadata metadata = beanDefinition.getMetadata(); - nacosPropertySource.setOrigin(metadata.getClassName()); - } - - private void initOrder(NacosPropertySource nacosPropertySource, Map annotationAttributes) { - boolean first = Boolean.TRUE.equals(annotationAttributes.get(FIRST_ATTRIBUTE_NAME)); - String before = (String) annotationAttributes.get(BEFORE_ATTRIBUTE_NAME); - String after = (String) annotationAttributes.get(AFTER_ATTRIBUTE_NAME); - nacosPropertySource.setFirst(first); - nacosPropertySource.setBefore(before); - nacosPropertySource.setAfter(after); - } - - @Override - protected NacosConfigMetadataEvent createMetaEvent(NacosPropertySource nacosPropertySource, - AnnotatedBeanDefinition beanDefinition) { - return new NacosConfigMetadataEvent(beanDefinition.getMetadata()); - } - - @Override - protected void doInitMetadataEvent(NacosPropertySource nacosPropertySource, AnnotatedBeanDefinition beanDefinition, - NacosConfigMetadataEvent metadataEvent) { - metadataEvent.setAnnotatedElement(metadataEvent.getAnnotatedElement()); - } +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> annotationAttributesList = new LinkedList>(); + + for (String annotationType : annotationTypes) { + annotationAttributesList + .addAll(getAnnotationAttributesList(metadata, annotationType)); + } + + return annotationAttributesList.toArray(new Map[0]); + } + + private List> getAnnotationAttributesList( + AnnotationMetadata metadata, String annotationType) { + + List> annotationAttributesList = new LinkedList>(); + + if (NacosPropertySources.class.getName().equals(annotationType)) { + Map annotationAttributes = metadata + .getAnnotationAttributes(annotationType); + if (annotationAttributes != null) { + annotationAttributesList.addAll(Arrays.asList( + (Map[]) annotationAttributes.get("value"))); + } + } + else if (com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource.class + .getName().equals(annotationType)) { + annotationAttributesList + .add(metadata.getAnnotationAttributes(annotationType)); + } + return annotationAttributesList; + } + + @Override + protected void initNacosPropertySource(NacosPropertySource nacosPropertySource, + AnnotatedBeanDefinition beanDefinition, + Map annotationAttributes) { + // AttributesMetadata + initAttributesMetadata(nacosPropertySource, annotationAttributes); + // Auto-Refreshed + initAutoRefreshed(nacosPropertySource, annotationAttributes); + // Origin + initOrigin(nacosPropertySource, beanDefinition); + // Order + initOrder(nacosPropertySource, annotationAttributes); + + } + + private void initAttributesMetadata(NacosPropertySource nacosPropertySource, + Map annotationAttributes) { + nacosPropertySource.setAttributesMetadata(annotationAttributes); + } + + private void initAutoRefreshed(NacosPropertySource nacosPropertySource, + Map annotationAttributes) { + boolean autoRefreshed = Boolean.TRUE + .equals(annotationAttributes.get(AUTO_REFRESHED_ATTRIBUTE_NAME)); + nacosPropertySource.setAutoRefreshed(autoRefreshed); + } + + private void initOrigin(NacosPropertySource nacosPropertySource, + AnnotatedBeanDefinition beanDefinition) { + AnnotationMetadata metadata = beanDefinition.getMetadata(); + nacosPropertySource.setOrigin(metadata.getClassName()); + } + + private void initOrder(NacosPropertySource nacosPropertySource, + Map annotationAttributes) { + boolean first = Boolean.TRUE + .equals(annotationAttributes.get(FIRST_ATTRIBUTE_NAME)); + String before = (String) annotationAttributes.get(BEFORE_ATTRIBUTE_NAME); + String after = (String) annotationAttributes.get(AFTER_ATTRIBUTE_NAME); + nacosPropertySource.setFirst(first); + nacosPropertySource.setBefore(before); + nacosPropertySource.setAfter(after); + } + + @Override + protected NacosConfigMetadataEvent createMetaEvent( + NacosPropertySource nacosPropertySource, + AnnotatedBeanDefinition beanDefinition) { + return new NacosConfigMetadataEvent(beanDefinition.getMetadata()); + } + + @Override + protected void doInitMetadataEvent(NacosPropertySource nacosPropertySource, + AnnotatedBeanDefinition beanDefinition, + NacosConfigMetadataEvent metadataEvent) { + metadataEvent.setAnnotatedElement(metadataEvent.getAnnotatedElement()); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySource.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySource.java index 108d2ac8..483760f1 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySource.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySource.java @@ -16,13 +16,13 @@ */ package com.alibaba.nacos.spring.core.env; -import org.springframework.core.env.PropertiesPropertySource; -import org.springframework.core.env.PropertySource; - import java.util.Collections; import java.util.Map; import java.util.Properties; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.env.PropertySource; + import static com.alibaba.nacos.spring.util.NacosUtils.toProperties; /** @@ -34,163 +34,165 @@ */ public class NacosPropertySource extends PropertiesPropertySource { - private String groupId; + private String groupId; - private String dataId; + private String dataId; - private boolean autoRefreshed; + private boolean autoRefreshed; - private boolean first; + private boolean first; - private String before; + private String before; - private String after; + private String after; - private String type; + private String type; - private Properties properties; + private Properties properties; - private Map attributesMetadata; + private Map attributesMetadata; - private Object origin; + private Object origin; - private String beanName; + private String beanName; - private Class beanType; + private Class beanType; - /** - * @param name the name of Nacos {@link PropertySource} - * @param nacosConfig the Nacos Config with {@link Properties} format - */ - public NacosPropertySource(String dataId, String groupId, String name, String nacosConfig, String type) { - super(name, toProperties(dataId, groupId, nacosConfig, type)); - this.type = type; - } + /** + * @param name the name of Nacos {@link PropertySource} + * @param nacosConfig the Nacos Config with {@link Properties} format + */ + public NacosPropertySource(String dataId, String groupId, String name, + String nacosConfig, String type) { + super(name, toProperties(dataId, groupId, nacosConfig, type)); + this.type = type; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getDataId() { - return dataId; - } + public String getDataId() { + return dataId; + } - public void setDataId(String dataId) { - this.dataId = dataId; - } + public void setDataId(String dataId) { + this.dataId = dataId; + } - public boolean isAutoRefreshed() { - return autoRefreshed; - } + public boolean isAutoRefreshed() { + return autoRefreshed; + } - public void setAutoRefreshed(boolean autoRefreshed) { - this.autoRefreshed = autoRefreshed; - } - - public boolean isFirst() { - return first; - } - - public void setFirst(boolean first) { - this.first = first; - } - - public String getBefore() { - return before; - } - - public void setBefore(String before) { - this.before = before; - } - - public String getAfter() { - return after; - } - - public void setAfter(String after) { - this.after = after; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Properties getProperties() { - return properties; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - /** - * @param attributesMetadata the attributesMetadata of attributes from - * {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} - * or <nacos:property-source ... > - */ - public void setAttributesMetadata(Map attributesMetadata) { - this.attributesMetadata = attributesMetadata; - } - - /** - * @param origin where Nacos {@link PropertySource} comes from - */ - public void setOrigin(Object origin) { - this.origin = origin; - } - - /** - * @return the attributesMetadata of attributes from - * {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} - * or <nacos:property-source ... > - */ - public Map getAttributesMetadata() { - return attributesMetadata != null ? attributesMetadata : Collections.emptyMap(); - } - - /** - * @return where Nacos {@link PropertySource} comes from - */ - public Object getOrigin() { - return origin; - } - - public String getBeanName() { - return beanName; - } - - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public Class getBeanType() { - return beanType; - } - - public void setBeanType(Class beanType) { - this.beanType = beanType; - } - - protected void copy(NacosPropertySource original) { - this.groupId = original.groupId; - this.dataId = original.dataId; - this.autoRefreshed = original.autoRefreshed; - this.first = original.first; - this.before = original.before; - this.after = original.after; - this.type = original.type; - this.properties = original.properties; - this.attributesMetadata = original.attributesMetadata; - this.origin = original.origin; - this.beanName = original.beanName; - this.beanType = original.beanType; - } + public void setAutoRefreshed(boolean autoRefreshed) { + this.autoRefreshed = autoRefreshed; + } + + public boolean isFirst() { + return first; + } + + public void setFirst(boolean first) { + this.first = first; + } + + public String getBefore() { + return before; + } + + public void setBefore(String before) { + this.before = before; + } + + public String getAfter() { + return after; + } + + public void setAfter(String after) { + this.after = after; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + + /** + * @param attributesMetadata the attributesMetadata of attributes from + * {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} + * or <nacos:property-source ... > + */ + public void setAttributesMetadata(Map attributesMetadata) { + this.attributesMetadata = attributesMetadata; + } + + /** + * @param origin where Nacos {@link PropertySource} comes from + */ + public void setOrigin(Object origin) { + this.origin = origin; + } + + /** + * @return the attributesMetadata of attributes from + * {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} + * or <nacos:property-source ... > + */ + public Map getAttributesMetadata() { + return attributesMetadata != null ? attributesMetadata + : Collections. emptyMap(); + } + + /** + * @return where Nacos {@link PropertySource} comes from + */ + public Object getOrigin() { + return origin; + } + + public String getBeanName() { + return beanName; + } + + public void setBeanName(String beanName) { + this.beanName = beanName; + } + + public Class getBeanType() { + return beanType; + } + + public void setBeanType(Class beanType) { + this.beanType = beanType; + } + + protected void copy(NacosPropertySource original) { + this.groupId = original.groupId; + this.dataId = original.dataId; + this.autoRefreshed = original.autoRefreshed; + this.first = original.first; + this.before = original.before; + this.after = original.after; + this.type = original.type; + this.properties = original.properties; + this.attributesMetadata = original.attributesMetadata; + this.origin = original.origin; + this.beanName = original.beanName; + this.beanType = original.beanType; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySourcePostProcessor.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySourcePostProcessor.java index 69f011c5..4f72c73c 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySourcePostProcessor.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/NacosPropertySourcePostProcessor.java @@ -16,6 +16,14 @@ */ package com.alibaba.nacos.spring.core.env; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.AbstractListener; import com.alibaba.nacos.api.config.listener.Listener; @@ -23,10 +31,10 @@ import com.alibaba.nacos.spring.beans.factory.annotation.ConfigServiceBeanBuilder; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySources; import com.alibaba.nacos.spring.context.config.xml.NacosPropertySourceXmlBeanDefinition; - import com.alibaba.nacos.spring.context.event.config.EventPublishingConfigService; import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.spring.util.BeanUtils; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; @@ -43,25 +51,17 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySources; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.getConfigServiceBeanBuilder; import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosServiceFactoryBean; import static com.alibaba.nacos.spring.util.NacosUtils.DEFAULT_STRING_ATTRIBUTE_VALUE; import static org.springframework.util.ObjectUtils.nullSafeEquals; /** - * {@link BeanFactoryPostProcessor Post Processor} resolves {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} or - * {@link NacosPropertySources @NacosPropertySources} or {@link NacosPropertySourceXmlBeanDefinition} - * to be {@link PropertySource}, and append into Spring - * {@link PropertySources} - * {@link } + * {@link BeanFactoryPostProcessor Post Processor} resolves + * {@link com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @NacosPropertySource} + * or {@link NacosPropertySources @NacosPropertySources} or + * {@link NacosPropertySourceXmlBeanDefinition} to be {@link PropertySource}, and append + * into Spring {@link PropertySources} {@link } * * @author Mercy * @see com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource @@ -71,164 +71,183 @@ * @see BeanDefinitionRegistryPostProcessor * @since 0.1.0 */ -public class NacosPropertySourcePostProcessor implements BeanDefinitionRegistryPostProcessor, BeanFactoryPostProcessor, - EnvironmentAware, Ordered { - - /** - * The bean name of {@link NacosPropertySourcePostProcessor} - */ - public static final String BEAN_NAME = "nacosPropertySourcePostProcessor"; - - private static BeanFactory beanFactory; - - private final Set processedBeanNames = new LinkedHashSet(); - - private ConfigurableEnvironment environment; - - private Collection nacosPropertySourceBuilders; - - private ConfigServiceBeanBuilder configServiceBeanBuilder; - - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - String[] abstractNacosPropertySourceBuilderBeanNames = BeanUtils.getBeanNames(beanFactory, - AbstractNacosPropertySourceBuilder.class); - - this.nacosPropertySourceBuilders = new ArrayList( - abstractNacosPropertySourceBuilderBeanNames.length); - - for (String beanName : abstractNacosPropertySourceBuilderBeanNames) { - this.nacosPropertySourceBuilders.add( - beanFactory.getBean(beanName, AbstractNacosPropertySourceBuilder.class)); - } - - NacosPropertySourcePostProcessor.beanFactory = beanFactory; - this.configServiceBeanBuilder = getConfigServiceBeanBuilder(beanFactory); - - String[] beanNames = beanFactory.getBeanDefinitionNames(); - - for (String beanName : beanNames) { - processPropertySource(beanName, beanFactory); - } - - } - - private void processPropertySource(String beanName, ConfigurableListableBeanFactory beanFactory) { - - if (processedBeanNames.contains(beanName)) { - return; - } - - BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); - - // Build multiple instance if possible - List nacosPropertySources = buildNacosPropertySources(beanName, beanDefinition); - - // Add Orderly - for (NacosPropertySource nacosPropertySource : nacosPropertySources) { - addNacosPropertySource(nacosPropertySource); - Properties properties = configServiceBeanBuilder.resolveProperties(nacosPropertySource.getAttributesMetadata()); - addListenerIfAutoRefreshed(nacosPropertySource, properties, environment); - } - - processedBeanNames.add(beanName); - } - - private List buildNacosPropertySources(String beanName, BeanDefinition beanDefinition) { - for (AbstractNacosPropertySourceBuilder builder : nacosPropertySourceBuilders) { - if (builder.supports(beanDefinition)) { - return builder.build(beanName, beanDefinition); - } - } - return Collections.emptyList(); - } +public class NacosPropertySourcePostProcessor + implements BeanDefinitionRegistryPostProcessor, BeanFactoryPostProcessor, + EnvironmentAware, Ordered { - private void addNacosPropertySource(NacosPropertySource nacosPropertySource) { + /** + * The bean name of {@link NacosPropertySourcePostProcessor} + */ + public static final String BEAN_NAME = "nacosPropertySourcePostProcessor"; - MutablePropertySources propertySources = environment.getPropertySources(); + private static BeanFactory beanFactory; - boolean first = nacosPropertySource.isFirst(); - String before = nacosPropertySource.getBefore(); - String after = nacosPropertySource.getAfter(); + private final Set processedBeanNames = new LinkedHashSet(); - boolean hasBefore = !nullSafeEquals(DEFAULT_STRING_ATTRIBUTE_VALUE, before); - boolean hasAfter = !nullSafeEquals(DEFAULT_STRING_ATTRIBUTE_VALUE, after); + private ConfigurableEnvironment environment; - boolean isRelative = hasBefore || hasAfter; + private Collection nacosPropertySourceBuilders; - if (first) { // If First - propertySources.addFirst(nacosPropertySource); - } else if (isRelative) { // If relative - if (hasBefore) { - propertySources.addBefore(before, nacosPropertySource); - } - if (hasAfter) { - propertySources.addAfter(after, nacosPropertySource); - } - } else { - propertySources.addLast(nacosPropertySource); // default add last - } - } + private ConfigServiceBeanBuilder configServiceBeanBuilder; - public static void addListenerIfAutoRefreshed(final NacosPropertySource nacosPropertySource, final Properties properties, final ConfigurableEnvironment environment) { + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) + throws BeansException { + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) + throws BeansException { + String[] abstractNacosPropertySourceBuilderBeanNames = BeanUtils + .getBeanNames(beanFactory, AbstractNacosPropertySourceBuilder.class); - if (!nacosPropertySource.isAutoRefreshed()) { // Disable Auto-Refreshed - return; - } + this.nacosPropertySourceBuilders = new ArrayList( + abstractNacosPropertySourceBuilderBeanNames.length); - final String dataId = nacosPropertySource.getDataId(); - final String groupId = nacosPropertySource.getGroupId(); - final String type = nacosPropertySource.getType(); - final NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory); + for (String beanName : abstractNacosPropertySourceBuilderBeanNames) { + this.nacosPropertySourceBuilders.add(beanFactory.getBean(beanName, + AbstractNacosPropertySourceBuilder.class)); + } - try { - - ConfigService configService = nacosServiceFactory.createConfigService(properties); - - Listener listener = new AbstractListener() { - - @Override - public void receiveConfigInfo(String config) { - String name = nacosPropertySource.getName(); - NacosPropertySource newNacosPropertySource = new NacosPropertySource(dataId, groupId, name, config, type); - newNacosPropertySource.copy(nacosPropertySource); - MutablePropertySources propertySources = environment.getPropertySources(); - // replace NacosPropertySource - propertySources.replace(name, newNacosPropertySource); - } - }; - - if (configService instanceof EventPublishingConfigService) { - ((EventPublishingConfigService) configService).addListener(dataId, groupId, type, listener); - } else { - configService.addListener(dataId, groupId, listener); - } - - } catch (NacosException e) { - throw new RuntimeException("ConfigService can't add Listener with properties : " + properties, e); - } - } - - - /** - * The order is closed to {@link ConfigurationClassPostProcessor#getOrder() HIGHEST_PRECEDENCE} almost. - * - * @return Ordered.HIGHEST_PRECEDENCE + 1 - * @see ConfigurationClassPostProcessor#getOrder() - */ - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE + 1; - } - - - @Override - public void setEnvironment(Environment environment) { - this.environment = (ConfigurableEnvironment) environment; - } + NacosPropertySourcePostProcessor.beanFactory = beanFactory; + this.configServiceBeanBuilder = getConfigServiceBeanBuilder(beanFactory); + + String[] beanNames = beanFactory.getBeanDefinitionNames(); + + for (String beanName : beanNames) { + processPropertySource(beanName, beanFactory); + } + + } + + private void processPropertySource(String beanName, + ConfigurableListableBeanFactory beanFactory) { + + if (processedBeanNames.contains(beanName)) { + return; + } + + BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); + + // Build multiple instance if possible + List nacosPropertySources = buildNacosPropertySources( + beanName, beanDefinition); + + // Add Orderly + for (NacosPropertySource nacosPropertySource : nacosPropertySources) { + addNacosPropertySource(nacosPropertySource); + Properties properties = configServiceBeanBuilder + .resolveProperties(nacosPropertySource.getAttributesMetadata()); + addListenerIfAutoRefreshed(nacosPropertySource, properties, environment); + } + + processedBeanNames.add(beanName); + } + + private List buildNacosPropertySources(String beanName, + BeanDefinition beanDefinition) { + for (AbstractNacosPropertySourceBuilder builder : nacosPropertySourceBuilders) { + if (builder.supports(beanDefinition)) { + return builder.build(beanName, beanDefinition); + } + } + return Collections.emptyList(); + } + + private void addNacosPropertySource(NacosPropertySource nacosPropertySource) { + + MutablePropertySources propertySources = environment.getPropertySources(); + + boolean first = nacosPropertySource.isFirst(); + String before = nacosPropertySource.getBefore(); + String after = nacosPropertySource.getAfter(); + + boolean hasBefore = !nullSafeEquals(DEFAULT_STRING_ATTRIBUTE_VALUE, before); + boolean hasAfter = !nullSafeEquals(DEFAULT_STRING_ATTRIBUTE_VALUE, after); + + boolean isRelative = hasBefore || hasAfter; + + if (first) { // If First + propertySources.addFirst(nacosPropertySource); + } + else if (isRelative) { // If relative + if (hasBefore) { + propertySources.addBefore(before, nacosPropertySource); + } + if (hasAfter) { + propertySources.addAfter(after, nacosPropertySource); + } + } + else { + propertySources.addLast(nacosPropertySource); // default add last + } + } + + public static void addListenerIfAutoRefreshed( + final NacosPropertySource nacosPropertySource, final Properties properties, + final ConfigurableEnvironment environment) { + + if (!nacosPropertySource.isAutoRefreshed()) { // Disable Auto-Refreshed + return; + } + + final String dataId = nacosPropertySource.getDataId(); + final String groupId = nacosPropertySource.getGroupId(); + final String type = nacosPropertySource.getType(); + final NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean( + beanFactory); + + try { + + ConfigService configService = nacosServiceFactory + .createConfigService(properties); + + Listener listener = new AbstractListener() { + + @Override + public void receiveConfigInfo(String config) { + String name = nacosPropertySource.getName(); + NacosPropertySource newNacosPropertySource = new NacosPropertySource( + dataId, groupId, name, config, type); + newNacosPropertySource.copy(nacosPropertySource); + MutablePropertySources propertySources = environment + .getPropertySources(); + // replace NacosPropertySource + propertySources.replace(name, newNacosPropertySource); + } + }; + + if (configService instanceof EventPublishingConfigService) { + ((EventPublishingConfigService) configService).addListener(dataId, + groupId, type, listener); + } + else { + configService.addListener(dataId, groupId, listener); + } + + } + catch (NacosException e) { + throw new RuntimeException( + "ConfigService can't add Listener with properties : " + properties, + e); + } + } + + /** + * The order is closed to {@link ConfigurationClassPostProcessor#getOrder() + * HIGHEST_PRECEDENCE} almost. + * + * @return Ordered.HIGHEST_PRECEDENCE + 1 + * @see ConfigurationClassPostProcessor#getOrder() + */ + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE + 1; + } + + @Override + public void setEnvironment(Environment environment) { + this.environment = (ConfigurableEnvironment) environment; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/XmlNacosPropertySourceBuilder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/XmlNacosPropertySourceBuilder.java index d30736e5..7300b7d6 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/XmlNacosPropertySourceBuilder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/core/env/XmlNacosPropertySourceBuilder.java @@ -16,22 +16,30 @@ */ package com.alibaba.nacos.spring.core.env; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import com.alibaba.nacos.api.config.ConfigType; import com.alibaba.nacos.spring.context.config.xml.NacosPropertySourceXmlBeanDefinition; import com.alibaba.nacos.spring.context.event.config.NacosConfigMetadataEvent; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.core.convert.ConversionService; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; - -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; -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.BEFORE_ATTRIBUTE_NAME; +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.FIRST_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.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; @@ -42,101 +50,117 @@ * @author Mercy * @since 0.1.0 */ -public class XmlNacosPropertySourceBuilder extends - AbstractNacosPropertySourceBuilder { - - /** - * The bean name of {@link XmlNacosPropertySourceBuilder} - */ - public static final String BEAN_NAME = "xmlNacosPropertySourceBuilder"; - - @Override - protected Map[] resolveRuntimeAttributesArray(NacosPropertySourceXmlBeanDefinition beanDefinition, - Properties globalNacosProperties) { - Element element = beanDefinition.getElement(); - Map runtimeAttributes = new HashMap(4); - // Nacos Metadata - runtimeAttributes.put(DATA_ID_ATTRIBUTE_NAME, getAttribute(element, "data-id", DEFAULT_STRING_ATTRIBUTE_VALUE)); - runtimeAttributes.put(GROUP_ID_ATTRIBUTE_NAME, getAttribute(element, "group-id", DEFAULT_GROUP)); - // PropertySource Name - runtimeAttributes.put(NAME_ATTRIBUTE_NAME, getAttribute(element, NAME_ATTRIBUTE_NAME, DEFAULT_STRING_ATTRIBUTE_VALUE)); - // Config type - String type = getAttribute(element, CONFIG_TYPE_ATTRIBUTE_NAME, DEFAULT_CONFIG_TYPE_VALUE); - - try { - runtimeAttributes.put(CONFIG_TYPE_ATTRIBUTE_NAME, ConfigType.valueOf(type.toUpperCase())); - // TODO support nested properties - runtimeAttributes.put(PROPERTIES_ATTRIBUTE_NAME, new Properties()); - return new Map[]{runtimeAttributes}; - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Now the config type just support [properties, json, yaml, xml, text, html]"); - } - - } - - @Override - protected void initNacosPropertySource(NacosPropertySource nacosPropertySource, - NacosPropertySourceXmlBeanDefinition beanDefinition, Map attributes) { - Element element = beanDefinition.getElement(); - - // Attributes Metadata - initAttributesMetadata(nacosPropertySource, element); - // Origin - initOrigin(nacosPropertySource, beanDefinition.getXmlReaderContext()); - // Auto-refreshed - initAutoRefreshed(nacosPropertySource, element); - // PropertySource Order - initOrder(nacosPropertySource, element); - } - - private void initOrigin(NacosPropertySource nacosPropertySource, XmlReaderContext xmlReaderContext) { - // Resource - Resource resource = xmlReaderContext.getResource(); - - nacosPropertySource.setOrigin(resource); - } - - private void initAutoRefreshed(NacosPropertySource nacosPropertySource, Element element) { - boolean autoRefreshed = getAttribute(element, "auto-refreshed", DEFAULT_BOOLEAN_ATTRIBUTE_VALUE); - nacosPropertySource.setAutoRefreshed(autoRefreshed); - } - - private void initAttributesMetadata(NacosPropertySource nacosPropertySource, Element element) { - NamedNodeMap elementAttributes = element.getAttributes(); - int length = elementAttributes.getLength(); - } - - private void initOrder(NacosPropertySource nacosPropertySource, Element element) { - // Order - boolean first = getAttribute(element, FIRST_ATTRIBUTE_NAME, DEFAULT_BOOLEAN_ATTRIBUTE_VALUE); - String before = getAttribute(element, BEFORE_ATTRIBUTE_NAME, DEFAULT_STRING_ATTRIBUTE_VALUE); - String after = getAttribute(element, AFTER_ATTRIBUTE_NAME, DEFAULT_STRING_ATTRIBUTE_VALUE); - nacosPropertySource.setFirst(first); - nacosPropertySource.setBefore(before); - nacosPropertySource.setAfter(after); - } - - - private T getAttribute(Element element, String name, T defaultValue) { - ConversionService conversionService = environment.getConversionService(); - String value = element.getAttribute(name); - String resolvedValue = environment.resolvePlaceholders(value); - T attributeValue = StringUtils.hasText(resolvedValue) ? - (T) conversionService.convert(resolvedValue, defaultValue.getClass()) : - defaultValue; - return attributeValue; - } - - - @Override - protected NacosConfigMetadataEvent createMetaEvent(NacosPropertySource nacosPropertySource, - NacosPropertySourceXmlBeanDefinition beanDefinition) { - return new NacosConfigMetadataEvent(beanDefinition.getElement()); - } - - @Override - protected void doInitMetadataEvent(NacosPropertySource nacosPropertySource, - NacosPropertySourceXmlBeanDefinition beanDefinition, NacosConfigMetadataEvent metadataEvent) { - metadataEvent.setXmlResource(beanDefinition.getXmlReaderContext().getResource()); - } +public class XmlNacosPropertySourceBuilder + extends AbstractNacosPropertySourceBuilder { + + /** + * The bean name of {@link XmlNacosPropertySourceBuilder} + */ + public static final String BEAN_NAME = "xmlNacosPropertySourceBuilder"; + + @Override + protected Map[] resolveRuntimeAttributesArray( + NacosPropertySourceXmlBeanDefinition beanDefinition, + Properties globalNacosProperties) { + Element element = beanDefinition.getElement(); + Map runtimeAttributes = new HashMap(4); + // Nacos Metadata + runtimeAttributes.put(DATA_ID_ATTRIBUTE_NAME, + getAttribute(element, "data-id", DEFAULT_STRING_ATTRIBUTE_VALUE)); + runtimeAttributes.put(GROUP_ID_ATTRIBUTE_NAME, + getAttribute(element, "group-id", DEFAULT_GROUP)); + // PropertySource Name + runtimeAttributes.put(NAME_ATTRIBUTE_NAME, getAttribute(element, + NAME_ATTRIBUTE_NAME, DEFAULT_STRING_ATTRIBUTE_VALUE)); + // Config type + String type = getAttribute(element, CONFIG_TYPE_ATTRIBUTE_NAME, + DEFAULT_CONFIG_TYPE_VALUE); + + try { + runtimeAttributes.put(CONFIG_TYPE_ATTRIBUTE_NAME, + ConfigType.valueOf(type.toUpperCase())); + // TODO support nested properties + runtimeAttributes.put(PROPERTIES_ATTRIBUTE_NAME, new Properties()); + return new Map[] { runtimeAttributes }; + } + catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "Now the config type just support [properties, json, yaml, xml, text, html]"); + } + + } + + @Override + protected void initNacosPropertySource(NacosPropertySource nacosPropertySource, + NacosPropertySourceXmlBeanDefinition beanDefinition, + Map attributes) { + Element element = beanDefinition.getElement(); + + // Attributes Metadata + initAttributesMetadata(nacosPropertySource, element); + // Origin + initOrigin(nacosPropertySource, beanDefinition.getXmlReaderContext()); + // Auto-refreshed + initAutoRefreshed(nacosPropertySource, element); + // PropertySource Order + initOrder(nacosPropertySource, element); + } + + private void initOrigin(NacosPropertySource nacosPropertySource, + XmlReaderContext xmlReaderContext) { + // Resource + Resource resource = xmlReaderContext.getResource(); + + nacosPropertySource.setOrigin(resource); + } + + private void initAutoRefreshed(NacosPropertySource nacosPropertySource, + Element element) { + boolean autoRefreshed = getAttribute(element, "auto-refreshed", + DEFAULT_BOOLEAN_ATTRIBUTE_VALUE); + nacosPropertySource.setAutoRefreshed(autoRefreshed); + } + + private void initAttributesMetadata(NacosPropertySource nacosPropertySource, + Element element) { + NamedNodeMap elementAttributes = element.getAttributes(); + int length = elementAttributes.getLength(); + } + + private void initOrder(NacosPropertySource nacosPropertySource, Element element) { + // Order + boolean first = getAttribute(element, FIRST_ATTRIBUTE_NAME, + DEFAULT_BOOLEAN_ATTRIBUTE_VALUE); + String before = getAttribute(element, BEFORE_ATTRIBUTE_NAME, + DEFAULT_STRING_ATTRIBUTE_VALUE); + String after = getAttribute(element, AFTER_ATTRIBUTE_NAME, + DEFAULT_STRING_ATTRIBUTE_VALUE); + nacosPropertySource.setFirst(first); + nacosPropertySource.setBefore(before); + nacosPropertySource.setAfter(after); + } + + private T getAttribute(Element element, String name, T defaultValue) { + ConversionService conversionService = environment.getConversionService(); + String value = element.getAttribute(name); + String resolvedValue = environment.resolvePlaceholders(value); + T attributeValue = StringUtils.hasText(resolvedValue) + ? (T) conversionService.convert(resolvedValue, defaultValue.getClass()) + : defaultValue; + return attributeValue; + } + + @Override + protected NacosConfigMetadataEvent createMetaEvent( + NacosPropertySource nacosPropertySource, + NacosPropertySourceXmlBeanDefinition beanDefinition) { + return new NacosConfigMetadataEvent(beanDefinition.getElement()); + } + + @Override + protected void doInitMetadataEvent(NacosPropertySource nacosPropertySource, + NacosPropertySourceXmlBeanDefinition beanDefinition, + NacosConfigMetadataEvent metadataEvent) { + metadataEvent.setXmlResource(beanDefinition.getXmlReaderContext().getResource()); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/ApplicationContextHolder.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/ApplicationContextHolder.java index a81d92c2..680503a1 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/ApplicationContextHolder.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/ApplicationContextHolder.java @@ -27,16 +27,17 @@ */ public class ApplicationContextHolder implements ApplicationContextAware { - public static final String BEAN_NAME = "nacosApplicationContextHolder"; + public static final String BEAN_NAME = "nacosApplicationContextHolder"; - private ConfigurableApplicationContext context; + private ConfigurableApplicationContext context; - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - context = (ConfigurableApplicationContext) applicationContext; - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + context = (ConfigurableApplicationContext) applicationContext; + } - public ConfigurableApplicationContext getApplicationContext() { - return context; - } + public ConfigurableApplicationContext getApplicationContext() { + return context; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactory.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactory.java index 1104fd5d..9f4e5723 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactory.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactory.java @@ -16,25 +16,26 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutorService; + import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.spring.context.event.config.EventPublishingConfigService; + import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ExecutorService; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.getNacosConfigListenerExecutorIfPresent; import static com.alibaba.nacos.spring.util.NacosUtils.identify; @@ -44,235 +45,263 @@ * @author Mercy * @since 0.1.0 */ +@SuppressWarnings("unchecked") public class CacheableEventPublishingNacosServiceFactory implements NacosServiceFactory { - private static final CacheableEventPublishingNacosServiceFactory SINGLETON = new CacheableEventPublishingNacosServiceFactory(); - - private final Map configServicesCache = new LinkedHashMap(2); - - private final Map namingServicesCache = new LinkedHashMap(2); - - private final Map maintainServiceCache = new LinkedHashMap(2); - - private final LinkedList deferServiceCache = new LinkedList(); - - private ConfigurableApplicationContext context; - - private ExecutorService nacosConfigListenerExecutor; - - private Map createWorkerManager = new HashMap(3); - - public CacheableEventPublishingNacosServiceFactory() { - createWorkerManager.put(ServiceType.CONFIG, new ConfigCreateWorker()); - createWorkerManager.put(ServiceType.NAMING, new NamingCreateWorker()); - createWorkerManager.put(ServiceType.MAINTAIN, new MaintainCreateWorker()); - createWorkerManager = Collections.unmodifiableMap(createWorkerManager); - } - - @Override - public ConfigService createConfigService(Properties properties) throws NacosException { - Properties copy = new Properties(); - copy.putAll(properties); - return (ConfigService) createWorkerManager.get(ServiceType.CONFIG).run(copy, null); - } - - @Override - public NamingService createNamingService(Properties properties) throws NacosException { - Properties copy = new Properties(); - copy.putAll(properties); - return (NamingService) createWorkerManager.get(ServiceType.NAMING).run(copy, null); - } - - @Override - public NamingMaintainService createNamingMaintainService(Properties properties) throws NacosException { - Properties copy = new Properties(); - copy.putAll(properties); - return (NamingMaintainService) createWorkerManager.get(ServiceType.MAINTAIN).run(copy, null); - } - - // Exist some cases need to create the ConfigService | NamingService | NamingMaintainService - // before loading the Context object, lazy loading - - public T deferCreateService(T service, Properties properties) { - DeferServiceHolder serviceHolder = new DeferServiceHolder(); - serviceHolder.setHolder(service); - serviceHolder.setProperties(properties); - deferServiceCache.add(serviceHolder); - return service; - } - - public void publishDeferService() throws NacosException { - for (DeferServiceHolder holder : deferServiceCache) { - final Object o = holder.getHolder(); - final Properties properties = holder.getProperties(); - if (o instanceof ConfigService) { - ConfigService configService = (ConfigService) o; - createWorkerManager.get(ServiceType.CONFIG).run(properties, configService); - } else if (o instanceof NamingService) { - NamingService namingService = (NamingService) o; - createWorkerManager.get(ServiceType.NAMING).run(properties, namingService); - } else if (o instanceof NamingMaintainService) { - NamingMaintainService maintainService = (NamingMaintainService) o; - createWorkerManager.get(ServiceType.MAINTAIN).run(properties, maintainService); - } - } - deferServiceCache.clear(); - } - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.context = (ConfigurableApplicationContext) applicationContext; - this.nacosConfigListenerExecutor = getSingleton().nacosConfigListenerExecutor == null ? - getNacosConfigListenerExecutorIfPresent(applicationContext) : getSingleton().nacosConfigListenerExecutor; - } - - @Override - public Collection getConfigServices() { - return configServicesCache.values(); - } - - @Override - public Collection getNamingServices() { - return namingServicesCache.values(); - } - - @Override - public Collection getNamingMaintainService() { - return maintainServiceCache.values(); - } - - public static CacheableEventPublishingNacosServiceFactory getSingleton() { - return SINGLETON; - } - - private static enum ServiceType { - - /** - * Config - */ - CONFIG, - - /** - * Naming - */ - NAMING, - - /** - * Maintain - */ - MAINTAIN - - } - - static class DeferServiceHolder { - - private Properties properties; - private Object holder; - private ServiceType type; - - public Properties getProperties() { - return properties; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - public Object getHolder() { - return holder; - } - - public void setHolder(Object holder) { - this.holder = holder; - } - - public ServiceType getType() { - return type; - } - - public void setType(ServiceType type) { - this.type = type; - } - } - - abstract class AbstractCreateWorker { - - AbstractCreateWorker() { - } - - /** - * To perform the corresponding create and logic object cache - * - * @param properties - * @param service - * @return T service - * @throws NacosException - */ - public abstract T run(Properties properties, T service) throws NacosException; - - } - - class ConfigCreateWorker extends AbstractCreateWorker { - - ConfigCreateWorker() { - } - - @Override - public ConfigService run(Properties properties, ConfigService service) throws NacosException { - String cacheKey = identify(properties); - ConfigService configService = configServicesCache.get(cacheKey); - - if (configService == null) { - if (service == null) { - service = NacosFactory.createConfigService(properties); - } - configService = new EventPublishingConfigService(service, properties, getSingleton().context, - getSingleton().nacosConfigListenerExecutor); - configServicesCache.put(cacheKey, configService); - } - return configService; - } - } - - class NamingCreateWorker extends AbstractCreateWorker { - - NamingCreateWorker() { - } - - @Override - public NamingService run(Properties properties, NamingService service) throws NacosException { - String cacheKey = identify(properties); - NamingService namingService = namingServicesCache.get(cacheKey); - - if (namingService == null) { - if (service == null) { - service = NacosFactory.createNamingService(properties); - } - namingService = new DelegatingNamingService(service, properties); - namingServicesCache.put(cacheKey, namingService); - } - return namingService; - } - } - - class MaintainCreateWorker extends AbstractCreateWorker { - - MaintainCreateWorker() { - } - - @Override - public NamingMaintainService run(Properties properties, NamingMaintainService service) throws NacosException { - String cacheKey = identify(properties); - NamingMaintainService namingMaintainService = maintainServiceCache.get(cacheKey); - - if (namingMaintainService == null) { - if (service == null) { - service = NacosFactory.createMaintainService(properties); - } - namingMaintainService = new DelegatingNamingMaintainService(service, properties); - maintainServiceCache.put(cacheKey, namingMaintainService); - } - return namingMaintainService; - } - } + private static volatile CacheableEventPublishingNacosServiceFactory SINGLETON = new CacheableEventPublishingNacosServiceFactory(); + + private final Map configServicesCache = new LinkedHashMap( + 2); + + private final Map namingServicesCache = new LinkedHashMap( + 2); + + private final Map maintainServiceCache = new LinkedHashMap( + 2); + + private final LinkedList deferServiceCache = new LinkedList(); + + private ConfigurableApplicationContext context; + + private ExecutorService nacosConfigListenerExecutor; + + private Map createWorkerManager = new HashMap( + 3); + + public CacheableEventPublishingNacosServiceFactory() { + createWorkerManager.put(ServiceType.CONFIG, new ConfigCreateWorker()); + createWorkerManager.put(ServiceType.NAMING, new NamingCreateWorker()); + createWorkerManager.put(ServiceType.MAINTAIN, new MaintainCreateWorker()); + createWorkerManager = Collections.unmodifiableMap(createWorkerManager); + } + + @Override + public ConfigService createConfigService(Properties properties) + throws NacosException { + Properties copy = new Properties(); + copy.putAll(properties); + return (ConfigService) createWorkerManager.get(ServiceType.CONFIG).run(copy, + null); + } + + @Override + public NamingService createNamingService(Properties properties) + throws NacosException { + Properties copy = new Properties(); + copy.putAll(properties); + return (NamingService) createWorkerManager.get(ServiceType.NAMING).run(copy, + null); + } + + @Override + public NamingMaintainService createNamingMaintainService(Properties properties) + throws NacosException { + Properties copy = new Properties(); + copy.putAll(properties); + return (NamingMaintainService) createWorkerManager.get(ServiceType.MAINTAIN) + .run(copy, null); + } + + // Exist some cases need to create the ConfigService | NamingService | + // NamingMaintainService + // before loading the Context object, lazy loading + + public T deferCreateService(T service, Properties properties) { + DeferServiceHolder serviceHolder = new DeferServiceHolder(); + serviceHolder.setHolder(service); + serviceHolder.setProperties(properties); + deferServiceCache.add(serviceHolder); + return service; + } + + @SuppressWarnings("unchecked") + public void publishDeferService(ApplicationContext context) throws NacosException { + setApplicationContext(context); + for (DeferServiceHolder holder : deferServiceCache) { + final Object o = holder.getHolder(); + final Properties properties = holder.getProperties(); + if (o instanceof ConfigService) { + ConfigService configService = (ConfigService) o; + createWorkerManager.get(ServiceType.CONFIG).run(properties, + configService); + } + else if (o instanceof NamingService) { + NamingService namingService = (NamingService) o; + createWorkerManager.get(ServiceType.NAMING).run(properties, + namingService); + } + else if (o instanceof NamingMaintainService) { + NamingMaintainService maintainService = (NamingMaintainService) o; + createWorkerManager.get(ServiceType.MAINTAIN).run(properties, + maintainService); + } + } + deferServiceCache.clear(); + } + + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + this.context = (ConfigurableApplicationContext) applicationContext; + this.nacosConfigListenerExecutor = getSingleton().nacosConfigListenerExecutor == null + ? getNacosConfigListenerExecutorIfPresent(applicationContext) + : getSingleton().nacosConfigListenerExecutor; + } + + @Override + public Collection getConfigServices() { + return configServicesCache.values(); + } + + @Override + public Collection getNamingServices() { + return namingServicesCache.values(); + } + + @Override + public Collection getNamingMaintainService() { + return maintainServiceCache.values(); + } + + public static CacheableEventPublishingNacosServiceFactory getSingleton() { + return SINGLETON; + } + + private static enum ServiceType { + + /** + * Config + */ + CONFIG, + + /** + * Naming + */ + NAMING, + + /** + * Maintain + */ + MAINTAIN + + } + + static class DeferServiceHolder { + + private Properties properties; + private Object holder; + private ServiceType type; + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + + Object getHolder() { + return holder; + } + + void setHolder(Object holder) { + this.holder = holder; + } + + public ServiceType getType() { + return type; + } + + public void setType(ServiceType type) { + this.type = type; + } + } + + abstract static class AbstractCreateWorker { + + AbstractCreateWorker() { + } + + /** + * To perform the corresponding create and logic object cache + * + * @param properties Set the parameters + * @param service nacos service {ConfigService | NamingService | + * NamingMaintainService} + * @return T service + * @throws NacosException + */ + public abstract T run(Properties properties, T service) throws NacosException; + + } + + class ConfigCreateWorker extends AbstractCreateWorker { + + ConfigCreateWorker() { + } + + @Override + public ConfigService run(Properties properties, ConfigService service) + throws NacosException { + String cacheKey = identify(properties); + ConfigService configService = configServicesCache.get(cacheKey); + + if (configService == null) { + if (service == null) { + service = NacosFactory.createConfigService(properties); + } + configService = new EventPublishingConfigService(service, properties, + getSingleton().context, + getSingleton().nacosConfigListenerExecutor); + configServicesCache.put(cacheKey, configService); + } + return configService; + } + } + + class NamingCreateWorker extends AbstractCreateWorker { + + NamingCreateWorker() { + } + + @Override + public NamingService run(Properties properties, NamingService service) + throws NacosException { + String cacheKey = identify(properties); + NamingService namingService = namingServicesCache.get(cacheKey); + + if (namingService == null) { + if (service == null) { + service = NacosFactory.createNamingService(properties); + } + namingService = new DelegatingNamingService(service, properties); + namingServicesCache.put(cacheKey, namingService); + } + return namingService; + } + } + + class MaintainCreateWorker extends AbstractCreateWorker { + + MaintainCreateWorker() { + } + + @Override + public NamingMaintainService run(Properties properties, + NamingMaintainService service) throws NacosException { + String cacheKey = identify(properties); + NamingMaintainService namingMaintainService = maintainServiceCache + .get(cacheKey); + + if (namingMaintainService == null) { + if (service == null) { + service = NacosFactory.createMaintainService(properties); + } + namingMaintainService = new DelegatingNamingMaintainService(service, + properties); + maintainServiceCache.put(cacheKey, namingMaintainService); + } + return namingMaintainService; + } + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingMaintainService.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingMaintainService.java index f974eec4..025bded4 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingMaintainService.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingMaintainService.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.Map; +import java.util.Properties; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.api.naming.pojo.Instance; @@ -23,96 +26,106 @@ import com.alibaba.nacos.api.selector.AbstractSelector; import com.alibaba.nacos.spring.metadata.NacosServiceMetaData; -import java.util.Map; -import java.util.Properties; - /** * @author liaochuntao * @since 0.3.0 */ -class DelegatingNamingMaintainService implements NamingMaintainService, NacosServiceMetaData { - - private final NamingMaintainService delegate; - - private final Properties properties; - - DelegatingNamingMaintainService(NamingMaintainService delegate, Properties properties) { - this.delegate = delegate; - this.properties = properties; - } - - @Override - public void updateInstance(String serviceName, Instance instance) throws NacosException { - delegate.updateInstance(serviceName, instance); - } - - @Override - public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException { - delegate.updateInstance(serviceName, groupName, instance); - } - - @Override - public Service queryService(String serviceName) throws NacosException { - return delegate.queryService(serviceName); - } - - @Override - public Service queryService(String serviceName, String groupName) throws NacosException { - return delegate.queryService(serviceName, groupName); - } - - @Override - public void createService(String serviceName) throws NacosException { - delegate.createService(serviceName); - } - - @Override - public void createService(String serviceName, String groupName) throws NacosException { - delegate.createService(serviceName, groupName); - } - - @Override - public void createService(String serviceName, String groupName, float protectThreshold) throws NacosException { - delegate.createService(serviceName, groupName, protectThreshold); - } - - @Override - public void createService(String serviceName, String groupName, float protectThreshold, String expression) throws NacosException { - delegate.createService(serviceName, groupName, protectThreshold, expression); - } - - @Override - public void createService(Service service, AbstractSelector selector) throws NacosException { - delegate.createService(service, selector); - } - - @Override - public boolean deleteService(String serviceName) throws NacosException { - return delegate.deleteService(serviceName); - } - - @Override - public boolean deleteService(String serviceName, String groupName) throws NacosException { - return delegate.deleteService(serviceName, groupName); - } - - @Override - public void updateService(String serviceName, String groupName, float protectThreshold) throws NacosException { - delegate.updateService(serviceName, groupName, protectThreshold); - } - - @Override - public void updateService(String serviceName, String groupName, float protectThreshold, Map metadata) throws NacosException { - delegate.updateService(serviceName, groupName, protectThreshold, metadata); - } - - @Override - public void updateService(Service service, AbstractSelector selector) throws NacosException { - delegate.updateService(service, selector); - } - - @Override - public Properties getProperties() { - return properties; - } +class DelegatingNamingMaintainService + implements NamingMaintainService, NacosServiceMetaData { + + private final NamingMaintainService delegate; + + private final Properties properties; + + DelegatingNamingMaintainService(NamingMaintainService delegate, + Properties properties) { + this.delegate = delegate; + this.properties = properties; + } + + @Override + public void updateInstance(String serviceName, Instance instance) + throws NacosException { + delegate.updateInstance(serviceName, instance); + } + + @Override + public void updateInstance(String serviceName, String groupName, Instance instance) + throws NacosException { + delegate.updateInstance(serviceName, groupName, instance); + } + + @Override + public Service queryService(String serviceName) throws NacosException { + return delegate.queryService(serviceName); + } + + @Override + public Service queryService(String serviceName, String groupName) + throws NacosException { + return delegate.queryService(serviceName, groupName); + } + + @Override + public void createService(String serviceName) throws NacosException { + delegate.createService(serviceName); + } + + @Override + public void createService(String serviceName, String groupName) + throws NacosException { + delegate.createService(serviceName, groupName); + } + + @Override + public void createService(String serviceName, String groupName, + float protectThreshold) throws NacosException { + delegate.createService(serviceName, groupName, protectThreshold); + } + + @Override + public void createService(String serviceName, String groupName, + float protectThreshold, String expression) throws NacosException { + delegate.createService(serviceName, groupName, protectThreshold, expression); + } + + @Override + public void createService(Service service, AbstractSelector selector) + throws NacosException { + delegate.createService(service, selector); + } + + @Override + public boolean deleteService(String serviceName) throws NacosException { + return delegate.deleteService(serviceName); + } + + @Override + public boolean deleteService(String serviceName, String groupName) + throws NacosException { + return delegate.deleteService(serviceName, groupName); + } + + @Override + public void updateService(String serviceName, String groupName, + float protectThreshold) throws NacosException { + delegate.updateService(serviceName, groupName, protectThreshold); + } + + @Override + public void updateService(String serviceName, String groupName, + float protectThreshold, Map metadata) throws NacosException { + delegate.updateService(serviceName, groupName, protectThreshold, metadata); + } + + @Override + public void updateService(Service service, AbstractSelector selector) + throws NacosException { + delegate.updateService(service, selector); + } + + @Override + public Properties getProperties() { + return properties; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingService.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingService.java index 185c2a5d..9810203b 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingService.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/DelegatingNamingService.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.List; +import java.util.Properties; + import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.EventListener; @@ -25,9 +28,6 @@ import com.alibaba.nacos.api.selector.AbstractSelector; import com.alibaba.nacos.spring.metadata.NacosServiceMetaData; -import java.util.List; -import java.util.Properties; - /** * Delegating {@link NamingService} with {@link NacosServiceMetaData} * @@ -38,267 +38,316 @@ */ class DelegatingNamingService implements NamingService, NacosServiceMetaData { - private final NamingService delegate; - - private final Properties properties; - - DelegatingNamingService(NamingService delegate, Properties properties) { - this.delegate = delegate; - this.properties = properties; - } - - @Override - public void registerInstance(String serviceName, String ip, int port) throws NacosException { - delegate.registerInstance(serviceName, ip, port); - } - - @Override - public void registerInstance(String serviceName, String groupName, String ip, int port) throws NacosException { - delegate.registerInstance(serviceName, groupName, ip, port); - } - - @Override - public void registerInstance(String serviceName, String ip, int port, String clusterName) throws NacosException { - delegate.registerInstance(serviceName, ip, port, clusterName); - } - - @Override - public void registerInstance(String serviceName, String groupName, String ip, int port, String clusterName) throws NacosException { - delegate.registerInstance(serviceName, groupName, ip, port, clusterName); - } - - @Override - public void registerInstance(String serviceName, Instance instance) throws NacosException { - delegate.registerInstance(serviceName, instance); - } - - @Override - public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { - delegate.registerInstance(serviceName, groupName, instance); - } - - @Override - public void deregisterInstance(String serviceName, String ip, int port) throws NacosException { - delegate.deregisterInstance(serviceName, ip, port); - } - - @Override - public void deregisterInstance(String serviceName, String groupName, String ip, int port) throws NacosException { - delegate.deregisterInstance(serviceName, groupName, ip, port); - } - - @Override - public void deregisterInstance(String serviceName, String ip, int port, String clusterName) throws NacosException { - delegate.deregisterInstance(serviceName, ip, port, clusterName); - } - - @Override - public void deregisterInstance(String serviceName, String groupName, String ip, int port, String clusterName) throws NacosException { - delegate.deregisterInstance(serviceName, groupName, ip, port, clusterName); - } - - @Override - public void deregisterInstance(String serviceName, Instance instance) throws NacosException { - delegate.registerInstance(serviceName, instance); - } - - @Override - public void deregisterInstance(String serviceName, String groupName, Instance instance) throws NacosException { - delegate.deregisterInstance(serviceName, groupName, instance); - } - - @Override - public List getAllInstances(String serviceName) throws NacosException { - return delegate.getAllInstances(serviceName); - } - - @Override - public List getAllInstances(String serviceName, String groupName) throws NacosException { - return delegate.getAllInstances(serviceName, groupName); - } - - @Override - public List getAllInstances(String serviceName, boolean subscribe) throws NacosException { - return delegate.getAllInstances(serviceName, subscribe); - } - - @Override - public List getAllInstances(String serviceName, String groupName, boolean subscribe) throws NacosException { - return delegate.getAllInstances(serviceName, groupName, subscribe); - } - - @Override - public List getAllInstances(String serviceName, List clusters) throws NacosException { - return delegate.getAllInstances(serviceName, clusters); - } - - @Override - public List getAllInstances(String serviceName, String groupName, List clusters) throws NacosException { - return delegate.getAllInstances(serviceName, groupName, clusters); - } - - @Override - public List getAllInstances(String serviceName, List clusters, boolean subscribe) throws NacosException { - return delegate.getAllInstances(serviceName, clusters, subscribe); - } - - @Override - public List getAllInstances(String serviceName, String groupName, List clusters, boolean subscribe) throws NacosException { - return delegate.getAllInstances(serviceName, groupName, clusters, subscribe); - } - - @Override - public List selectInstances(String serviceName, boolean healthy) throws NacosException { - return delegate.selectInstances(serviceName, healthy); - } - - @Override - public List selectInstances(String serviceName, String groupName, boolean healthy) throws NacosException { - return delegate.selectInstances(serviceName, groupName, healthy); - } - - @Override - public List selectInstances(String serviceName, boolean healthy, boolean subscribe) throws NacosException { - return delegate.selectInstances(serviceName, healthy, subscribe); - } - - @Override - public List selectInstances(String serviceName, String groupName, boolean healthy, boolean subscribe) throws NacosException { - return delegate.selectInstances(serviceName, groupName, healthy, subscribe); - } - - @Override - public List selectInstances(String serviceName, List clusters, boolean healthy) throws NacosException { - return delegate.selectInstances(serviceName, clusters, healthy); - } - - @Override - public List selectInstances(String serviceName, String groupName, List clusters, boolean healthy) throws NacosException { - return delegate.selectInstances(serviceName, groupName, clusters, healthy); - } - - @Override - public List selectInstances(String serviceName, List clusters, boolean healthy, boolean subscribe) throws NacosException { - return delegate.selectInstances(serviceName, clusters, healthy, subscribe); - } - - @Override - public List selectInstances(String serviceName, String groupName, List clusters, boolean healthy, boolean subscribe) throws NacosException { - return delegate.selectInstances(serviceName, groupName, clusters, healthy, subscribe); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, String groupName) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, groupName); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, subscribe); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, String groupName, boolean subscribe) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, groupName, subscribe); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, clusters); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, String groupName, List clusters) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, groupName, clusters); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, List clusters, boolean subscribe) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, clusters, subscribe); - } - - @Override - public Instance selectOneHealthyInstance(String serviceName, String groupName, List clusters, boolean subscribe) throws NacosException { - return delegate.selectOneHealthyInstance(serviceName, groupName, clusters, subscribe); - } - - @Override - public void subscribe(String serviceName, EventListener listener) throws NacosException { - delegate.subscribe(serviceName, listener); - } - - @Override - public void subscribe(String serviceName, String groupName, EventListener listener) throws NacosException { - delegate.subscribe(serviceName, groupName, listener); - } - - @Override - public void subscribe(String serviceName, List clusters, EventListener listener) throws NacosException { - delegate.subscribe(serviceName, clusters, listener); - } - - @Override - public void subscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException { - delegate.subscribe(serviceName, groupName, clusters, listener); - } - - @Override - public void unsubscribe(String serviceName, EventListener listener) throws NacosException { - delegate.unsubscribe(serviceName, listener); - } - - @Override - public void unsubscribe(String serviceName, String groupName, EventListener listener) throws NacosException { - delegate.unsubscribe(serviceName, groupName, listener); - } - - @Override - public void unsubscribe(String serviceName, List clusters, EventListener listener) throws NacosException { - delegate.unsubscribe(serviceName, clusters, listener); - } - - @Override - public void unsubscribe(String serviceName, String groupName, List clusters, EventListener listener) throws NacosException { - delegate.unsubscribe(serviceName, groupName, clusters, listener); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize) throws NacosException { - return delegate.getServicesOfServer(pageNo, pageSize); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize, String groupName) throws NacosException { - return delegate.getServicesOfServer(pageNo, pageSize, groupName); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException { - return delegate.getServicesOfServer(pageNo, pageSize, selector); - } - - @Override - public ListView getServicesOfServer(int pageNo, int pageSize, String groupName, AbstractSelector selector) throws NacosException { - return delegate.getServicesOfServer(pageNo, pageSize, groupName, selector); - } - - @Override - public List getSubscribeServices() throws NacosException { - return delegate.getSubscribeServices(); - } - - @Override - public String getServerStatus() { - return delegate.getServerStatus(); - } - - @Override - public Properties getProperties() { - return properties; - } + private final NamingService delegate; + + private final Properties properties; + + DelegatingNamingService(NamingService delegate, Properties properties) { + this.delegate = delegate; + this.properties = properties; + } + + @Override + public void registerInstance(String serviceName, String ip, int port) + throws NacosException { + delegate.registerInstance(serviceName, ip, port); + } + + @Override + public void registerInstance(String serviceName, String groupName, String ip, + int port) throws NacosException { + delegate.registerInstance(serviceName, groupName, ip, port); + } + + @Override + public void registerInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + delegate.registerInstance(serviceName, ip, port, clusterName); + } + + @Override + public void registerInstance(String serviceName, String groupName, String ip, + int port, String clusterName) throws NacosException { + delegate.registerInstance(serviceName, groupName, ip, port, clusterName); + } + + @Override + public void registerInstance(String serviceName, Instance instance) + throws NacosException { + delegate.registerInstance(serviceName, instance); + } + + @Override + public void registerInstance(String serviceName, String groupName, Instance instance) + throws NacosException { + delegate.registerInstance(serviceName, groupName, instance); + } + + @Override + public void deregisterInstance(String serviceName, String ip, int port) + throws NacosException { + delegate.deregisterInstance(serviceName, ip, port); + } + + @Override + public void deregisterInstance(String serviceName, String groupName, String ip, + int port) throws NacosException { + delegate.deregisterInstance(serviceName, groupName, ip, port); + } + + @Override + public void deregisterInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + delegate.deregisterInstance(serviceName, ip, port, clusterName); + } + + @Override + public void deregisterInstance(String serviceName, String groupName, String ip, + int port, String clusterName) throws NacosException { + delegate.deregisterInstance(serviceName, groupName, ip, port, clusterName); + } + + @Override + public void deregisterInstance(String serviceName, Instance instance) + throws NacosException { + delegate.registerInstance(serviceName, instance); + } + + @Override + public void deregisterInstance(String serviceName, String groupName, + Instance instance) throws NacosException { + delegate.deregisterInstance(serviceName, groupName, instance); + } + + @Override + public List getAllInstances(String serviceName) throws NacosException { + return delegate.getAllInstances(serviceName); + } + + @Override + public List getAllInstances(String serviceName, String groupName) + throws NacosException { + return delegate.getAllInstances(serviceName, groupName); + } + + @Override + public List getAllInstances(String serviceName, boolean subscribe) + throws NacosException { + return delegate.getAllInstances(serviceName, subscribe); + } + + @Override + public List getAllInstances(String serviceName, String groupName, + boolean subscribe) throws NacosException { + return delegate.getAllInstances(serviceName, groupName, subscribe); + } + + @Override + public List getAllInstances(String serviceName, List clusters) + throws NacosException { + return delegate.getAllInstances(serviceName, clusters); + } + + @Override + public List getAllInstances(String serviceName, String groupName, + List clusters) throws NacosException { + return delegate.getAllInstances(serviceName, groupName, clusters); + } + + @Override + public List getAllInstances(String serviceName, List clusters, + boolean subscribe) throws NacosException { + return delegate.getAllInstances(serviceName, clusters, subscribe); + } + + @Override + public List getAllInstances(String serviceName, String groupName, + List clusters, boolean subscribe) throws NacosException { + return delegate.getAllInstances(serviceName, groupName, clusters, subscribe); + } + + @Override + public List selectInstances(String serviceName, boolean healthy) + throws NacosException { + return delegate.selectInstances(serviceName, healthy); + } + + @Override + public List selectInstances(String serviceName, String groupName, + boolean healthy) throws NacosException { + return delegate.selectInstances(serviceName, groupName, healthy); + } + + @Override + public List selectInstances(String serviceName, boolean healthy, + boolean subscribe) throws NacosException { + return delegate.selectInstances(serviceName, healthy, subscribe); + } + + @Override + public List selectInstances(String serviceName, String groupName, + boolean healthy, boolean subscribe) throws NacosException { + return delegate.selectInstances(serviceName, groupName, healthy, subscribe); + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy) throws NacosException { + return delegate.selectInstances(serviceName, clusters, healthy); + } + + @Override + public List selectInstances(String serviceName, String groupName, + List clusters, boolean healthy) throws NacosException { + return delegate.selectInstances(serviceName, groupName, clusters, healthy); + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy, boolean subscribe) throws NacosException { + return delegate.selectInstances(serviceName, clusters, healthy, subscribe); + } + + @Override + public List selectInstances(String serviceName, String groupName, + List clusters, boolean healthy, boolean subscribe) + throws NacosException { + return delegate.selectInstances(serviceName, groupName, clusters, healthy, + subscribe); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName) throws NacosException { + return delegate.selectOneHealthyInstance(serviceName); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName) + throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, groupName); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) + throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, subscribe); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + boolean subscribe) throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, groupName, subscribe); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters) + throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, clusters); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + List clusters) throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, groupName, clusters); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters, + boolean subscribe) throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, clusters, subscribe); + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + List clusters, boolean subscribe) throws NacosException { + return delegate.selectOneHealthyInstance(serviceName, groupName, clusters, + subscribe); + } + + @Override + public void subscribe(String serviceName, EventListener listener) + throws NacosException { + delegate.subscribe(serviceName, listener); + } + + @Override + public void subscribe(String serviceName, String groupName, EventListener listener) + throws NacosException { + delegate.subscribe(serviceName, groupName, listener); + } + + @Override + public void subscribe(String serviceName, List clusters, + EventListener listener) throws NacosException { + delegate.subscribe(serviceName, clusters, listener); + } + + @Override + public void subscribe(String serviceName, String groupName, List clusters, + EventListener listener) throws NacosException { + delegate.subscribe(serviceName, groupName, clusters, listener); + } + + @Override + public void unsubscribe(String serviceName, EventListener listener) + throws NacosException { + delegate.unsubscribe(serviceName, listener); + } + + @Override + public void unsubscribe(String serviceName, String groupName, EventListener listener) + throws NacosException { + delegate.unsubscribe(serviceName, groupName, listener); + } + + @Override + public void unsubscribe(String serviceName, List clusters, + EventListener listener) throws NacosException { + delegate.unsubscribe(serviceName, clusters, listener); + } + + @Override + public void unsubscribe(String serviceName, String groupName, List clusters, + EventListener listener) throws NacosException { + delegate.unsubscribe(serviceName, groupName, clusters, listener); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize) + throws NacosException { + return delegate.getServicesOfServer(pageNo, pageSize); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + String groupName) throws NacosException { + return delegate.getServicesOfServer(pageNo, pageSize, groupName); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + return delegate.getServicesOfServer(pageNo, pageSize, selector); + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + String groupName, AbstractSelector selector) throws NacosException { + return delegate.getServicesOfServer(pageNo, pageSize, groupName, selector); + } + + @Override + public List getSubscribeServices() throws NacosException { + return delegate.getSubscribeServices(); + } + + @Override + public String getServerStatus() { + return delegate.getServerStatus(); + } + + @Override + public Properties getProperties() { + return properties; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/NacosServiceFactory.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/NacosServiceFactory.java index d8584b64..77ead0b7 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/NacosServiceFactory.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/factory/NacosServiceFactory.java @@ -16,15 +16,15 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.Collection; +import java.util.Properties; + import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.api.naming.NamingService; -import java.util.Collection; -import java.util.Properties; - /** * Nacos Service Factory * @@ -34,60 +34,61 @@ */ public interface NacosServiceFactory { - /** - * The bean name of {@link NacosServiceFactory} - */ - String BEAN_NAME = "nacosServiceFactory"; + /** + * The bean name of {@link NacosServiceFactory} + */ + String BEAN_NAME = "nacosServiceFactory"; - /** - * Create {@link ConfigService} instance - * - * @param properties init param - * @return a {@link ConfigService} instance - * @throws NacosException If creation is failed. - * @see NacosFactory#createConfigService(Properties) - */ - ConfigService createConfigService(Properties properties) throws NacosException; + /** + * Create {@link ConfigService} instance + * + * @param properties init param + * @return a {@link ConfigService} instance + * @throws NacosException If creation is failed. + * @see NacosFactory#createConfigService(Properties) + */ + ConfigService createConfigService(Properties properties) throws NacosException; - /** - * Create {@link NamingService} instance - * - * @param properties init param - * @return a {@link NamingService} instance - * @throws NacosException If creation is failed. - * @see NacosFactory#createNamingService(Properties) - */ - NamingService createNamingService(Properties properties) throws NacosException; + /** + * Create {@link NamingService} instance + * + * @param properties init param + * @return a {@link NamingService} instance + * @throws NacosException If creation is failed. + * @see NacosFactory#createNamingService(Properties) + */ + NamingService createNamingService(Properties properties) throws NacosException; - /** - * Create {@link NamingMaintainService} instance - * - * @param properties init param - * @return a {@link NamingMaintainService} instance - * @throws NacosException If creation is failed. - * @see NacosFactory#createNamingService(Properties) - */ - NamingMaintainService createNamingMaintainService(Properties properties) throws NacosException; + /** + * Create {@link NamingMaintainService} instance + * + * @param properties init param + * @return a {@link NamingMaintainService} instance + * @throws NacosException If creation is failed. + * @see NacosFactory#createNamingService(Properties) + */ + NamingMaintainService createNamingMaintainService(Properties properties) + throws NacosException; - /** - * Get all instances of {@link ConfigService} - * - * @return read-only {@link Collection} - */ - Collection getConfigServices(); + /** + * Get all instances of {@link ConfigService} + * + * @return read-only {@link Collection} + */ + Collection getConfigServices(); - /** - * Get all instances of {@link NamingService} - * - * @return read-only {@link Collection} - */ - Collection getNamingServices(); + /** + * Get all instances of {@link NamingService} + * + * @return read-only {@link Collection} + */ + Collection getNamingServices(); - /** - * Get all instances of {@link NamingMaintainService} - * - * @return read-only {@link Collection} - */ - Collection getNamingMaintainService(); + /** + * Get all instances of {@link NamingMaintainService} + * + * @return read-only {@link Collection} + */ + Collection getNamingMaintainService(); } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/metadata/NacosServiceMetaData.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/metadata/NacosServiceMetaData.java index 0b7ae93a..0fc698b1 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/metadata/NacosServiceMetaData.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/metadata/NacosServiceMetaData.java @@ -16,12 +16,12 @@ */ package com.alibaba.nacos.spring.metadata; +import java.util.Properties; + import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.naming.NamingService; -import java.util.Properties; - /** * An interface exposes the Meta-Data of Nacos Service * @@ -33,11 +33,11 @@ */ public interface NacosServiceMetaData { - /** - * Get the {@link Properties} for Nacos Service - * - * @return non-null - * @see NacosProperties - */ - Properties getProperties(); + /** + * Get the {@link Properties} for Nacos Service + * + * @return non-null + * @see NacosProperties + */ + Properties getProperties(); } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/AbstractConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/AbstractConfigParse.java index 22df97a6..191fe728 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/AbstractConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/AbstractConfigParse.java @@ -17,23 +17,24 @@ package com.alibaba.nacos.spring.util; /** - * The user inherits the AbstraceConfigParse abstract class and adds the implementation class in - * META-INF/com.alibaba.nacos.spring.util.ConfigParse to implement the addition of custom parsing rules. - * If the dataId and group methods are not overridden, Will override the original parsing rule implementation, - * otherwise the user-defined parsing rules will only be applied to specific dataId and group + * The user inherits the AbstraceConfigParse abstract class and adds the implementation + * class in META-INF/com.alibaba.nacos.spring.util.ConfigParse to implement the addition + * of custom parsing rules. If the dataId and group methods are not overridden, Will + * override the original parsing rule implementation, otherwise the user-defined parsing + * rules will only be applied to specific dataId and group * * @author liaochuntao * @since 0.3.0 */ public abstract class AbstractConfigParse implements ConfigParse { - @Override - public String dataId() { - return ""; - } + @Override + public String dataId() { + return ""; + } - @Override - public String group() { - return ""; - } + @Override + public String group() { + return ""; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParse.java index a7c34743..800476a4 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParse.java @@ -24,33 +24,33 @@ */ public interface ConfigParse { - /** - * parse config context to map - * - * @param configText receive config context - * @return {@link Properties} - */ - Properties parse(String configText); + /** + * parse config context to map + * + * @param configText receive config context + * @return {@link Properties} + */ + Properties parse(String configText); - /** - * get this ConfigParse process config type - * - * @return this parse process type - */ - String processType(); + /** + * get this ConfigParse process config type + * + * @return this parse process type + */ + String processType(); - /** - * get config dataId - * - * @return dataId - */ - String dataId(); + /** + * get config dataId + * + * @return dataId + */ + String dataId(); - /** - * get config group - * - * @return group - */ - String group(); + /** + * get config group + * + * @return group + */ + String group(); } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParseUtils.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParseUtils.java index 79624d8b..7c752159 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParseUtils.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ConfigParseUtils.java @@ -16,11 +16,6 @@ */ package com.alibaba.nacos.spring.util; -import com.alibaba.nacos.spring.util.parse.DefaultJsonConfigParse; -import com.alibaba.nacos.spring.util.parse.DefaultPropertiesConfigParse; -import com.alibaba.nacos.spring.util.parse.DefaultXmlConfigParse; -import com.alibaba.nacos.spring.util.parse.DefaultYamlConfigParse; - import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -28,114 +23,133 @@ import java.util.Properties; import java.util.ServiceLoader; +import com.alibaba.nacos.spring.util.parse.DefaultJsonConfigParse; +import com.alibaba.nacos.spring.util.parse.DefaultPropertiesConfigParse; +import com.alibaba.nacos.spring.util.parse.DefaultXmlConfigParse; +import com.alibaba.nacos.spring.util.parse.DefaultYamlConfigParse; + /** * @author liaochuntao * @since 0.3.0 */ final class ConfigParseUtils { - private static final String LINK_CHAR = "#@#"; - private static Map DEFAULT_CONFIG_PARSE_MAP = new HashMap(8); - private static Map> CUSTOMER_CONFIG_PARSE_MAP = new HashMap(8); - - static { - - DefaultJsonConfigParse jsonConfigParse = new DefaultJsonConfigParse(); - DefaultPropertiesConfigParse propertiesConfigParse = new DefaultPropertiesConfigParse(); - DefaultYamlConfigParse yamlConfigParse = new DefaultYamlConfigParse(); - DefaultXmlConfigParse xmlConfigParse = new DefaultXmlConfigParse(); - - // register nacos default ConfigParse - DEFAULT_CONFIG_PARSE_MAP.put(jsonConfigParse.processType().toLowerCase(), jsonConfigParse); - DEFAULT_CONFIG_PARSE_MAP.put(propertiesConfigParse.processType().toLowerCase(), propertiesConfigParse); - DEFAULT_CONFIG_PARSE_MAP.put(yamlConfigParse.processType().toLowerCase(), yamlConfigParse); - DEFAULT_CONFIG_PARSE_MAP.put(xmlConfigParse.processType().toLowerCase(), xmlConfigParse); - - // register customer ConfigParse - ServiceLoader configParses = ServiceLoader.load(ConfigParse.class); - StringBuilder sb = new StringBuilder(); - for (ConfigParse configParse : configParses) { - String type = configParse.processType().toLowerCase(); - if (!CUSTOMER_CONFIG_PARSE_MAP.containsKey(type)) { - CUSTOMER_CONFIG_PARSE_MAP.put(type, new HashMap(1)); - } - sb.setLength(0); - sb.append(configParse.dataId()).append(LINK_CHAR).append(configParse.group()); - if (LINK_CHAR.equals(sb.toString())) { - // If the user does not set the data id and group processed by config parse, - // this type of config is resolved globally by default - DEFAULT_CONFIG_PARSE_MAP.put(type, configParse); - } else { - CUSTOMER_CONFIG_PARSE_MAP.get(type).put(sb.toString(), configParse); - } - } - - DEFAULT_CONFIG_PARSE_MAP = Collections.unmodifiableMap(DEFAULT_CONFIG_PARSE_MAP); - CUSTOMER_CONFIG_PARSE_MAP = Collections.unmodifiableMap(CUSTOMER_CONFIG_PARSE_MAP); - } - - static Properties toProperties(final String context, String type) { - - if (context == null) { - return new Properties(); - } - // Again the type lowercase, ensure the search - type = type.toLowerCase(); - - Properties properties = new Properties(); - if (DEFAULT_CONFIG_PARSE_MAP.containsKey(type)) { - ConfigParse configParse = DEFAULT_CONFIG_PARSE_MAP.get(type); - properties.putAll(configParse.parse(context)); - return properties; - } else { - throw new UnsupportedOperationException("Parsing is not yet supported for this type profile : " + type); - } - } - - /** - * XML configuration parsing to support different schemas - * - * @param dataId config dataId - * @param group config group - * @param context config context - * @param type config type - * @return {@link Properties} - */ - static Properties toProperties(final String dataId, final String group, final String context, String type) { - - if (context == null) { - return new Properties(); - } - // Again the type lowercase, ensure the search - type = type.toLowerCase(); - - String configParseKey = new StringBuilder() - .append(dataId) - .append(LINK_CHAR) - .append(group) - .toString(); - Properties properties = new Properties(); - - if (CUSTOMER_CONFIG_PARSE_MAP.isEmpty() || LINK_CHAR.equals(configParseKey)) { - return toProperties(context, type); - } - if (CUSTOMER_CONFIG_PARSE_MAP.get(type) == null || CUSTOMER_CONFIG_PARSE_MAP.get(type).isEmpty()) { - return toProperties(context, type); - } - if (CUSTOMER_CONFIG_PARSE_MAP.get(type).get(configParseKey) == null) { - return toProperties(context, type); - } else { - if (CUSTOMER_CONFIG_PARSE_MAP.containsKey(type)) { - ConfigParse configParse = CUSTOMER_CONFIG_PARSE_MAP.get(type).get(configParseKey); - if (configParse == null) { - throw new NoSuchElementException("This config can't find ConfigParse to parse"); - } - properties.putAll(configParse.parse(context)); - return properties; - } else { - throw new UnsupportedOperationException("Parsing is not yet supported for this type profile : " + type); - } - } - } + private static final String LINK_CHAR = "#@#"; + private static Map DEFAULT_CONFIG_PARSE_MAP = new HashMap(8); + private static Map> CUSTOMER_CONFIG_PARSE_MAP = new HashMap( + 8); + + static { + + DefaultJsonConfigParse jsonConfigParse = new DefaultJsonConfigParse(); + DefaultPropertiesConfigParse propertiesConfigParse = new DefaultPropertiesConfigParse(); + DefaultYamlConfigParse yamlConfigParse = new DefaultYamlConfigParse(); + DefaultXmlConfigParse xmlConfigParse = new DefaultXmlConfigParse(); + + // register nacos default ConfigParse + DEFAULT_CONFIG_PARSE_MAP.put(jsonConfigParse.processType().toLowerCase(), + jsonConfigParse); + DEFAULT_CONFIG_PARSE_MAP.put(propertiesConfigParse.processType().toLowerCase(), + propertiesConfigParse); + DEFAULT_CONFIG_PARSE_MAP.put(yamlConfigParse.processType().toLowerCase(), + yamlConfigParse); + DEFAULT_CONFIG_PARSE_MAP.put(xmlConfigParse.processType().toLowerCase(), + xmlConfigParse); + + // register customer ConfigParse + ServiceLoader configParses = ServiceLoader.load(ConfigParse.class); + StringBuilder sb = new StringBuilder(); + for (ConfigParse configParse : configParses) { + String type = configParse.processType().toLowerCase(); + if (!CUSTOMER_CONFIG_PARSE_MAP.containsKey(type)) { + CUSTOMER_CONFIG_PARSE_MAP.put(type, new HashMap(1)); + } + sb.setLength(0); + sb.append(configParse.dataId()).append(LINK_CHAR).append(configParse.group()); + if (LINK_CHAR.equals(sb.toString())) { + // If the user does not set the data id and group processed by config + // parse, + // this type of config is resolved globally by default + DEFAULT_CONFIG_PARSE_MAP.put(type, configParse); + } + else { + CUSTOMER_CONFIG_PARSE_MAP.get(type).put(sb.toString(), configParse); + } + } + + DEFAULT_CONFIG_PARSE_MAP = Collections.unmodifiableMap(DEFAULT_CONFIG_PARSE_MAP); + CUSTOMER_CONFIG_PARSE_MAP = Collections + .unmodifiableMap(CUSTOMER_CONFIG_PARSE_MAP); + } + + static Properties toProperties(final String context, String type) { + + if (context == null) { + return new Properties(); + } + // Again the type lowercase, ensure the search + type = type.toLowerCase(); + + Properties properties = new Properties(); + if (DEFAULT_CONFIG_PARSE_MAP.containsKey(type)) { + ConfigParse configParse = DEFAULT_CONFIG_PARSE_MAP.get(type); + properties.putAll(configParse.parse(context)); + return properties; + } + else { + throw new UnsupportedOperationException( + "Parsing is not yet supported for this type profile : " + type); + } + } + + /** + * XML configuration parsing to support different schemas + * + * @param dataId config dataId + * @param group config group + * @param context config context + * @param type config type + * @return {@link Properties} + */ + static Properties toProperties(final String dataId, final String group, + final String context, String type) { + + if (context == null) { + return new Properties(); + } + // Again the type lowercase, ensure the search + type = type.toLowerCase(); + + String configParseKey = new StringBuilder().append(dataId).append(LINK_CHAR) + .append(group).toString(); + Properties properties = new Properties(); + + if (CUSTOMER_CONFIG_PARSE_MAP.isEmpty() || LINK_CHAR.equals(configParseKey)) { + return toProperties(context, type); + } + if (CUSTOMER_CONFIG_PARSE_MAP.get(type) == null + || CUSTOMER_CONFIG_PARSE_MAP.get(type).isEmpty()) { + return toProperties(context, type); + } + if (CUSTOMER_CONFIG_PARSE_MAP.get(type).get(configParseKey) == null) { + return toProperties(context, type); + } + else { + if (CUSTOMER_CONFIG_PARSE_MAP.containsKey(type)) { + ConfigParse configParse = CUSTOMER_CONFIG_PARSE_MAP.get(type) + .get(configParseKey); + if (configParse == null) { + throw new NoSuchElementException( + "This config can't find ConfigParse to parse"); + } + properties.putAll(configParse.parse(context)); + return properties; + } + else { + throw new UnsupportedOperationException( + "Parsing is not yet supported for this type profile : " + type); + } + } + } } \ No newline at end of file diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/GlobalNacosPropertiesSource.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/GlobalNacosPropertiesSource.java index c29fd874..a14ee45f 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/GlobalNacosPropertiesSource.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/GlobalNacosPropertiesSource.java @@ -16,13 +16,17 @@ */ package com.alibaba.nacos.spring.util; -import com.alibaba.nacos.api.annotation.NacosProperties; -import org.springframework.beans.factory.BeanFactory; - import java.util.Map; import java.util.Properties; -import static com.alibaba.nacos.spring.util.NacosBeanUtils.*; +import com.alibaba.nacos.api.annotation.NacosProperties; + +import org.springframework.beans.factory.BeanFactory; + +import static com.alibaba.nacos.spring.util.NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME; +import static com.alibaba.nacos.spring.util.NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME; +import static com.alibaba.nacos.spring.util.NacosBeanUtils.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.NacosUtils.merge; import static java.util.Collections.emptyMap; @@ -34,54 +38,54 @@ */ public enum GlobalNacosPropertiesSource { - /** - * Default Global {@link NacosProperties} - */ - DEFAULT(GLOBAL_NACOS_PROPERTIES_BEAN_NAME), - - /** - * Global {@link NacosProperties} for Nacos Config - */ - CONFIG(CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME), - - /** - * Global {@link NacosProperties} for Nacos discovery - */ - DISCOVERY(DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME), + /** + * Default Global {@link NacosProperties} + */ + DEFAULT(GLOBAL_NACOS_PROPERTIES_BEAN_NAME), - /** - * Global {@link NacosProperties} for Nacos maintain - */ - MAINTAIN(MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME); + /** + * Global {@link NacosProperties} for Nacos Config + */ + CONFIG(CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME), + /** + * Global {@link NacosProperties} for Nacos discovery + */ + DISCOVERY(DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME), - private final String beanName; + /** + * Global {@link NacosProperties} for Nacos maintain + */ + MAINTAIN(MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME); - GlobalNacosPropertiesSource(String beanName) { - this.beanName = beanName; - } + private final String beanName; - /** - * Get Merged {@link Properties} from {@link BeanFactory} - * - * @param beanFactory {@link BeanFactory} - * @return Global {@link Properties} Bean - */ - public Properties getMergedGlobalProperties(BeanFactory beanFactory) { - Properties currentProperties = getProperties(beanFactory, beanName); - Properties globalProperties = getProperties(beanFactory, GLOBAL_NACOS_PROPERTIES_BEAN_NAME); - // merge - merge(globalProperties, currentProperties); - return globalProperties; - } + GlobalNacosPropertiesSource(String beanName) { + this.beanName = beanName; + } + /** + * Get Merged {@link Properties} from {@link BeanFactory} + * + * @param beanFactory {@link BeanFactory} + * @return Global {@link Properties} Bean + */ + public Properties getMergedGlobalProperties(BeanFactory beanFactory) { + Properties currentProperties = getProperties(beanFactory, beanName); + Properties globalProperties = getProperties(beanFactory, + GLOBAL_NACOS_PROPERTIES_BEAN_NAME); + // merge + merge(globalProperties, currentProperties); + return globalProperties; + } - private Properties getProperties(BeanFactory beanFactory, String beanName) { - Properties properties = new Properties(); - // If Bean is absent , source will be empty. - Map propertiesSource = beanFactory.containsBean(beanName) ? - beanFactory.getBean(beanName, Properties.class) : emptyMap(); - properties.putAll(propertiesSource); - return properties; - } + private Properties getProperties(BeanFactory beanFactory, String beanName) { + Properties properties = new Properties(); + // If Bean is absent , source will be empty. + Map propertiesSource = beanFactory.containsBean(beanName) + ? beanFactory.getBean(beanName, Properties.class) + : emptyMap(); + properties.putAll(propertiesSource); + return properties; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosBeanUtils.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosBeanUtils.java index f5b78534..3b7881c3 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosBeanUtils.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosBeanUtils.java @@ -16,12 +16,22 @@ */ package com.alibaba.nacos.spring.util; +import java.lang.reflect.Constructor; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + import com.alibaba.nacos.spring.beans.factory.annotation.AnnotationNacosInjectedBeanPostProcessor; import com.alibaba.nacos.spring.beans.factory.annotation.ConfigServiceBeanBuilder; import com.alibaba.nacos.spring.beans.factory.annotation.NamingMaintainServiceBeanBuilder; import com.alibaba.nacos.spring.beans.factory.annotation.NamingServiceBeanBuilder; import com.alibaba.nacos.spring.context.annotation.config.NacosConfigListenerMethodProcessor; import com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor; +import com.alibaba.nacos.spring.context.annotation.config.SpringValueAnnotationBeanPostProcessor; import com.alibaba.nacos.spring.context.event.LoggingNacosConfigMetadataEventListener; import com.alibaba.nacos.spring.context.properties.config.NacosConfigurationPropertiesBindingPostProcessor; import com.alibaba.nacos.spring.core.env.AnnotationNacosPropertySourceBuilder; @@ -32,6 +42,7 @@ import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.spring.util.BeanUtils; import org.apache.commons.lang3.ArrayUtils; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -46,15 +57,6 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; -import java.lang.reflect.Constructor; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - import static com.alibaba.nacos.spring.context.constants.NacosConstants.DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM; import static com.alibaba.nacos.spring.context.constants.NacosConstants.NACOS_CONFIG_LISTENER_PARALLELISM; import static com.alibaba.nacos.spring.util.NacosUtils.resolveProperties; @@ -67,413 +69,513 @@ */ public abstract class NacosBeanUtils { - /** - * The bean name of {@link PropertySourcesPlaceholderConfigurer} - */ - public static final String PLACEHOLDER_CONFIGURER_BEAN_NAME = "propertySourcesPlaceholderConfigurer"; - - /** - * The bean name of global Nacos {@link Properties} - */ - public static final String GLOBAL_NACOS_PROPERTIES_BEAN_NAME = "globalNacosProperties"; - - /** - * The bean name of global Nacos {@link Properties} for config - */ - public static final String CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME - + "$config"; - - /** - * The bean name of global Nacos {@link Properties} for discovery - */ - public static final String DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME + - "$discovery"; - - /** - * The bean name of global Nacos {@link Properties} for maintain - */ - public static final String MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME + - "$maintain"; - - /** - * The bean name of {@link Executor} for Nacos Config Listener - */ - public static final String NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME = "nacosConfigListenerExecutor"; - - /** - * Register an object to be Singleton Bean - * - * @param registry {@link BeanDefinitionRegistry} - * @param beanName bean name - * @param singletonObject singleton object - */ - public static void registerSingleton(BeanDefinitionRegistry registry, String beanName, Object singletonObject) { - SingletonBeanRegistry beanRegistry = null; - if (registry instanceof SingletonBeanRegistry) { - beanRegistry = (SingletonBeanRegistry) registry; - } else if (registry instanceof AbstractApplicationContext) { - // Maybe AbstractApplicationContext or its sub-classes - beanRegistry = ((AbstractApplicationContext) registry).getBeanFactory(); - } - // Register Singleton Object if possible - if (beanRegistry != null) { - // Determine in advance whether injected with beans - if (!beanRegistry.containsSingleton(beanName)) { - beanRegistry.registerSingleton(beanName, singletonObject); - } - } - } - - /** - * Register Infrastructure Bean - * - * @param registry {@link BeanDefinitionRegistry} - * @param beanName the name of bean - * @param beanClass the class of bean - * @param constructorArgs the arguments of {@link Constructor} - */ - public static void registerInfrastructureBean(BeanDefinitionRegistry registry, String beanName, Class beanClass, - Object... constructorArgs) { - // Build a BeanDefinition for NacosServiceFactory class - BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(beanClass); - for (Object constructorArg : constructorArgs) { - beanDefinitionBuilder.addConstructorArgValue(constructorArg); - } - // ROLE_INFRASTRUCTURE - beanDefinitionBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - // Register - registry.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition()); - } - - /** - * Register Infrastructure Bean if absent - * - * @param registry {@link BeanDefinitionRegistry} - * @param beanName the name of bean - * @param beanClass the class of bean - * @param constructorArgs the arguments of {@link Constructor} - */ - public static void registerInfrastructureBeanIfAbsent(BeanDefinitionRegistry registry, String beanName, Class beanClass, - Object... constructorArgs) { - if (!isBeanDefinitionPresent(registry, beanName, beanClass) && !registry.containsBeanDefinition(beanName)) { - registerInfrastructureBean(registry, beanName, beanClass, constructorArgs); - } - } - - /** - * Resolve {@link BeanFactory} from {@link BeanDefinitionRegistry} - * - * @param registry {@link BeanDefinitionRegistry} - * @return {@link BeanFactory} if resolved - */ - public static BeanFactory resolveBeanFactory(BeanDefinitionRegistry registry) { - if (registry instanceof BeanFactory) { - return (BeanFactory) registry; - } - - if (registry instanceof AbstractApplicationContext) { - return ((AbstractApplicationContext) registry).getBeanFactory(); - } - return null; - } - - /** - * Is {@link BeanDefinition} present in {@link BeanDefinitionRegistry} - * - * @param registry {@link BeanDefinitionRegistry} - * @param beanName the name of bean - * @param targetBeanClass the type of bean - * @return If Present , return true - */ - public static boolean isBeanDefinitionPresent(BeanDefinitionRegistry registry, String beanName, Class targetBeanClass) { - String[] beanNames = BeanUtils.getBeanNames((ListableBeanFactory) registry, targetBeanClass); - return ArrayUtils.contains(beanNames, beanName); - } - - /** - * Register {@link PropertySourcesPlaceholderConfigurer} Bean - * - * @param registry {@link BeanDefinitionRegistry} - */ - public static void registerPropertySourcesPlaceholderConfigurer(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, PLACEHOLDER_CONFIGURER_BEAN_NAME, - PropertySourcesPlaceholderConfigurer.class); - } - - - /** - * Register Global Nacos Properties Bean with specified name - * - * @param attributes the attributes of Global Nacos Properties may contain placeholders - * @param registry {@link BeanDefinitionRegistry} - * @param propertyResolver {@link PropertyResolver} - * @param beanName Bean name - */ - public static void registerGlobalNacosProperties(AnnotationAttributes attributes, - BeanDefinitionRegistry registry, - PropertyResolver propertyResolver, - String beanName) { - if (attributes == null) { - return; // Compatible with null - } - AnnotationAttributes globalPropertiesAttributes = attributes.getAnnotation("globalProperties"); - registerGlobalNacosProperties((Map) globalPropertiesAttributes, registry, propertyResolver, - beanName); - } - - /** - * Register Global Nacos Properties Bean with specified name - * - * @param globalPropertiesAttributes the attributes of Global Nacos Properties may contain placeholders - * @param registry {@link BeanDefinitionRegistry} - * @param propertyResolver {@link PropertyResolver} - * @param beanName Bean name - */ - public static void registerGlobalNacosProperties(Map globalPropertiesAttributes, - BeanDefinitionRegistry registry, - PropertyResolver propertyResolver, - String beanName) { - Properties globalProperties = resolveProperties(globalPropertiesAttributes, propertyResolver); - registerSingleton(registry, beanName, globalProperties); - } - - public static void registerNacosApplicationContextHolder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, ApplicationContextHolder.BEAN_NAME, - ApplicationContextHolder.class); - } - - public static void registerNacosConfigPropertiesBindingPostProcessor(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME, - NacosConfigurationPropertiesBindingPostProcessor.class); - } - - public static void registerNacosConfigListenerMethodProcessor(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NacosConfigListenerMethodProcessor.BEAN_NAME, - NacosConfigListenerMethodProcessor.class); - } - - public static void registerNacosPropertySourcePostProcessor(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NacosPropertySourcePostProcessor.BEAN_NAME, - NacosPropertySourcePostProcessor.class); - } - - public static void registerAnnotationNacosPropertySourceBuilder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, AnnotationNacosPropertySourceBuilder.BEAN_NAME, - AnnotationNacosPropertySourceBuilder.class); - } - - public static void registerXmlNacosPropertySourceBuilder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, XmlNacosPropertySourceBuilder.BEAN_NAME, - XmlNacosPropertySourceBuilder.class); - } - - public static void registerNacosConfigListenerExecutor(BeanDefinitionRegistry registry, Environment environment) { - final String beanName = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME; - if (registry instanceof BeanFactory && ((BeanFactory) registry).containsBean(beanName)) { - return; - } - ExecutorService nacosConfigListenerExecutor = buildNacosConfigListenerExecutor(environment); - registerSingleton(registry, beanName, nacosConfigListenerExecutor); - } - - private static ExecutorService buildNacosConfigListenerExecutor(Environment environment) { - int parallelism = getParallelism(environment); - return Executors.newFixedThreadPool(parallelism, new ThreadFactory() { - private final AtomicInteger threadNumber = new AtomicInteger(1); - - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r); - thread.setName("NacosConfigListener-ThreadPool-" + threadNumber.getAndIncrement()); - return thread; - } - }); - } - - private static int getParallelism(Environment environment) { - int parallelism = environment.getProperty(NACOS_CONFIG_LISTENER_PARALLELISM, int.class, - DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM); - return parallelism < 1 ? DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM : parallelism; - } - - public static void registerNacosValueAnnotationBeanPostProcessor(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NacosValueAnnotationBeanPostProcessor.BEAN_NAME, - NacosValueAnnotationBeanPostProcessor.class); - } - - /** - * Register Nacos Common Beans - * - * @param registry {@link BeanDefinitionRegistry} - */ - public static void registerNacosCommonBeans(BeanDefinitionRegistry registry) { - // Register NacosApplicationContextHolder Bean - registerNacosApplicationContextHolder(registry); - // Register AnnotationNacosInjectedBeanPostProcessor Bean - registerAnnotationNacosInjectedBeanPostProcessor(registry); - } - - /** - * Register Nacos Config Beans - * - * @param registry {@link BeanDefinitionRegistry} - * @param environment {@link Environment} - */ - public static void registerNacosConfigBeans(BeanDefinitionRegistry registry, Environment environment) { - // Register PropertySourcesPlaceholderConfigurer Bean - registerPropertySourcesPlaceholderConfigurer(registry); - - registerNacosConfigPropertiesBindingPostProcessor(registry); - - registerNacosConfigListenerMethodProcessor(registry); - - registerNacosPropertySourcePostProcessor(registry); - - registerAnnotationNacosPropertySourceBuilder(registry); - - registerNacosConfigListenerExecutor(registry, environment); - - registerNacosValueAnnotationBeanPostProcessor(registry); - - registerConfigServiceBeanBuilder(registry); - - registerLoggingNacosConfigMetadataEventListener(registry); - } - - /** - * Invokes {@link NacosPropertySourcePostProcessor} - * - * @param beanFactory {@link BeanFactory} - */ - public static void invokeNacosPropertySourcePostProcessor(BeanFactory beanFactory) { - NacosPropertySourcePostProcessor postProcessor = - beanFactory.getBean(NacosPropertySourcePostProcessor.BEAN_NAME, NacosPropertySourcePostProcessor.class); - postProcessor.postProcessBeanFactory((ConfigurableListableBeanFactory) beanFactory); - } - - /** - * Register {@link LoggingNacosConfigMetadataEventListener} Bean - * - * @param registry {@link BeanDefinitionRegistry} - */ - private static void registerLoggingNacosConfigMetadataEventListener(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, LoggingNacosConfigMetadataEventListener.BEAN_NAME, - LoggingNacosConfigMetadataEventListener.class); - } - - /** - * Register Nacos Discovery Beans - * - * @param registry {@link BeanDefinitionRegistry} - */ - public static void registerNacosDiscoveryBeans(BeanDefinitionRegistry registry) { - registerNamingServiceBeanBuilder(registry); - registerNamingMaintainServiceBeanBuilder(registry); - } - - /** - * Register {@link AnnotationNacosInjectedBeanPostProcessor} with - * {@link AnnotationNacosInjectedBeanPostProcessor#BEAN_NAME name} - * - * @param registry {@link BeanDefinitionRegistry} - */ - private static void registerAnnotationNacosInjectedBeanPostProcessor(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME, - AnnotationNacosInjectedBeanPostProcessor.class); - } - - private static void registerConfigServiceBeanBuilder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, ConfigServiceBeanBuilder.BEAN_NAME, ConfigServiceBeanBuilder.class); - } - - private static void registerNamingServiceBeanBuilder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NamingServiceBeanBuilder.BEAN_NAME, NamingServiceBeanBuilder.class); - } - - private static void registerNamingMaintainServiceBeanBuilder(BeanDefinitionRegistry registry) { - registerInfrastructureBeanIfAbsent(registry, NamingMaintainServiceBeanBuilder.BEAN_NAME, NamingMaintainServiceBeanBuilder.class); - } - - /** - * Get Global Properties Bean - * - * @param beanFactory {@link BeanFactory} - * @return Global Properties Bean - * @throws NoSuchBeanDefinitionException if there is no such bean definition - */ - public static Properties getGlobalPropertiesBean(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - return beanFactory.getBean(GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class); - } - - /** - * Get {@link NacosServiceFactory} Bean - * - * @param beanFactory {@link BeanFactory} - * @return {@link NacosServiceFactory} Bean - * @throws NoSuchBeanDefinitionException if there is no such bean definition - */ - public static NacosServiceFactory getNacosServiceFactoryBean(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - if (null == beanFactory) { - return getNacosServiceFactoryBean(); - } - ApplicationContextHolder applicationContextHolder = getApplicationContextHolder(beanFactory); - CacheableEventPublishingNacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory.getSingleton(); - nacosServiceFactory.setApplicationContext(applicationContextHolder.getApplicationContext()); - return nacosServiceFactory; - } - - public static NacosServiceFactory getNacosServiceFactoryBean() throws NoSuchBeanDefinitionException { - return CacheableEventPublishingNacosServiceFactory.getSingleton(); - } - - public static ApplicationContextHolder getApplicationContextHolder(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - return beanFactory.getBean(ApplicationContextHolder.BEAN_NAME, ApplicationContextHolder.class); - } - - /** - * Get {@link Executor} Bean for Nacos Config Listener If Present - * - * @param beanFactory {@link BeanFactory} - * @return {@link Executor} Bean If Present, or null - */ - public static ExecutorService getNacosConfigListenerExecutorIfPresent(BeanFactory beanFactory) { - if (!beanFactory.containsBean(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME)) { - return null; - } - return beanFactory.getBean(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME, ExecutorService.class); - } - - /** - * Get {@link ConfigServiceBeanBuilder} Bean - * - * @param beanFactory {@link BeanFactory} - * @return {@link ConfigServiceBeanBuilder} Bean - * @throws NoSuchBeanDefinitionException if there is no such bean definition - */ - public static ConfigServiceBeanBuilder getConfigServiceBeanBuilder(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - return beanFactory.getBean(ConfigServiceBeanBuilder.BEAN_NAME, ConfigServiceBeanBuilder.class); - } - - /** - * Get {@link NamingServiceBeanBuilder} Bean - * - * @param beanFactory {@link BeanFactory} - * @return {@link NamingServiceBeanBuilder} Bean - * @throws NoSuchBeanDefinitionException if there is no such bean definition - */ - public static NamingServiceBeanBuilder getNamingServiceBeanBuilder(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - return beanFactory.getBean(NamingServiceBeanBuilder.BEAN_NAME, NamingServiceBeanBuilder.class); - } - - /** - * Get {@link NamingMaintainServiceBeanBuilder} Bean - * - * @param beanFactory {@link BeanFactory} - * @return {@link NamingMaintainServiceBeanBuilder} Bean - * @throws NoSuchBeanDefinitionException if there is no such bean definition - */ - public static NamingMaintainServiceBeanBuilder getNamingMaintainServiceBeanBuilder(BeanFactory beanFactory) throws NoSuchBeanDefinitionException { - return beanFactory.getBean(NamingMaintainServiceBeanBuilder.BEAN_NAME, NamingMaintainServiceBeanBuilder.class); - } + /** + * The bean name of {@link PropertySourcesPlaceholderConfigurer} + */ + public static final String PLACEHOLDER_CONFIGURER_BEAN_NAME = "propertySourcesPlaceholderConfigurer"; + + /** + * The bean name of global Nacos {@link Properties} + */ + public static final String GLOBAL_NACOS_PROPERTIES_BEAN_NAME = "globalNacosProperties"; + + /** + * The bean name of global Nacos {@link Properties} for config + */ + public static final String CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME + + "$config"; + + /** + * The bean name of global Nacos {@link Properties} for discovery + */ + public static final String DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME + + "$discovery"; + + /** + * The bean name of global Nacos {@link Properties} for maintain + */ + public static final String MAINTAIN_GLOBAL_NACOS_PROPERTIES_BEAN_NAME = GLOBAL_NACOS_PROPERTIES_BEAN_NAME + + "$maintain"; + + /** + * The bean name of {@link Executor} for Nacos Config Listener + */ + public static final String NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME = "nacosConfigListenerExecutor"; + + /** + * the ignoreResourceNotFound property for propertySourcesPlaceholderConfigurer + */ + public static final String IGNORE_RESOURCE_NOT_FOUND = "ignoreResourceNotFound"; + + /** + * the ignoreUnresolvablePlaceholders property for + * propertySourcesPlaceholderConfigurer + */ + public static final String IGNORE_UNRESOLVABLE_PLACEHOLDERS = "ignoreUnresolvablePlaceholders"; + + /** + * Register an object to be Singleton Bean + * + * @param registry {@link BeanDefinitionRegistry} + * @param beanName bean name + * @param singletonObject singleton object + */ + public static void registerSingleton(BeanDefinitionRegistry registry, String beanName, + Object singletonObject) { + SingletonBeanRegistry beanRegistry = null; + if (registry instanceof SingletonBeanRegistry) { + beanRegistry = (SingletonBeanRegistry) registry; + } + else if (registry instanceof AbstractApplicationContext) { + // Maybe AbstractApplicationContext or its sub-classes + beanRegistry = ((AbstractApplicationContext) registry).getBeanFactory(); + } + // Register Singleton Object if possible + if (beanRegistry != null) { + // Determine in advance whether injected with beans + if (!beanRegistry.containsSingleton(beanName)) { + beanRegistry.registerSingleton(beanName, singletonObject); + } + } + } + + /** + * Register Infrastructure Bean + * + * @param registry {@link BeanDefinitionRegistry} + * @param beanName the name of bean + * @param beanClass the class of bean + * @param constructorArgs the arguments of {@link Constructor} + */ + public static void registerInfrastructureBean(BeanDefinitionRegistry registry, + String beanName, Class beanClass, Object... constructorArgs) { + // Build a BeanDefinition for NacosServiceFactory class + BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder + .rootBeanDefinition(beanClass); + for (Object constructorArg : constructorArgs) { + beanDefinitionBuilder.addConstructorArgValue(constructorArg); + } + // ROLE_INFRASTRUCTURE + beanDefinitionBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + // Register + registry.registerBeanDefinition(beanName, + beanDefinitionBuilder.getBeanDefinition()); + } + + /** + * Register Infrastructure Bean if absent + * + * @param registry {@link BeanDefinitionRegistry} + * @param beanName the name of bean + * @param beanClass the class of bean + * @param constructorArgs the arguments of {@link Constructor} + */ + public static void registerInfrastructureBeanIfAbsent(BeanDefinitionRegistry registry, + String beanName, Class beanClass, Object... constructorArgs) { + if (!isBeanDefinitionPresent(registry, beanName, beanClass) + && !registry.containsBeanDefinition(beanName)) { + registerInfrastructureBean(registry, beanName, beanClass, constructorArgs); + } + } + + /** + * Resolve {@link BeanFactory} from {@link BeanDefinitionRegistry} + * + * @param registry {@link BeanDefinitionRegistry} + * @return {@link BeanFactory} if resolved + */ + public static BeanFactory resolveBeanFactory(BeanDefinitionRegistry registry) { + if (registry instanceof BeanFactory) { + return (BeanFactory) registry; + } + + if (registry instanceof AbstractApplicationContext) { + return ((AbstractApplicationContext) registry).getBeanFactory(); + } + return null; + } + + /** + * Is {@link BeanDefinition} present in {@link BeanDefinitionRegistry} + * + * @param registry {@link BeanDefinitionRegistry} + * @param beanName the name of bean + * @param targetBeanClass the type of bean + * @return If Present , return true + */ + public static boolean isBeanDefinitionPresent(BeanDefinitionRegistry registry, + String beanName, Class targetBeanClass) { + String[] beanNames = BeanUtils.getBeanNames((ListableBeanFactory) registry, + targetBeanClass); + return ArrayUtils.contains(beanNames, beanName); + } + + /** + * Register {@link PropertySourcesPlaceholderConfigurer} Bean + * + * @param registry {@link BeanDefinitionRegistry} + * @param beanFactory {@link BeanFactory} + */ + public static void registerPropertySourcesPlaceholderConfigurer( + BeanDefinitionRegistry registry, BeanFactory beanFactory) { + registerInfrastructureBeanIfAbsent(registry, PLACEHOLDER_CONFIGURER_BEAN_NAME, + PropertySourcesPlaceholderConfigurer.class); + + /* + * If you can't guarantee your old project properties file and config items are + * complete , please setIgnoreUnresolvablePlaceholders setIgnoreResourceNotFound + * is true 。 if not,you may not be able to start the spring container and your + * application + */ + + boolean ignoreResourceNotFound = Boolean + .parseBoolean(System.getProperty(IGNORE_RESOURCE_NOT_FOUND)); + boolean ignoreUnresolvablePlaceholders = Boolean + .parseBoolean(System.getProperty(IGNORE_UNRESOLVABLE_PLACEHOLDERS)); + if (ignoreResourceNotFound || ignoreUnresolvablePlaceholders) { + PropertySourcesPlaceholderConfigurer configurer = (PropertySourcesPlaceholderConfigurer) beanFactory + .getBean(NacosBeanUtils.PLACEHOLDER_CONFIGURER_BEAN_NAME); + if (configurer != null) { + configurer.setIgnoreResourceNotFound(ignoreResourceNotFound); + configurer.setIgnoreUnresolvablePlaceholders( + ignoreUnresolvablePlaceholders); + } + } + } + + /** + * Register Global Nacos Properties Bean with specified name + * + * @param attributes the attributes of Global Nacos Properties may contain + * placeholders + * @param registry {@link BeanDefinitionRegistry} + * @param propertyResolver {@link PropertyResolver} + * @param beanName Bean name + */ + public static void registerGlobalNacosProperties(AnnotationAttributes attributes, + BeanDefinitionRegistry registry, PropertyResolver propertyResolver, + String beanName) { + if (attributes == null) { + return; // Compatible with null + } + AnnotationAttributes globalPropertiesAttributes = attributes + .getAnnotation("globalProperties"); + registerGlobalNacosProperties((Map) globalPropertiesAttributes, registry, + propertyResolver, beanName); + } + + /** + * Register Global Nacos Properties Bean with specified name + * + * @param globalPropertiesAttributes the attributes of Global Nacos Properties may + * contain placeholders + * @param registry {@link BeanDefinitionRegistry} + * @param propertyResolver {@link PropertyResolver} + * @param beanName Bean name + */ + public static void registerGlobalNacosProperties(Map globalPropertiesAttributes, + BeanDefinitionRegistry registry, PropertyResolver propertyResolver, + String beanName) { + Properties globalProperties = resolveProperties(globalPropertiesAttributes, + propertyResolver); + registerSingleton(registry, beanName, globalProperties); + } + + public static void registerNacosApplicationContextHolder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, ApplicationContextHolder.BEAN_NAME, + ApplicationContextHolder.class); + } + + public static void registerNacosConfigPropertiesBindingPostProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME, + NacosConfigurationPropertiesBindingPostProcessor.class); + } + + public static void registerNacosConfigListenerMethodProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + NacosConfigListenerMethodProcessor.BEAN_NAME, + NacosConfigListenerMethodProcessor.class); + } + + public static void registerNacosPropertySourcePostProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + NacosPropertySourcePostProcessor.BEAN_NAME, + NacosPropertySourcePostProcessor.class); + } + + public static void registerAnnotationNacosPropertySourceBuilder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + AnnotationNacosPropertySourceBuilder.BEAN_NAME, + AnnotationNacosPropertySourceBuilder.class); + } + + public static void registerXmlNacosPropertySourceBuilder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + XmlNacosPropertySourceBuilder.BEAN_NAME, + XmlNacosPropertySourceBuilder.class); + } + + public static void registerNacosConfigListenerExecutor( + BeanDefinitionRegistry registry, Environment environment) { + final String beanName = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME; + if (registry instanceof BeanFactory + && ((BeanFactory) registry).containsBean(beanName)) { + return; + } + ExecutorService nacosConfigListenerExecutor = buildNacosConfigListenerExecutor( + environment); + registerSingleton(registry, beanName, nacosConfigListenerExecutor); + } + + private static ExecutorService buildNacosConfigListenerExecutor( + Environment environment) { + int parallelism = getParallelism(environment); + return Executors.newFixedThreadPool(parallelism, new ThreadFactory() { + private final AtomicInteger threadNumber = new AtomicInteger(1); + + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r); + thread.setName("NacosConfigListener-ThreadPool-" + + threadNumber.getAndIncrement()); + return thread; + } + }); + } + + private static int getParallelism(Environment environment) { + int parallelism = environment.getProperty(NACOS_CONFIG_LISTENER_PARALLELISM, + int.class, DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM); + return parallelism < 1 ? DEFAULT_NACOS_CONFIG_LISTENER_PARALLELISM : parallelism; + } + + public static void registerNacosValueAnnotationBeanPostProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + NacosValueAnnotationBeanPostProcessor.BEAN_NAME, + NacosValueAnnotationBeanPostProcessor.class); + } + + public static void registerSpringValueAnnotationBeanPostProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + SpringValueAnnotationBeanPostProcessor.BEAN_NAME, + SpringValueAnnotationBeanPostProcessor.class); + } + + /** + * Register Nacos Common Beans + * + * @param registry {@link BeanDefinitionRegistry} + */ + public static void registerNacosCommonBeans(BeanDefinitionRegistry registry) { + // Register NacosApplicationContextHolder Bean + registerNacosApplicationContextHolder(registry); + // Register AnnotationNacosInjectedBeanPostProcessor Bean + registerAnnotationNacosInjectedBeanPostProcessor(registry); + } + + /** + * Register Nacos Config Beans + * + * @param registry {@link BeanDefinitionRegistry} + * @param environment {@link Environment} + * @param beanFactory {@link BeanFactory} + */ + public static void registerNacosConfigBeans(BeanDefinitionRegistry registry, + Environment environment, BeanFactory beanFactory) { + // Register PropertySourcesPlaceholderConfigurer Bean + registerPropertySourcesPlaceholderConfigurer(registry, beanFactory); + + registerNacosConfigPropertiesBindingPostProcessor(registry); + + registerNacosConfigListenerMethodProcessor(registry); + + registerNacosPropertySourcePostProcessor(registry); + + registerAnnotationNacosPropertySourceBuilder(registry); + + registerNacosConfigListenerExecutor(registry, environment); + + registerNacosValueAnnotationBeanPostProcessor(registry); + + registerSpringValueAnnotationBeanPostProcessor(registry); + + registerConfigServiceBeanBuilder(registry); + + registerLoggingNacosConfigMetadataEventListener(registry); + } + + /** + * Invokes {@link NacosPropertySourcePostProcessor} + * + * @param beanFactory {@link BeanFactory} + */ + public static void invokeNacosPropertySourcePostProcessor(BeanFactory beanFactory) { + NacosPropertySourcePostProcessor postProcessor = beanFactory.getBean( + NacosPropertySourcePostProcessor.BEAN_NAME, + NacosPropertySourcePostProcessor.class); + postProcessor + .postProcessBeanFactory((ConfigurableListableBeanFactory) beanFactory); + } + + /** + * Register {@link LoggingNacosConfigMetadataEventListener} Bean + * + * @param registry {@link BeanDefinitionRegistry} + */ + private static void registerLoggingNacosConfigMetadataEventListener( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + LoggingNacosConfigMetadataEventListener.BEAN_NAME, + LoggingNacosConfigMetadataEventListener.class); + } + + /** + * Register Nacos Discovery Beans + * + * @param registry {@link BeanDefinitionRegistry} + */ + public static void registerNacosDiscoveryBeans(BeanDefinitionRegistry registry) { + registerNamingServiceBeanBuilder(registry); + registerNamingMaintainServiceBeanBuilder(registry); + } + + /** + * Register {@link AnnotationNacosInjectedBeanPostProcessor} with + * {@link AnnotationNacosInjectedBeanPostProcessor#BEAN_NAME name} + * + * @param registry {@link BeanDefinitionRegistry} + */ + private static void registerAnnotationNacosInjectedBeanPostProcessor( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME, + AnnotationNacosInjectedBeanPostProcessor.class); + } + + private static void registerConfigServiceBeanBuilder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, ConfigServiceBeanBuilder.BEAN_NAME, + ConfigServiceBeanBuilder.class); + } + + private static void registerNamingServiceBeanBuilder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, NamingServiceBeanBuilder.BEAN_NAME, + NamingServiceBeanBuilder.class); + } + + private static void registerNamingMaintainServiceBeanBuilder( + BeanDefinitionRegistry registry) { + registerInfrastructureBeanIfAbsent(registry, + NamingMaintainServiceBeanBuilder.BEAN_NAME, + NamingMaintainServiceBeanBuilder.class); + } + + /** + * Get Global Properties Bean + * + * @param beanFactory {@link BeanFactory} + * @return Global Properties Bean + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + public static Properties getGlobalPropertiesBean(BeanFactory beanFactory) + throws NoSuchBeanDefinitionException { + return beanFactory.getBean(GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class); + } + + /** + * Get {@link NacosServiceFactory} Bean + * + * @param beanFactory {@link BeanFactory} + * @return {@link NacosServiceFactory} Bean + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + public static NacosServiceFactory getNacosServiceFactoryBean(BeanFactory beanFactory) + throws NoSuchBeanDefinitionException { + if (null == beanFactory) { + return getNacosServiceFactoryBean(); + } + ApplicationContextHolder applicationContextHolder = getApplicationContextHolder( + beanFactory); + CacheableEventPublishingNacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory + .getSingleton(); + nacosServiceFactory + .setApplicationContext(applicationContextHolder.getApplicationContext()); + return nacosServiceFactory; + } + + public static NacosServiceFactory getNacosServiceFactoryBean() + throws NoSuchBeanDefinitionException { + return CacheableEventPublishingNacosServiceFactory.getSingleton(); + } + + public static ApplicationContextHolder getApplicationContextHolder( + BeanFactory beanFactory) throws NoSuchBeanDefinitionException { + return beanFactory.getBean(ApplicationContextHolder.BEAN_NAME, + ApplicationContextHolder.class); + } + + /** + * Get {@link Executor} Bean for Nacos Config Listener If Present + * + * @param beanFactory {@link BeanFactory} + * @return {@link Executor} Bean If Present, or null + */ + public static ExecutorService getNacosConfigListenerExecutorIfPresent( + BeanFactory beanFactory) { + if (!beanFactory.containsBean(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME)) { + return null; + } + return beanFactory.getBean(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME, + ExecutorService.class); + } + + /** + * Get {@link ConfigServiceBeanBuilder} Bean + * + * @param beanFactory {@link BeanFactory} + * @return {@link ConfigServiceBeanBuilder} Bean + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + public static ConfigServiceBeanBuilder getConfigServiceBeanBuilder( + BeanFactory beanFactory) throws NoSuchBeanDefinitionException { + return beanFactory.getBean(ConfigServiceBeanBuilder.BEAN_NAME, + ConfigServiceBeanBuilder.class); + } + + /** + * Get {@link NamingServiceBeanBuilder} Bean + * + * @param beanFactory {@link BeanFactory} + * @return {@link NamingServiceBeanBuilder} Bean + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + public static NamingServiceBeanBuilder getNamingServiceBeanBuilder( + BeanFactory beanFactory) throws NoSuchBeanDefinitionException { + return beanFactory.getBean(NamingServiceBeanBuilder.BEAN_NAME, + NamingServiceBeanBuilder.class); + } + + /** + * Get {@link NamingMaintainServiceBeanBuilder} Bean + * + * @param beanFactory {@link BeanFactory} + * @return {@link NamingMaintainServiceBeanBuilder} Bean + * @throws NoSuchBeanDefinitionException if there is no such bean definition + */ + public static NamingMaintainServiceBeanBuilder getNamingMaintainServiceBeanBuilder( + BeanFactory beanFactory) throws NoSuchBeanDefinitionException { + return beanFactory.getBean(NamingMaintainServiceBeanBuilder.BEAN_NAME, + NamingMaintainServiceBeanBuilder.class); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosUtils.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosUtils.java index 095bd79d..d3a59937 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosUtils.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/NacosUtils.java @@ -16,6 +16,20 @@ */ package com.alibaba.nacos.spring.util; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Enumeration; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Pattern; + import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; @@ -24,6 +38,7 @@ import com.alibaba.nacos.api.exception.NacosException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValues; import org.springframework.core.env.Environment; @@ -32,23 +47,14 @@ import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import java.io.IOException; -import java.io.StringReader; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Pattern; - -import static com.alibaba.nacos.api.PropertyKeyConst.*; +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH; +import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static org.springframework.core.annotation.AnnotationUtils.getAnnotation; import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; import static org.springframework.util.StringUtils.hasText; @@ -61,353 +67,381 @@ */ public abstract class NacosUtils { - /** - * Default value of {@link String} attribute for {@link Annotation} - */ - public static final String DEFAULT_STRING_ATTRIBUTE_VALUE = ""; - - /** - * Default value of {@link String} attribute for {@link Annotation} - */ - public static final String DEFAULT_CONFIG_TYPE_VALUE = "properties"; - - /** - * Default value of boolean attribute for {@link Annotation} - */ - public static final boolean DEFAULT_BOOLEAN_ATTRIBUTE_VALUE = false; - - /** - * The separator - */ - public static final String SEPARATOR = "|"; - - /** - * Default timeout for getting Nacos configuration - */ - public static final long DEFAULT_TIMEOUT = Long.getLong("nacos.default.timeout", 5000L); - - private static final Logger logger = LoggerFactory.getLogger(NacosUtils.class); - - /** - * Build The default name of {@link NacosConfigurationProperties @NacosPropertySource} - * - * @param dataId data Id - * @param groupId group Id - * @param properties Nacos Properties - * @return non-null - */ - public static String buildDefaultPropertySourceName(String dataId, String groupId, Map properties) { - return build(dataId, groupId, identify(properties)); - } - - /** - * Generate Id of {@link NacosProperties Nacos Properties annotation} - * - * @param nacosProperties {@link NacosProperties Nacos Properties annotation} - * @return Id - */ - public static String identify(NacosProperties nacosProperties) { - return identify(getAnnotationAttributes(nacosProperties)); - } - - /** - * Generate Id of {@link NacosProperties Nacos Properties} - * - * @param properties {@link Properties Nacos Properties} - * @return Id - */ - - public static String identify(Map properties) { - - String namespace = (String) properties.get(NAMESPACE); - String serverAddress = (String) properties.get(SERVER_ADDR); - String contextPath = (String) properties.get(CONTEXT_PATH); - String clusterName = (String) properties.get(CLUSTER_NAME); - String endpoint = (String) properties.get(ENDPOINT); - String accessKey = (String) properties.get(ACCESS_KEY); - String secretKey = (String) properties.get(SECRET_KEY); - String encode = (String) properties.get(ENCODE); - - return build(namespace, clusterName, serverAddress, contextPath, endpoint, accessKey, secretKey, encode); - - } - - private static String build(Object... values) { - StringBuilder stringBuilder = new StringBuilder(); - - for (Object value : values) { - - String stringValue = value == null ? null : String.valueOf(value); - if (StringUtils.hasText(stringValue)) { - stringBuilder.append(stringValue); - } - stringBuilder.append(SEPARATOR); - } - - return stringBuilder.toString(); - } - - /** - * Is {@link NacosProperties @NacosProperties} with default attribute values. - * - * @param nacosProperties {@link NacosProperties @NacosProperties} - * @return If default values , return true,or false - */ - public static boolean isDefault(final NacosProperties nacosProperties) { - - final List records = new LinkedList(); - - ReflectionUtils.doWithMethods(nacosProperties.annotationType(), new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0) { - Object defaultValue = method.getDefaultValue(); - if (defaultValue != null) { - try { - Object returnValue = method.invoke(nacosProperties); - if (!defaultValue.equals(returnValue)) { - records.add(returnValue); - } - } catch (Exception e) { - } - } - } - } - }); - - return records.isEmpty(); - } - - public static String readTypeFromDataId(String dataId) { - if (StringUtils.isEmpty(dataId)) { - return dataId; - } - int index = dataId.lastIndexOf("."); - return index != -1 ? dataId.substring(index + 1) : ""; - } - - public static String readFromEnvironment(String label, Environment environment) { - return environment.resolvePlaceholders(label); - } - - public static PropertyValues resolvePropertyValues(Object bean, String content, String type) { - return resolvePropertyValues(bean, "", "", "", content, type); - } - - public static PropertyValues resolvePropertyValues(Object bean, final String prefix, String dataId, String groupId, String content, String type) { - final Properties configProperties = toProperties(dataId, groupId, content, type); - final MutablePropertyValues propertyValues = new MutablePropertyValues(); - ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - String propertyName = NacosUtils.resolvePropertyName(field); - propertyName = StringUtils.isEmpty(prefix) ? propertyName : prefix + "." + propertyName; - if (hasText(propertyName)) { - // If it is a map, the data will not be fetched - // fix issue #91 - if (Collection.class.isAssignableFrom(field.getType()) || - field.getType().isAssignableFrom(Map.class)) { - bindContainer(prefix, propertyName, configProperties, propertyValues); - return; - } - if (configProperties.containsKey(propertyName)) { - String propertyValue = configProperties.getProperty(propertyName); - propertyValues.add(field.getName(), propertyValue); - } - } - } - }); - return propertyValues; - } - - public static Properties resolveProperties(NacosProperties nacosProperties, PropertyResolver propertyResolver) { - return resolveProperties(nacosProperties, propertyResolver, null); - } - - public static Properties resolveProperties(NacosProperties nacosProperties, PropertyResolver propertyResolver, - Properties defaultProperties) { - - Map attributes = getAnnotationAttributes(nacosProperties); - - return resolveProperties(attributes, propertyResolver, defaultProperties); - - } - - /** - * {@link #resolveProperties(Map, PropertyResolver) Resolve} placeholders of {@link NacosProperties @NacosProperties}'s attributes via specified - * {@link PropertyResolver} if present, or try to {@link #merge(Properties, Properties) merge} from - * default properties - * - * @param attributes {@link NacosProperties @NacosProperties}'s attributes - * @param propertyResolver the resolver of properties' placeholder - * @param defaultProperties default properties - * @return a new resolved {@link Properties} properties - * @see #resolveProperties(Map, PropertyResolver) - */ - public static Properties resolveProperties(Map attributes, PropertyResolver propertyResolver, - Properties defaultProperties) { - - if (CollectionUtils.isEmpty(attributes)) { - return defaultProperties; - } - - Properties resolveProperties = resolveProperties(attributes, propertyResolver); - - merge(resolveProperties, defaultProperties); - - return resolveProperties; - } - - - /** - * Resolve placeholders of properties via specified {@link PropertyResolver} if present - * - * @param properties The properties - * @param propertyResolver {@link PropertyResolver} instance, for instance, {@link Environment} - * @return a new instance of {@link Properties} after resolving. - */ - public static Properties resolveProperties(Map properties, PropertyResolver propertyResolver) { - PropertiesPlaceholderResolver propertiesPlaceholderResolver = new PropertiesPlaceholderResolver(propertyResolver); - return propertiesPlaceholderResolver.resolve(properties); - } - - /** - * Merge Nacos Properties If any property from target properties is absent - * - * @param targetProperties {@link Properties target Properties} - * @param sourceProperties {@link Properties source Properties} - */ - protected static void merge(Properties targetProperties, Properties sourceProperties) { - - if (CollectionUtils.isEmpty(sourceProperties)) { - return; - } - - for (Map.Entry entry : sourceProperties.entrySet()) { - String propertyName = (String) entry.getKey(); - if (!targetProperties.containsKey(propertyName)) { - String propertyValue = (String) entry.getValue(); - targetProperties.setProperty(propertyName, propertyValue); - } - } - - } - - /** - * Get content from {@link ConfigService} via dataId and groupId - * - * @param configService {@link ConfigService} - * @param dataId dataId - * @param groupId groupId - * @return If available , return content , or null - */ - public static String getContent(ConfigService configService, String dataId, String groupId) { - String content = null; - try { - content = configService.getConfig(dataId, groupId, DEFAULT_TIMEOUT); - } catch (NacosException e) { - if (logger.isErrorEnabled()) { - logger.error("Can't get content from dataId : " + dataId + " , groupId : " + groupId, e); - } - } - return content; - } - - /** - * Simple solutions to support {@link Map} or {@link Collection} - * - * @param fieldName property name - * @param configProperties config context - * @param propertyValues {@link MutablePropertyValues} - */ - private static void bindContainer(String prefix, String fieldName, Properties configProperties, MutablePropertyValues propertyValues) { - String regx1 = fieldName + "\\[(.*)\\]"; - String regx2 = fieldName + "\\..*"; - Pattern pattern1 = Pattern.compile(regx1); - Pattern pattern2 = Pattern.compile(regx2); - Enumeration enumeration = (Enumeration) configProperties.propertyNames(); - while (enumeration.hasMoreElements()) { - String s = enumeration.nextElement(); - String name = StringUtils.isEmpty(prefix) ? s : s.replace(prefix + ".", ""); - String value = configProperties.getProperty(s); - if (configProperties.containsKey(fieldName)) { - // for example: list=1,2,3,4,5 will be into here - bindContainer(prefix, fieldName, listToProperties(fieldName, configProperties.getProperty(fieldName)), propertyValues); - } - else if (pattern1.matcher(s).find()) { - propertyValues.add(name, value); - } else if (pattern2.matcher(s).find()) { - int index = s.indexOf('.'); - if (index != -1) { - String key = s.substring(index + 1); - propertyValues.add(name + "[" + key + "]", value); - } - } - } - } - - /** - * convert list=1,2,3,4 to list[0]=1, list[1]=2, list[2]=3, list[3]=4 - * - * @param fieldName fieldName - * @param content content - * @return {@link Properties} - */ - private static Properties listToProperties(String fieldName, String content) { - String[] splits = content.split(","); - int index = 0; - Properties properties = new Properties(); - for (String s : splits) { - properties.put(fieldName + "[" + index + "]", s.trim()); - index ++; - } - return properties; - } - - private static String resolvePropertyName(Field field) { - // Ignore property name if @NacosIgnore present - if (getAnnotation(field, NacosIgnore.class) != null) { - return null; - } - NacosProperty nacosProperty = getAnnotation(field, NacosProperty.class); - // If @NacosProperty present ,return its value() , or field name - return nacosProperty != null ? nacosProperty.value() : field.getName(); - } - - public static Class resolveGenericType(Class declaredClass) { - ParameterizedType parameterizedType = (ParameterizedType) declaredClass.getGenericSuperclass(); - Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - return (Class) actualTypeArguments[0]; - } - - public static Properties toProperties(String text) { - return toProperties(text, "properties"); - } - - public static Properties toProperties(String text, String type) { - return toProperties("", "", text, type); - } - - public static Properties toProperties(String dataId, String group, String text) { - return toProperties(dataId, group, text, "properties"); - } - - /** - * XML configuration parsing to support different schemas - * - * @param dataId config dataId - * @param group config group - * @param text config context - * @param type config type - * @return {@link Properties} - */ - public static Properties toProperties(String dataId, String group, String text, String type) { - type = type.toLowerCase(); - if ("yml".equalsIgnoreCase(type)) { - type = "yaml"; - } - return ConfigParseUtils.toProperties(dataId, group, text, type); - } - + /** + * Default value of {@link String} attribute for {@link Annotation} + */ + public static final String DEFAULT_STRING_ATTRIBUTE_VALUE = ""; + + /** + * Default value of {@link String} attribute for {@link Annotation} + */ + public static final String DEFAULT_CONFIG_TYPE_VALUE = "properties"; + + /** + * Default value of boolean attribute for {@link Annotation} + */ + public static final boolean DEFAULT_BOOLEAN_ATTRIBUTE_VALUE = false; + + /** + * The separator + */ + public static final String SEPARATOR = "|"; + + /** + * Default timeout for getting Nacos configuration + */ + public static final long DEFAULT_TIMEOUT = Long.getLong("nacos.default.timeout", + 5000L); + + private static final Logger logger = LoggerFactory.getLogger(NacosUtils.class); + + /** + * Build The default name of {@link NacosConfigurationProperties @NacosPropertySource} + * + * @param dataId data Id + * @param groupId group Id + * @param properties Nacos Properties + * @return non-null + */ + public static String buildDefaultPropertySourceName(String dataId, String groupId, + Map properties) { + return build(dataId, groupId, identify(properties)); + } + + /** + * Generate Id of {@link NacosProperties Nacos Properties annotation} + * + * @param nacosProperties {@link NacosProperties Nacos Properties annotation} + * @return Id + */ + public static String identify(NacosProperties nacosProperties) { + return identify(getAnnotationAttributes(nacosProperties)); + } + + /** + * Generate Id of {@link NacosProperties Nacos Properties} + * + * @param properties {@link Properties Nacos Properties} + * @return Id + */ + + public static String identify(Map properties) { + + String namespace = (String) properties.get(NAMESPACE); + String serverAddress = (String) properties.get(SERVER_ADDR); + String contextPath = (String) properties.get(CONTEXT_PATH); + String clusterName = (String) properties.get(CLUSTER_NAME); + String endpoint = (String) properties.get(ENDPOINT); + String accessKey = (String) properties.get(ACCESS_KEY); + String secretKey = (String) properties.get(SECRET_KEY); + String encode = (String) properties.get(ENCODE); + + return build(namespace, clusterName, serverAddress, contextPath, endpoint, + accessKey, secretKey, encode); + + } + + private static String build(Object... values) { + StringBuilder stringBuilder = new StringBuilder(); + + for (Object value : values) { + + String stringValue = value == null ? null : String.valueOf(value); + if (StringUtils.hasText(stringValue)) { + stringBuilder.append(stringValue); + } + stringBuilder.append(SEPARATOR); + } + + return stringBuilder.toString(); + } + + /** + * Is {@link NacosProperties @NacosProperties} with default attribute values. + * + * @param nacosProperties {@link NacosProperties @NacosProperties} + * @return If default values , return true,or false + */ + public static boolean isDefault(final NacosProperties nacosProperties) { + + final List records = new LinkedList(); + + ReflectionUtils.doWithMethods(nacosProperties.annotationType(), + new ReflectionUtils.MethodCallback() { + @Override + public void doWith(Method method) + throws IllegalArgumentException, IllegalAccessException { + if (Modifier.isPublic(method.getModifiers()) + && method.getParameterTypes().length == 0) { + Object defaultValue = method.getDefaultValue(); + if (defaultValue != null) { + try { + Object returnValue = method.invoke(nacosProperties); + if (!defaultValue.equals(returnValue)) { + records.add(returnValue); + } + } + catch (Exception e) { + } + } + } + } + }); + + return records.isEmpty(); + } + + public static String readTypeFromDataId(String dataId) { + if (StringUtils.isEmpty(dataId)) { + return dataId; + } + int index = dataId.lastIndexOf("."); + return index != -1 ? dataId.substring(index + 1) : ""; + } + + public static String readFromEnvironment(String label, Environment environment) { + return environment.resolvePlaceholders(label); + } + + public static PropertyValues resolvePropertyValues(Object bean, String content, + String type) { + return resolvePropertyValues(bean, "", "", "", content, type); + } + + public static PropertyValues resolvePropertyValues(Object bean, final String prefix, + String dataId, String groupId, String content, String type) { + final Properties configProperties = toProperties(dataId, groupId, content, type); + final MutablePropertyValues propertyValues = new MutablePropertyValues(); + ReflectionUtils.doWithFields(bean.getClass(), + new ReflectionUtils.FieldCallback() { + @Override + public void doWith(Field field) + throws IllegalArgumentException, IllegalAccessException { + String propertyName = NacosUtils.resolvePropertyName(field); + propertyName = StringUtils.isEmpty(prefix) ? propertyName + : prefix + "." + propertyName; + if (hasText(propertyName)) { + // If it is a map, the data will not be fetched + // fix issue #91 + if (Collection.class.isAssignableFrom(field.getType()) + || field.getType().isAssignableFrom(Map.class)) { + bindContainer(prefix, propertyName, configProperties, + propertyValues); + return; + } + if (configProperties.containsKey(propertyName)) { + String propertyValue = configProperties + .getProperty(propertyName); + propertyValues.add(field.getName(), propertyValue); + } + } + } + }); + return propertyValues; + } + + public static Properties resolveProperties(NacosProperties nacosProperties, + PropertyResolver propertyResolver) { + return resolveProperties(nacosProperties, propertyResolver, null); + } + + public static Properties resolveProperties(NacosProperties nacosProperties, + PropertyResolver propertyResolver, Properties defaultProperties) { + + Map attributes = getAnnotationAttributes(nacosProperties); + + return resolveProperties(attributes, propertyResolver, defaultProperties); + + } + + /** + * {@link #resolveProperties(Map, PropertyResolver) Resolve} placeholders of + * {@link NacosProperties @NacosProperties}'s attributes via specified + * {@link PropertyResolver} if present, or try to + * {@link #merge(Properties, Properties) merge} from default properties + * + * @param attributes {@link NacosProperties @NacosProperties}'s attributes + * @param propertyResolver the resolver of properties' placeholder + * @param defaultProperties default properties + * @return a new resolved {@link Properties} properties + * @see #resolveProperties(Map, PropertyResolver) + */ + public static Properties resolveProperties(Map attributes, + PropertyResolver propertyResolver, Properties defaultProperties) { + + if (CollectionUtils.isEmpty(attributes)) { + return defaultProperties; + } + + Properties resolveProperties = resolveProperties(attributes, propertyResolver); + + merge(resolveProperties, defaultProperties); + + return resolveProperties; + } + + /** + * Resolve placeholders of properties via specified {@link PropertyResolver} if + * present + * + * @param properties The properties + * @param propertyResolver {@link PropertyResolver} instance, for instance, + * {@link Environment} + * @return a new instance of {@link Properties} after resolving. + */ + public static Properties resolveProperties(Map properties, + PropertyResolver propertyResolver) { + PropertiesPlaceholderResolver propertiesPlaceholderResolver = new PropertiesPlaceholderResolver( + propertyResolver); + return propertiesPlaceholderResolver.resolve(properties); + } + + /** + * Merge Nacos Properties If any property from target properties is absent + * + * @param targetProperties {@link Properties target Properties} + * @param sourceProperties {@link Properties source Properties} + */ + protected static void merge(Properties targetProperties, + Properties sourceProperties) { + + if (CollectionUtils.isEmpty(sourceProperties)) { + return; + } + + for (Map.Entry entry : sourceProperties.entrySet()) { + String propertyName = (String) entry.getKey(); + if (!targetProperties.containsKey(propertyName)) { + String propertyValue = (String) entry.getValue(); + targetProperties.setProperty(propertyName, propertyValue); + } + } + + } + + /** + * Get content from {@link ConfigService} via dataId and groupId + * + * @param configService {@link ConfigService} + * @param dataId dataId + * @param groupId groupId + * @return If available , return content , or null + */ + public static String getContent(ConfigService configService, String dataId, + String groupId) { + String content = null; + try { + content = configService.getConfig(dataId, groupId, DEFAULT_TIMEOUT); + } + catch (NacosException e) { + if (logger.isErrorEnabled()) { + logger.error("Can't get content from dataId : " + dataId + " , groupId : " + + groupId, e); + } + } + return content; + } + + /** + * Simple solutions to support {@link Map} or {@link Collection} + * + * @param fieldName property name + * @param configProperties config context + * @param propertyValues {@link MutablePropertyValues} + */ + private static void bindContainer(String prefix, String fieldName, + Properties configProperties, MutablePropertyValues propertyValues) { + String regx1 = fieldName + "\\[(.*)\\]"; + String regx2 = fieldName + "\\..*"; + Pattern pattern1 = Pattern.compile(regx1); + Pattern pattern2 = Pattern.compile(regx2); + Enumeration enumeration = (Enumeration) configProperties + .propertyNames(); + while (enumeration.hasMoreElements()) { + String s = enumeration.nextElement(); + String name = StringUtils.isEmpty(prefix) ? s : s.replace(prefix + ".", ""); + String value = configProperties.getProperty(s); + if (configProperties.containsKey(fieldName)) { + // for example: list=1,2,3,4,5 will be into here + bindContainer(prefix, fieldName, listToProperties(fieldName, + configProperties.getProperty(fieldName)), propertyValues); + } + else if (pattern1.matcher(s).find()) { + propertyValues.add(name, value); + } + else if (pattern2.matcher(s).find()) { + int index = s.indexOf('.'); + if (index != -1) { + String key = s.substring(index + 1); + propertyValues.add(name + "[" + key + "]", value); + } + } + } + } + + /** + * convert list=1,2,3,4 to list[0]=1, list[1]=2, list[2]=3, list[3]=4 + * + * @param fieldName fieldName + * @param content content + * @return {@link Properties} + */ + private static Properties listToProperties(String fieldName, String content) { + String[] splits = content.split(","); + int index = 0; + Properties properties = new Properties(); + for (String s : splits) { + properties.put(fieldName + "[" + index + "]", s.trim()); + index++; + } + return properties; + } + + private static String resolvePropertyName(Field field) { + // Ignore property name if @NacosIgnore present + if (getAnnotation(field, NacosIgnore.class) != null) { + return null; + } + NacosProperty nacosProperty = getAnnotation(field, NacosProperty.class); + // If @NacosProperty present ,return its value() , or field name + return nacosProperty != null ? nacosProperty.value() : field.getName(); + } + + public static Class resolveGenericType(Class declaredClass) { + ParameterizedType parameterizedType = (ParameterizedType) declaredClass + .getGenericSuperclass(); + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + return (Class) actualTypeArguments[0]; + } + + public static Properties toProperties(String text) { + return toProperties(text, "properties"); + } + + public static Properties toProperties(String text, String type) { + return toProperties("", "", text, type); + } + + public static Properties toProperties(String dataId, String group, String text) { + return toProperties(dataId, group, text, "properties"); + } + + /** + * XML configuration parsing to support different schemas + * + * @param dataId config dataId + * @param group config group + * @param text config context + * @param type config type + * @return {@link Properties} + */ + public static Properties toProperties(String dataId, String group, String text, + String type) { + type = type.toLowerCase(); + if ("yml".equalsIgnoreCase(type)) { + type = "yaml"; + } + return ConfigParseUtils.toProperties(dataId, group, text, type); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ObjectUtils.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ObjectUtils.java index a5426f5d..553d0e5d 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ObjectUtils.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/ObjectUtils.java @@ -16,34 +16,71 @@ */ package com.alibaba.nacos.spring.util; -import com.alibaba.nacos.api.config.annotation.NacosIgnore; -import org.springframework.util.ReflectionUtils; - import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; +import com.alibaba.nacos.api.config.annotation.NacosIgnore; + +import org.springframework.beans.TypeConverter; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.core.MethodParameter; +import org.springframework.util.ReflectionUtils; + /** * @author liaochuntao * @since 0.3.0 */ -public abstract class ObjectUtils { - - public static void cleanMapOrCollectionField(final Object bean) { - ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { - - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - field.setAccessible(true); - if (field.isAnnotationPresent(NacosIgnore.class)) { - return; - } - Class type = field.getType(); - if (type.isAssignableFrom(Map.class) || Collection.class.isAssignableFrom(type)) { - field.set(bean, null); - } - } - }); - } +public final class ObjectUtils { + + private ObjectUtils() { + } + + public static void cleanMapOrCollectionField(final Object bean) { + ReflectionUtils.doWithFields(bean.getClass(), + new ReflectionUtils.FieldCallback() { + + @Override + public void doWith(Field field) + throws IllegalArgumentException, IllegalAccessException { + field.setAccessible(true); + if (field.isAnnotationPresent(NacosIgnore.class)) { + return; + } + Class type = field.getType(); + if (type.isAssignableFrom(Map.class) + || Collection.class.isAssignableFrom(type)) { + field.set(bean, null); + } + } + }); + } + + public static Object convertIfNecessary(ConfigurableListableBeanFactory beanFactory, + Field field, Object value) { + TypeConverter converter = beanFactory.getTypeConverter(); + return converter.convertIfNecessary(value, field.getType(), field); + } + + public static Object convertIfNecessary(ConfigurableListableBeanFactory beanFactory, + 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; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolver.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolver.java index aee5e7b0..bd5ea273 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolver.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolver.java @@ -16,14 +16,14 @@ */ package com.alibaba.nacos.spring.util; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.env.PropertyResolver; -import org.springframework.util.StringUtils; - import java.lang.annotation.Annotation; import java.util.Map; import java.util.Properties; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.env.PropertyResolver; +import org.springframework.util.StringUtils; + /** * Placeholder Resolver for {@link Properties properties} * @@ -32,42 +32,43 @@ */ public class PropertiesPlaceholderResolver { - private final PropertyResolver propertyResolver; + private final PropertyResolver propertyResolver; - public PropertiesPlaceholderResolver(PropertyResolver propertyResolver) { - this.propertyResolver = propertyResolver; - } + public PropertiesPlaceholderResolver(PropertyResolver propertyResolver) { + this.propertyResolver = propertyResolver; + } - /** - * Resolve placeholders in specified {@link Annotation annotation} - * - * @param annotation {@link Annotation annotation} - * @return Resolved {@link Properties source properties} - */ - public Properties resolve(Annotation annotation) { - Map attributes = AnnotationUtils.getAnnotationAttributes(annotation); - return resolve(attributes); - } + /** + * Resolve placeholders in specified {@link Annotation annotation} + * + * @param annotation {@link Annotation annotation} + * @return Resolved {@link Properties source properties} + */ + public Properties resolve(Annotation annotation) { + Map attributes = AnnotationUtils + .getAnnotationAttributes(annotation); + return resolve(attributes); + } - /** - * Resolve placeholders in specified {@link Map properties} - * - * @param properties {@link Map source properties} - * @return Resolved {@link Properties source properties} - */ - public Properties resolve(Map properties) { - Properties resolvedProperties = new Properties(); - for (Map.Entry entry : properties.entrySet()) { - if (entry.getValue() instanceof CharSequence) { - String key = String.valueOf(entry.getKey()); - String value = String.valueOf(entry.getValue()); - String resolvedValue = propertyResolver.resolvePlaceholders(value); - if (StringUtils.hasText(resolvedValue)) { // set properties if has test - resolvedProperties.setProperty(key, resolvedValue); - } - } - } - return resolvedProperties; - } + /** + * Resolve placeholders in specified {@link Map properties} + * + * @param properties {@link Map source properties} + * @return Resolved {@link Properties source properties} + */ + public Properties resolve(Map properties) { + Properties resolvedProperties = new Properties(); + for (Map.Entry entry : properties.entrySet()) { + if (entry.getValue() instanceof CharSequence) { + String key = String.valueOf(entry.getKey()); + String value = String.valueOf(entry.getValue()); + String resolvedValue = propertyResolver.resolvePlaceholders(value); + if (StringUtils.hasText(resolvedValue)) { // set properties if has test + resolvedProperties.setProperty(key, resolvedValue); + } + } + } + return resolvedProperties; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/Tuple.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/Tuple.java new file mode 100644 index 00000000..5ca83ca8 --- /dev/null +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/Tuple.java @@ -0,0 +1,61 @@ +/* + * 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.util; + +/** + * @author liaochuntao + * @since 0.0.1 + */ +public class Tuple { + + private static final Tuple empty = new Tuple(); + + private A first; + private B second; + + private Tuple() { + } + + ; + + public static Tuple empty() { + return empty; + } + + public static Tuple of(A first, B second) { + Tuple tuple = new Tuple(); + tuple.setFirst(first); + tuple.setSecond(second); + return tuple; + } + + public A getFirst() { + return first; + } + + public void setFirst(A first) { + this.first = first; + } + + public B getSecond() { + return second; + } + + public void setSecond(B second) { + this.second = second; + } +} diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/config/NacosConfigLoader.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/config/NacosConfigLoader.java index 8e8f101d..2395eb4f 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/config/NacosConfigLoader.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/config/NacosConfigLoader.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.spring.util.config; +import java.util.Properties; + import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -23,11 +25,10 @@ import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.NacosUtils; import com.alibaba.nacos.spring.util.PropertiesPlaceholderResolver; + import org.springframework.core.convert.ConversionService; import org.springframework.core.env.ConfigurableEnvironment; -import java.util.Properties; - /** * Nacos Configuration Loader * @@ -36,80 +37,84 @@ */ public class NacosConfigLoader { - private final ConfigurableEnvironment environment; + private final ConfigurableEnvironment environment; - private final ConversionService conversionService; + private final ConversionService conversionService; - private final PropertiesPlaceholderResolver resolver; + private final PropertiesPlaceholderResolver resolver; - private NacosServiceFactory nacosServiceFactory; + private NacosServiceFactory nacosServiceFactory; - private ConfigService configService; + private ConfigService configService; - public NacosConfigLoader(ConfigurableEnvironment environment) { - this.environment = environment; - this.conversionService = environment.getConversionService(); - this.resolver = new PropertiesPlaceholderResolver(environment); - } + public NacosConfigLoader(ConfigurableEnvironment environment) { + this.environment = environment; + this.conversionService = environment.getConversionService(); + this.resolver = new PropertiesPlaceholderResolver(environment); + } - /** - * Load Nacos config vid dataId, groupId and {@link NacosProperties} - * - * @param dataId dataId - * @param groupId groupId - * @param nacosProperties {@link NacosProperties} - * @return Nacos config - * @throws RuntimeException If {@link ConfigService} creating is failed. - */ - public String load(String dataId, String groupId, NacosProperties nacosProperties) throws RuntimeException { - Properties properties = resolver.resolve(nacosProperties); - return load(dataId, groupId, properties); - } + /** + * Load Nacos config vid dataId, groupId and {@link NacosProperties} + * + * @param dataId dataId + * @param groupId groupId + * @param nacosProperties {@link NacosProperties} + * @return Nacos config + * @throws RuntimeException If {@link ConfigService} creating is failed. + */ + public String load(String dataId, String groupId, NacosProperties nacosProperties) + throws RuntimeException { + Properties properties = resolver.resolve(nacosProperties); + return load(dataId, groupId, properties); + } - /** - * Load Nacos config vid dataId, groupId and {@link Properties acos Properties} - * - * @param dataId dataId - * @param groupId groupId - * @param nacosProperties {@link Properties acos Properties} - * @return Nacos config - * @throws RuntimeException If {@link ConfigService} creating is failed. - */ - public String load(String dataId, String groupId, Properties nacosProperties) throws RuntimeException { - try { - configService = nacosServiceFactory != null ? - nacosServiceFactory.createConfigService(nacosProperties) : - NacosFactory.createConfigService(nacosProperties); - } catch (NacosException e) { - throw new RuntimeException("ConfigService can't be created with dataId :" - + dataId + " , groupId : " + groupId + " , properties : " + nacosProperties - , e); - } - return NacosUtils.getContent(configService, dataId, groupId); - } + /** + * Load Nacos config vid dataId, groupId and {@link Properties acos Properties} + * + * @param dataId dataId + * @param groupId groupId + * @param nacosProperties {@link Properties acos Properties} + * @return Nacos config + * @throws RuntimeException If {@link ConfigService} creating is failed. + */ + public String load(String dataId, String groupId, Properties nacosProperties) + throws RuntimeException { + try { + configService = nacosServiceFactory != null + ? nacosServiceFactory.createConfigService(nacosProperties) + : NacosFactory.createConfigService(nacosProperties); + } + catch (NacosException e) { + throw new RuntimeException("ConfigService can't be created with dataId :" + + dataId + " , groupId : " + groupId + " , properties : " + + nacosProperties, e); + } + return NacosUtils.getContent(configService, dataId, groupId); + } - /** - * Load target class object from Nacos config - * - * @param dataId dataId - * @param groupId groupId - * @param nacosProperties {@link NacosProperties} - * @param targetClass target class - * @param target class - * @return target class object - * @throws RuntimeException {@link #load(String, String, NacosProperties)} - * @see #load(String, String, NacosProperties) - */ - public T load(String dataId, String groupId, NacosProperties nacosProperties, Class targetClass) throws RuntimeException { - String config = load(dataId, groupId, nacosProperties); - return conversionService.convert(config, targetClass); - } + /** + * Load target class object from Nacos config + * + * @param dataId dataId + * @param groupId groupId + * @param nacosProperties {@link NacosProperties} + * @param targetClass target class + * @param target class + * @return target class object + * @throws RuntimeException {@link #load(String, String, NacosProperties)} + * @see #load(String, String, NacosProperties) + */ + public T load(String dataId, String groupId, NacosProperties nacosProperties, + Class targetClass) throws RuntimeException { + String config = load(dataId, groupId, nacosProperties); + return conversionService.convert(config, targetClass); + } - public void setNacosServiceFactory(NacosServiceFactory nacosServiceFactory) { - this.nacosServiceFactory = nacosServiceFactory; - } + public void setNacosServiceFactory(NacosServiceFactory nacosServiceFactory) { + this.nacosServiceFactory = nacosServiceFactory; + } - public ConfigService getConfigService() { - return configService; - } + public ConfigService getConfigService() { + return configService; + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/ConfigParseException.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/ConfigParseException.java index 55a15db8..000b596c 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/ConfigParseException.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/ConfigParseException.java @@ -22,7 +22,7 @@ */ class ConfigParseException extends RuntimeException { - ConfigParseException(Throwable cause) { - super(cause); - } + ConfigParseException(Throwable cause) { + super(cause); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultJsonConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultJsonConfigParse.java index 090a6425..8011b181 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultJsonConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultJsonConfigParse.java @@ -16,13 +16,12 @@ */ package com.alibaba.nacos.spring.util.parse; -import com.alibaba.nacos.api.config.ConfigType; -import com.alibaba.nacos.spring.util.AbstractConfigParse; -import com.alibaba.nacos.spring.util.ConfigParse; - import java.util.Map; import java.util.Properties; +import com.alibaba.nacos.api.config.ConfigType; +import com.alibaba.nacos.spring.util.AbstractConfigParse; + import static com.alibaba.nacos.spring.util.parse.DefaultYamlConfigParse.createYaml; /** @@ -31,22 +30,21 @@ */ public class DefaultJsonConfigParse extends AbstractConfigParse { - @Override - public Properties parse(String configText) { - final Properties result = new Properties(); - DefaultYamlConfigParse.process(new DefaultYamlConfigParse.MatchCallback() { - @Override - public void process(Properties properties, Map map) { - result.putAll(properties); - } - }, createYaml(), configText); - return result; - } - - @Override - public String processType() { - return ConfigType.JSON.getType(); - } + @Override + public Properties parse(String configText) { + final Properties result = new Properties(); + DefaultYamlConfigParse.process(new DefaultYamlConfigParse.MatchCallback() { + @Override + public void process(Properties properties, Map map) { + result.putAll(properties); + } + }, createYaml(), configText); + return result; + } + + @Override + public String processType() { + return ConfigType.JSON.getType(); + } } - diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultPropertiesConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultPropertiesConfigParse.java index 4350907d..20e3edf1 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultPropertiesConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultPropertiesConfigParse.java @@ -16,16 +16,16 @@ */ package com.alibaba.nacos.spring.util.parse; +import java.io.IOException; +import java.io.StringReader; +import java.util.Properties; + import com.alibaba.nacos.api.config.ConfigType; import com.alibaba.nacos.spring.util.AbstractConfigParse; -import com.alibaba.nacos.spring.util.ConfigParse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.util.StringUtils; -import java.io.IOException; -import java.io.StringReader; -import java.util.Properties; +import org.springframework.util.StringUtils; /** * @author liaochuntao @@ -33,25 +33,26 @@ */ public class DefaultPropertiesConfigParse extends AbstractConfigParse { - private static final Logger logger = LoggerFactory.getLogger(DefaultPropertiesConfigParse.class); - - @Override - public Properties parse(String configText) { - Properties properties = new Properties(); - try { - if (StringUtils.hasText(configText)) { - properties.load(new StringReader(configText)); - } - } catch (IOException e) { - throw new ConfigParseException(e); - } - return properties; - } - - @Override - public String processType() { - return ConfigType.PROPERTIES.getType(); - } + private static final Logger logger = LoggerFactory + .getLogger(DefaultPropertiesConfigParse.class); + + @Override + public Properties parse(String configText) { + Properties properties = new Properties(); + try { + if (StringUtils.hasText(configText)) { + properties.load(new StringReader(configText)); + } + } + catch (IOException e) { + throw new ConfigParseException(e); + } + return properties; + } + + @Override + public String processType() { + return ConfigType.PROPERTIES.getType(); + } } - diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultXmlConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultXmlConfigParse.java index 390ac1cc..c20d3fc5 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultXmlConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultXmlConfigParse.java @@ -16,21 +16,23 @@ */ package com.alibaba.nacos.spring.util.parse; +import java.io.ByteArrayInputStream; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.xml.parsers.DocumentBuilderFactory; + import com.alibaba.nacos.api.config.ConfigType; import com.alibaba.nacos.spring.util.AbstractConfigParse; -import org.springframework.util.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.ByteArrayInputStream; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; +import org.springframework.util.StringUtils; /* @@ -74,79 +76,87 @@ */ public class DefaultXmlConfigParse extends AbstractConfigParse { - private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + private DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - @Override - public Properties parse(String configText) { - Properties properties = new Properties(); - try { - Document document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(configText.getBytes("UTF-8"))); - Element root = document.getDocumentElement(); - Map map = new LinkedHashMap(8); - recursionXmlToMap(map, root); - mapToProperties("", properties, map); - } catch (Exception e) { - throw new ConfigParseException(e); - } - return properties; - } + @Override + public Properties parse(String configText) { + Properties properties = new Properties(); + try { + Document document = factory.newDocumentBuilder() + .parse(new ByteArrayInputStream(configText.getBytes("UTF-8"))); + Element root = document.getDocumentElement(); + Map map = new LinkedHashMap(8); + recursionXmlToMap(map, root); + mapToProperties("", properties, map); + } + catch (Exception e) { + throw new ConfigParseException(e); + } + return properties; + } - private void recursionXmlToMap(Map outMap, Element element) { - NodeList nodeList = element.getChildNodes(); - String name = element.getNodeName(); - if (nodeList.getLength() == 1 && !nodeList.item(0).hasChildNodes()) { - addData(outMap, name, element.getTextContent()); - } else { - Map innerMap = new LinkedHashMap(1); - int length = nodeList.getLength(); - for (int i = 0; i < length; i ++) { - Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element tElement = (Element) node; - recursionXmlToMap(innerMap, tElement); - } - } - addData(outMap, name, innerMap); - } - } + private void recursionXmlToMap(Map outMap, Element element) { + NodeList nodeList = element.getChildNodes(); + String name = element.getNodeName(); + if (nodeList.getLength() == 1 && !nodeList.item(0).hasChildNodes()) { + addData(outMap, name, element.getTextContent()); + } + else { + Map innerMap = new LinkedHashMap(1); + int length = nodeList.getLength(); + for (int i = 0; i < length; i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element tElement = (Element) node; + recursionXmlToMap(innerMap, tElement); + } + } + addData(outMap, name, innerMap); + } + } - private void addData(Map map, String key, Object data) { - if (map.containsKey(key)) { - if (map.get(key) instanceof List) { - ((List) map.get(key)).add(data); - } else { - List list = new LinkedList(); - list.add(map.get(key)); - map.put(key, list); - } - } else { - map.put(key, data); - } - } + private void addData(Map map, String key, Object data) { + if (map.containsKey(key)) { + if (map.get(key) instanceof List) { + ((List) map.get(key)).add(data); + } + else { + List list = new LinkedList(); + list.add(map.get(key)); + map.put(key, list); + } + } + else { + map.put(key, data); + } + } - private void mapToProperties(String prefixName, Properties properties, Object data) { - if (data instanceof List) { - List list = (List) data; - for (int i = 0; i < list.size(); i ++) { - int lastIndex = prefixName.lastIndexOf('.'); - String preName = prefixName.substring(0, lastIndex); - String lastName = prefixName.substring(lastIndex); - mapToProperties(preName + "[" + i + "]", properties, list.get(i)); - } - } else if (data instanceof Map) { - Map map = (Map) data; - for (Map.Entry entry : map.entrySet()) { - String tmpPrefix = StringUtils.isEmpty(prefixName) ? entry.getKey() : prefixName + "." + entry.getKey(); - mapToProperties(tmpPrefix, properties, entry.getValue()); - } - } else { - properties.setProperty(prefixName, String.valueOf(data)); - } - } + private void mapToProperties(String prefixName, Properties properties, Object data) { + if (data instanceof List) { + List list = (List) data; + for (int i = 0; i < list.size(); i++) { + int lastIndex = prefixName.lastIndexOf('.'); + String preName = prefixName.substring(0, lastIndex); + String lastName = prefixName.substring(lastIndex); + mapToProperties(preName + "[" + i + "]", properties, list.get(i)); + } + } + else if (data instanceof Map) { + Map map = (Map) data; + for (Map.Entry entry : map.entrySet()) { + String tmpPrefix = StringUtils.isEmpty(prefixName) ? entry.getKey() + : prefixName + "." + entry.getKey(); + mapToProperties(tmpPrefix, properties, entry.getValue()); + } + } + else { + properties.setProperty(prefixName, String.valueOf(data)); + } + } - @Override - public String processType() { - return ConfigType.XML.getType(); - } + @Override + public String processType() { + return ConfigType.XML.getType(); + } } diff --git a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultYamlConfigParse.java b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultYamlConfigParse.java index c1d4209d..b827c153 100644 --- a/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultYamlConfigParse.java +++ b/nacos-spring-context/src/main/java/com/alibaba/nacos/spring/util/parse/DefaultYamlConfigParse.java @@ -16,9 +16,16 @@ */ package com.alibaba.nacos.spring.util.parse; +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + import com.alibaba.nacos.api.config.ConfigType; import com.alibaba.nacos.spring.util.AbstractConfigParse; -import com.alibaba.nacos.spring.util.ConfigParse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; @@ -26,179 +33,181 @@ import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.parser.ParserException; -import java.util.AbstractMap; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - /** * @author liaochuntao * @since 0.3.0 */ public class DefaultYamlConfigParse extends AbstractConfigParse { - protected static final Logger logger = LoggerFactory.getLogger(DefaultYamlConfigParse.class); - - protected static Yaml createYaml() { - return new Yaml(new MapAppenderConstructor()); - } - - @Override - public Properties parse(String configText) { - final Properties result = new Properties(); - process(new MatchCallback() { - @Override - public void process(Properties properties, Map map) { - result.putAll(properties); - } - }, createYaml(), configText); - return result; - } - - @Override - public String processType() { - return ConfigType.YAML.getType(); - } - - protected static boolean process(MatchCallback callback, Yaml yaml, String content) { - int count = 0; - if (logger.isDebugEnabled()) { - logger.debug("Loading from YAML: " + content); - } - for (Object object : yaml.loadAll(content)) { - if (object != null && process(asMap(object), callback)) { - count++; - } - } - if (logger.isDebugEnabled()) { - logger.debug("Loaded " + count + " document" + (count > 1 ? "s" : "") + " from YAML resource: " + content); - } - return (count > 0); - } - - protected static boolean process(Map map, MatchCallback callback) { - Properties properties = new Properties(); - properties.putAll(getFlattenedMap(map)); - - if (logger.isDebugEnabled()) { - logger.debug("Merging document (no matchers set): " + map); - } - callback.process(properties, map); - return true; - } - - @SuppressWarnings("unchecked") - protected static Map asMap(Object object) { - // YAML can have numbers as keys - Map result = new LinkedHashMap(); - if (!(object instanceof Map)) { - // A document can be a text literal - result.put("document", object); - return result; - } - - Map map = (Map) object; - for (Map.Entry entry : map.entrySet()) { - Object key = entry.getKey(); - Object value = entry.getValue(); - if (value instanceof Map) { - value = asMap(value); - } - if (key instanceof CharSequence) { - result.put(key.toString(), value); - } - else { - result.put("[" + key.toString() + "]", value); - } - } - return result; - } - - protected static Map getFlattenedMap(Map source) { - Map result = new LinkedHashMap(); - buildFlattenedMap(result, source, null); - return result; - } - - protected static void buildFlattenedMap(Map result, Map source, String path) { - for (Map.Entry entry : source.entrySet()) { - String key = entry.getKey(); - if (!com.alibaba.nacos.client.utils.StringUtils.isBlank(path)) { - if (key.startsWith("[")) { - key = path + key; - } else { - key = path + '.' + key; - } - } - Object value = entry.getValue(); - if (value instanceof String) { - result.put(key, value); - } else if (value instanceof Map) { - // Need a compound key - @SuppressWarnings("unchecked") - Map map = (Map) value; - buildFlattenedMap(result, map, key); - } else if (value instanceof Collection) { - // Need a compound key - @SuppressWarnings("unchecked") - Collection collection = (Collection) value; - int count = 0; - for (Object object : collection) { - buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key); - } - } else { - result.put(key, (value != null ? value.toString() : "")); - } - } - } - - protected interface MatchCallback { - - /** - * Put Map to Properties - * - * @param properties {@link Properties} - * @param map {@link Map} - */ - void process(Properties properties, Map map); - } - - protected static class MapAppenderConstructor extends Constructor { - - MapAppenderConstructor() { - super(); - } - - @Override - protected Map constructMapping(MappingNode node) { - try { - return super.constructMapping(node); - } catch (IllegalStateException ex) { - throw new ParserException("while parsing MappingNode", node.getStartMark(), ex.getMessage(), node.getEndMark()); - } - } - - @Override - protected Map createDefaultMap() { - final Map delegate = super.createDefaultMap(); - return new AbstractMap() { - @Override - public Object put(Object key, Object value) { - if (delegate.containsKey(key)) { - throw new IllegalStateException("Duplicate key: " + key); - } - return delegate.put(key, value); - } - - @Override - public Set> entrySet() { - return delegate.entrySet(); - } - }; - } - } + protected static final Logger logger = LoggerFactory + .getLogger(DefaultYamlConfigParse.class); + + protected static Yaml createYaml() { + return new Yaml(new MapAppenderConstructor()); + } + + @Override + public Properties parse(String configText) { + final Properties result = new Properties(); + process(new MatchCallback() { + @Override + public void process(Properties properties, Map map) { + result.putAll(properties); + } + }, createYaml(), configText); + return result; + } + + @Override + public String processType() { + return ConfigType.YAML.getType(); + } + + protected static boolean process(MatchCallback callback, Yaml yaml, String content) { + int count = 0; + if (logger.isDebugEnabled()) { + logger.debug("Loading from YAML: " + content); + } + for (Object object : yaml.loadAll(content)) { + if (object != null && process(asMap(object), callback)) { + count++; + } + } + if (logger.isDebugEnabled()) { + logger.debug("Loaded " + count + " document" + (count > 1 ? "s" : "") + + " from YAML resource: " + content); + } + return (count > 0); + } + + protected static boolean process(Map map, MatchCallback callback) { + Properties properties = new Properties(); + properties.putAll(getFlattenedMap(map)); + + if (logger.isDebugEnabled()) { + logger.debug("Merging document (no matchers set): " + map); + } + callback.process(properties, map); + return true; + } + + @SuppressWarnings("unchecked") + protected static Map asMap(Object object) { + // YAML can have numbers as keys + Map result = new LinkedHashMap(); + if (!(object instanceof Map)) { + // A document can be a text literal + result.put("document", object); + return result; + } + + Map map = (Map) object; + for (Map.Entry entry : map.entrySet()) { + Object key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof Map) { + value = asMap(value); + } + if (key instanceof CharSequence) { + result.put(key.toString(), value); + } + else { + result.put("[" + key.toString() + "]", value); + } + } + return result; + } + + protected static Map getFlattenedMap(Map source) { + Map result = new LinkedHashMap(); + buildFlattenedMap(result, source, null); + return result; + } + + protected static void buildFlattenedMap(Map result, + Map source, String path) { + for (Map.Entry entry : source.entrySet()) { + String key = entry.getKey(); + if (!com.alibaba.nacos.client.utils.StringUtils.isBlank(path)) { + if (key.startsWith("[")) { + key = path + key; + } + else { + key = path + '.' + key; + } + } + Object value = entry.getValue(); + if (value instanceof String) { + result.put(key, value); + } + else if (value instanceof Map) { + // Need a compound key + @SuppressWarnings("unchecked") + Map map = (Map) value; + buildFlattenedMap(result, map, key); + } + else if (value instanceof Collection) { + // Need a compound key + @SuppressWarnings("unchecked") + Collection collection = (Collection) value; + int count = 0; + for (Object object : collection) { + buildFlattenedMap(result, + Collections.singletonMap("[" + (count++) + "]", object), key); + } + } + else { + result.put(key, (value != null ? value.toString() : "")); + } + } + } + + protected interface MatchCallback { + + /** + * Put Map to Properties + * + * @param properties {@link Properties} + * @param map {@link Map} + */ + void process(Properties properties, Map map); + } + + protected static class MapAppenderConstructor extends Constructor { + + MapAppenderConstructor() { + super(); + } + + @Override + protected Map constructMapping(MappingNode node) { + try { + return super.constructMapping(node); + } + catch (IllegalStateException ex) { + throw new ParserException("while parsing MappingNode", + node.getStartMark(), ex.getMessage(), node.getEndMark()); + } + } + + @Override + protected Map createDefaultMap() { + final Map delegate = super.createDefaultMap(); + return new AbstractMap() { + @Override + public Object put(Object key, Object value) { + if (delegate.containsKey(key)) { + throw new IllegalStateException("Duplicate key: " + key); + } + return delegate.put(key, value); + } + + @Override + public Set> entrySet() { + return delegate.entrySet(); + } + }; + } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessorTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessorTest.java index f7642e8b..93236481 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessorTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/beans/factory/annotation/AnnotationNacosInjectedBeanPostProcessorTest.java @@ -28,6 +28,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; @@ -36,7 +37,9 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.*; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.CONTENT; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; /** * {@link AnnotationNacosInjectedBeanPostProcessor} Test @@ -45,61 +48,60 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - TestConfiguration.class, - ConfigServiceBeanBuilder.class, - NamingServiceBeanBuilder.class, - AnnotationNacosInjectedBeanPostProcessor.class, - AnnotationNacosInjectedBeanPostProcessorTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, AnnotationNacosInjectedBeanPostProcessorTest.class}) +@ContextConfiguration(classes = { TestConfiguration.class, ConfigServiceBeanBuilder.class, + NamingServiceBeanBuilder.class, AnnotationNacosInjectedBeanPostProcessor.class, + AnnotationNacosInjectedBeanPostProcessorTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + AnnotationNacosInjectedBeanPostProcessorTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) -public class AnnotationNacosInjectedBeanPostProcessorTest extends AbstractNacosHttpServerTestExecutionListener { +public class AnnotationNacosInjectedBeanPostProcessorTest + extends AbstractNacosHttpServerTestExecutionListener { - @Bean(name = ApplicationContextHolder.BEAN_NAME) - public ApplicationContextHolder applicationContextHolder(ApplicationContext applicationContext) { - ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); - applicationContextHolder.setApplicationContext(applicationContext); - return applicationContextHolder; - } + @Bean(name = ApplicationContextHolder.BEAN_NAME) + public ApplicationContextHolder applicationContextHolder( + ApplicationContext applicationContext) { + ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); + applicationContextHolder.setApplicationContext(applicationContext); + return applicationContextHolder; + } - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) - private ConfigService configService2; + @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) + private ConfigService configService2; - @NacosInjected(properties = @NacosProperties(encode = "GBK")) - private ConfigService configService3; + @NacosInjected(properties = @NacosProperties(encode = "GBK")) + private ConfigService configService3; - @NacosInjected - private NamingService namingService; + @NacosInjected + private NamingService namingService; - @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) - private NamingService namingService2; + @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) + private NamingService namingService2; - @NacosInjected(properties = @NacosProperties(encode = "GBK")) - private NamingService namingService3; + @NacosInjected(properties = @NacosProperties(encode = "GBK")) + private NamingService namingService3; - @Test - public void testInjection() { + @Test + public void testInjection() { - Assert.assertEquals(configService, configService2); - Assert.assertNotEquals(configService2, configService3); + Assert.assertEquals(configService, configService2); + Assert.assertNotEquals(configService2, configService3); - Assert.assertEquals(namingService, namingService2); - Assert.assertNotEquals(namingService2, namingService3); - } + Assert.assertEquals(namingService, namingService2); + Assert.assertNotEquals(namingService2, namingService3); + } - @Test - public void test() throws NacosException { - configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); - Assert.assertEquals(CONTENT, configService.getConfig(DATA_ID, GROUP_ID, 5000)); - } + @Test + public void test() throws NacosException { + configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); + Assert.assertEquals(CONTENT, configService.getConfig(DATA_ID, GROUP_ID, 5000)); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/config/NacosNamespaceHandlerTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/config/NacosNamespaceHandlerTest.java index 46852e08..c1ff4ed7 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/config/NacosNamespaceHandlerTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/config/NacosNamespaceHandlerTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; @@ -27,6 +30,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -35,11 +39,10 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; -import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.*; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.GROUP_ID_PARAM_NAME; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; /** @@ -51,45 +54,45 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "classpath:/META-INF/nacos-context.xml", - "classpath:/META-INF/nacos-property-source.xml" -}) +@ContextConfiguration(locations = { "classpath:/META-INF/nacos-context.xml", + "classpath:/META-INF/nacos-property-source.xml" }) @DirtiesContext -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosNamespaceHandlerTest.class}) -public class NacosNamespaceHandlerTest extends AbstractNacosHttpServerTestExecutionListener { +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosNamespaceHandlerTest.class }) +public class NacosNamespaceHandlerTest + extends AbstractNacosHttpServerTestExecutionListener { - @Autowired - private User user; + @Autowired + private User user; - @Override - protected String getServerAddressPropertyName() { - return "nacos.server-addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "nacos.server-addr"; + } - @Override - protected void init(EmbeddedNacosHttpServer server) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, "user"); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, "id=" + 1 + "\nname=mercyblitz"); - server.initConfig(config); - } + @Override + protected void init(EmbeddedNacosHttpServer server) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, "user"); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, "id=" + 1 + "\nname=mercyblitz"); + server.initConfig(config); + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @Test - public void testGetConfig() throws Exception { - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); - Assert.assertEquals("9527", configService.getConfig(DATA_ID, DEFAULT_GROUP, 5000)); - } + @Test + public void testGetConfig() throws Exception { + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); + Assert.assertEquals("9527", + configService.getConfig(DATA_ID, DEFAULT_GROUP, 5000)); + } - @Test - public void testUser() { - Assert.assertEquals(Long.valueOf(1L), user.getId()); - Assert.assertEquals("mercyblitz", user.getName()); - } + @Test + public void testUser() { + Assert.assertEquals(Long.valueOf(1L), user.getId()); + Assert.assertEquals("mercyblitz", user.getName()); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrarTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrarTest.java index 9ac7d48e..f1068064 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrarTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/NacosBeanDefinitionRegistrarTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.context.annotation; +import java.util.Properties; +import java.util.concurrent.ExecutorService; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -30,14 +33,13 @@ import com.alibaba.nacos.spring.context.properties.config.NacosConfigurationPropertiesBindingPostProcessor; import com.alibaba.nacos.spring.core.env.AnnotationNacosPropertySourceBuilder; import com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor; -import com.alibaba.nacos.spring.factory.CacheableEventPublishingNacosServiceFactory; -import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; import com.alibaba.nacos.spring.test.Config; import com.alibaba.nacos.spring.util.NacosBeanUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; @@ -49,9 +51,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.Properties; -import java.util.concurrent.ExecutorService; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; import static com.alibaba.nacos.spring.util.NacosBeanUtils.NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME; @@ -64,97 +63,97 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosBeanDefinitionRegistrarTest.class, -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosBeanDefinitionRegistrarTest.class}) +@ContextConfiguration(classes = { NacosBeanDefinitionRegistrarTest.class, }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosBeanDefinitionRegistrarTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) @EnableNacosConfig @EnableNacosDiscovery -public class NacosBeanDefinitionRegistrarTest extends AbstractNacosHttpServerTestExecutionListener { - - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } - - @Bean - public Config config() { - return new Config(); - } - - @Autowired - @Qualifier(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties globalProperties; - - @Autowired - @Qualifier(NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties configGlobalProperties; - @Autowired - @Qualifier(NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties discoveryGlobalProperties; - - @Autowired - @Qualifier(AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME) - private AnnotationNacosInjectedBeanPostProcessor annotationNacosInjectedBeanPostProcessor; - - @Autowired - @Qualifier(PLACEHOLDER_CONFIGURER_BEAN_NAME) - private PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer; - - @Autowired - @Qualifier(NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME) - private NacosConfigurationPropertiesBindingPostProcessor nacosConfigurationPropertiesBindingPostProcessor; - - @Autowired - @Qualifier(NacosConfigListenerMethodProcessor.BEAN_NAME) - private NacosConfigListenerMethodProcessor nacosConfigListenerMethodProcessor; - - @Autowired - @Qualifier(NacosPropertySourcePostProcessor.BEAN_NAME) - private NacosPropertySourcePostProcessor nacosPropertySourcePostProcessor; - - @Autowired - @Qualifier(AnnotationNacosPropertySourceBuilder.BEAN_NAME) - private AnnotationNacosPropertySourceBuilder annotationNacosPropertySourceBuilder; - - @Autowired - @Qualifier(NacosValueAnnotationBeanPostProcessor.BEAN_NAME) - private NacosValueAnnotationBeanPostProcessor nacosValueAnnotationBeanPostProcessor; - - @Autowired - @Qualifier(ConfigServiceBeanBuilder.BEAN_NAME) - private ConfigServiceBeanBuilder configServiceBeanBuilder; - - @Autowired - @Qualifier(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) - private ExecutorService nacosConfigListenerExecutor; - - @Autowired - @Qualifier(NamingServiceBeanBuilder.BEAN_NAME) - private NamingServiceBeanBuilder namingServiceBeanBuilder; - - @NacosInjected - private ConfigService globalConfigService; - - @NacosInjected(properties = @NacosProperties(serverAddr = "${server.addr}")) - private ConfigService configService; - - @NacosInjected - private NamingService namingService; - - @Autowired - private Config config; - - @Value("${user.home:${user.dir}}") - private String dir; - - @Test - public void testGetConfig() throws Exception { - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); - Assert.assertEquals("9527", configService.getConfig(DATA_ID, DEFAULT_GROUP, 5000)); - } - +public class NacosBeanDefinitionRegistrarTest + extends AbstractNacosHttpServerTestExecutionListener { + + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } + + @Bean + public Config config() { + return new Config(); + } + + @Autowired + @Qualifier(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties globalProperties; + + @Autowired + @Qualifier(NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties configGlobalProperties; + @Autowired + @Qualifier(NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties discoveryGlobalProperties; + + @Autowired + @Qualifier(AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME) + private AnnotationNacosInjectedBeanPostProcessor annotationNacosInjectedBeanPostProcessor; + + @Autowired + @Qualifier(PLACEHOLDER_CONFIGURER_BEAN_NAME) + private PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer; + + @Autowired + @Qualifier(NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME) + private NacosConfigurationPropertiesBindingPostProcessor nacosConfigurationPropertiesBindingPostProcessor; + + @Autowired + @Qualifier(NacosConfigListenerMethodProcessor.BEAN_NAME) + private NacosConfigListenerMethodProcessor nacosConfigListenerMethodProcessor; + + @Autowired + @Qualifier(NacosPropertySourcePostProcessor.BEAN_NAME) + private NacosPropertySourcePostProcessor nacosPropertySourcePostProcessor; + + @Autowired + @Qualifier(AnnotationNacosPropertySourceBuilder.BEAN_NAME) + private AnnotationNacosPropertySourceBuilder annotationNacosPropertySourceBuilder; + + @Autowired + @Qualifier(NacosValueAnnotationBeanPostProcessor.BEAN_NAME) + private NacosValueAnnotationBeanPostProcessor nacosValueAnnotationBeanPostProcessor; + + @Autowired + @Qualifier(ConfigServiceBeanBuilder.BEAN_NAME) + private ConfigServiceBeanBuilder configServiceBeanBuilder; + + @Autowired + @Qualifier(NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) + private ExecutorService nacosConfigListenerExecutor; + + @Autowired + @Qualifier(NamingServiceBeanBuilder.BEAN_NAME) + private NamingServiceBeanBuilder namingServiceBeanBuilder; + + @NacosInjected + private ConfigService globalConfigService; + + @NacosInjected(properties = @NacosProperties(serverAddr = "${server.addr}")) + private ConfigService configService; + + @NacosInjected + private NamingService namingService; + + @Autowired + private Config config; + + @Value("${user.home:${user.dir}}") + private String dir; + + @Test + public void testGetConfig() throws Exception { + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); + Assert.assertEquals("9527", + configService.getConfig(DATA_ID, DEFAULT_GROUP, 5000)); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfigTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfigTest.java index eb8df097..07e9af8b 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfigTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/EnableNacosConfigTest.java @@ -18,9 +18,17 @@ import org.junit.Assert; import org.junit.Test; + import org.springframework.mock.env.MockEnvironment; -import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.*; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.ACCESS_KEY_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.CLUSTER_NAME_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.CONTEXT_PATH_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.ENCODE_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.ENDPOINT_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.NAMESPACE_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.SECRET_KEY_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig.SERVER_ADDR_PLACEHOLDER; /** * {@link EnableNacosConfig} Test @@ -30,57 +38,82 @@ */ public class EnableNacosConfigTest { - @Test - public void testPlaceholders() { - Assert.assertEquals("${nacos.config.endpoint:${nacos.endpoint:}}", ENDPOINT_PLACEHOLDER); - Assert.assertEquals("${nacos.config.namespace:${nacos.namespace:}}", NAMESPACE_PLACEHOLDER); - Assert.assertEquals("${nacos.config.access-key:${nacos.access-key:}}", ACCESS_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.config.secret-key:${nacos.secret-key:}}", SECRET_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.config.server-addr:${nacos.server-addr:}}", SERVER_ADDR_PLACEHOLDER); - Assert.assertEquals("${nacos.config.context-path:${nacos.context-path:}}", CONTEXT_PATH_PLACEHOLDER); - Assert.assertEquals("${nacos.config.cluster-name:${nacos.cluster-name:}}", CLUSTER_NAME_PLACEHOLDER); - Assert.assertEquals("${nacos.config.encode:${nacos.encode:UTF-8}}", ENCODE_PLACEHOLDER); - } + @Test + public void testPlaceholders() { + Assert.assertEquals("${nacos.config.endpoint:${nacos.endpoint:}}", + ENDPOINT_PLACEHOLDER); + Assert.assertEquals("${nacos.config.namespace:${nacos.namespace:}}", + NAMESPACE_PLACEHOLDER); + Assert.assertEquals("${nacos.config.access-key:${nacos.access-key:}}", + ACCESS_KEY_PLACEHOLDER); + Assert.assertEquals("${nacos.config.secret-key:${nacos.secret-key:}}", + SECRET_KEY_PLACEHOLDER); + Assert.assertEquals("${nacos.config.server-addr:${nacos.server-addr:}}", + SERVER_ADDR_PLACEHOLDER); + Assert.assertEquals("${nacos.config.context-path:${nacos.context-path:}}", + CONTEXT_PATH_PLACEHOLDER); + Assert.assertEquals("${nacos.config.cluster-name:${nacos.cluster-name:}}", + CLUSTER_NAME_PLACEHOLDER); + Assert.assertEquals("${nacos.config.encode:${nacos.encode:UTF-8}}", + ENCODE_PLACEHOLDER); + } - @Test - public void testResolvePlaceholders() { - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.config.endpoint", "test-value", "test-value"); - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.endpoint", "test-value", "test-value"); - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "", "test-value", ""); + @Test + public void testResolvePlaceholders() { + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.config.endpoint", + "test-value", "test-value"); + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.endpoint", "test-value", + "test-value"); + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.config.namespace", "test-value", "test-value"); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.namespace", "test-value", "test-value"); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.config.namespace", + "test-value", "test-value"); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.namespace", "test-value", + "test-value"); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.config.access-key", "test-value", "test-value"); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.access-key", "test-value", "test-value"); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.config.access-key", + "test-value", "test-value"); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.access-key", "test-value", + "test-value"); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.config.secret-key", "test-value", "test-value"); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.secret-key", "test-value", "test-value"); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.config.secret-key", + "test-value", "test-value"); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.secret-key", "test-value", + "test-value"); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.config.server-addr", "test-value", "test-value"); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.server-addr", "test-value", "test-value"); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.config.server-addr", + "test-value", "test-value"); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.server-addr", "test-value", + "test-value"); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.config.context-path", "test-value", "test-value"); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.context-path", "test-value", "test-value"); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.config.context-path", + "test-value", "test-value"); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.context-path", + "test-value", "test-value"); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.config.cluster-name", "test-value", "test-value"); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.cluster-name", "test-value", "test-value"); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.config.cluster-name", + "test-value", "test-value"); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.cluster-name", + "test-value", "test-value"); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.config.encode", "test-value", "test-value"); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.encode", "test-value", "test-value"); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "", "test-value", "UTF-8"); - } + testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.config.encode", "test-value", + "test-value"); + testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.encode", "test-value", + "test-value"); + testResolvePlaceholder(ENCODE_PLACEHOLDER, "", "test-value", "UTF-8"); + } - private void testResolvePlaceholder(String placeholder, String propertyName, String propertyValue, String expectValue) { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty(propertyName, propertyValue); - String resolvedValue = environment.resolvePlaceholders(placeholder); - Assert.assertEquals(expectValue, resolvedValue); - } + private void testResolvePlaceholder(String placeholder, String propertyName, + String propertyValue, String expectValue) { + MockEnvironment environment = new MockEnvironment(); + environment.setProperty(propertyName, propertyValue); + String resolvedValue = environment.resolvePlaceholders(placeholder); + Assert.assertEquals(expectValue, resolvedValue); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrarTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrarTest.java index e126ada7..66201806 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrarTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigBeanDefinitionRegistrarTest.java @@ -16,9 +16,12 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.Properties; + import com.alibaba.nacos.api.annotation.NacosProperties; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -26,8 +29,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Properties; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME; /** @@ -38,23 +39,20 @@ */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = NacosConfigBeanDefinitionRegistrarTest.class) -@EnableNacosConfig(globalProperties = @NacosProperties(enableRemoteSyncConfig = "true", - maxRetry = "5", - configRetryTime = "2600", - configLongPollTimeout = "26000")) +@EnableNacosConfig(globalProperties = @NacosProperties(enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "2600", configLongPollTimeout = "26000")) @Component public class NacosConfigBeanDefinitionRegistrarTest { - @Autowired - private BeanFactory beanFactory; + @Autowired + private BeanFactory beanFactory; - @Autowired - @Qualifier(CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties properties; + @Autowired + @Qualifier(CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties properties; - @Test - public void testRegisterBeanDefinitions() { + @Test + public void testRegisterBeanDefinitions() { - } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessorTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessorTest.java index e4590ec8..43e5b9ff 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessorTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerMethodProcessorTest.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -33,6 +35,7 @@ import com.alibaba.nacos.spring.test.User; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @@ -42,8 +45,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import javax.annotation.PostConstruct; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; import static org.junit.Assert.assertEquals; @@ -56,90 +57,89 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - TestConfiguration.class, - Listeners.class, - ConfigServiceBeanBuilder.class, - AnnotationNacosInjectedBeanPostProcessor.class, - NacosConfigListenerMethodProcessor.class, - NacosConfigListenerMethodProcessorTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosConfigListenerMethodProcessorTest.class}) +@ContextConfiguration(classes = { TestConfiguration.class, Listeners.class, + ConfigServiceBeanBuilder.class, AnnotationNacosInjectedBeanPostProcessor.class, + NacosConfigListenerMethodProcessor.class, + NacosConfigListenerMethodProcessorTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosConfigListenerMethodProcessorTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) -public class NacosConfigListenerMethodProcessorTest extends AbstractNacosHttpServerTestExecutionListener { - - @Bean(name = ApplicationContextHolder.BEAN_NAME) - public ApplicationContextHolder applicationContextHolder(ApplicationContext applicationContext) { - ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); - applicationContextHolder.setApplicationContext(applicationContext); - return applicationContextHolder; - } - - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } - - @Autowired - private Listeners listeners; - - @NacosInjected - private ConfigService configService; - - private volatile boolean received = false; - - @PostConstruct - public void initListener() throws NacosException { - configService.addListener(DATA_ID, DEFAULT_GROUP, new AbstractListener() { - @Override - public void receiveConfigInfo(String config) { - assertEquals("9527", config); // asserts true - } - }); - } - - @NacosConfigListener(dataId = DATA_ID) - public void onMessage(String config) { - assertEquals("9527", config); // asserts true - } - - @NacosConfigListener(dataId = DATA_ID) - public void onInteger(Integer value) { - assertEquals(Integer.valueOf(9527), value); // asserts true - } - - @NacosConfigListener(dataId = DATA_ID) - public void onInt(int value) { - assertEquals(9527, value); // asserts true - } - - @Test - public void testPublishConfig() throws NacosException, InterruptedException { - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); - - Thread.sleep(3000); - - assertNull(listeners.getIntegerValue()); // asserts true - assertEquals(Double.valueOf(9527), listeners.getDoubleValue()); // asserts true - } - - - @Test - public void testPublishUser() throws NacosException, InterruptedException { - configService.publishConfig("user", DEFAULT_GROUP, "{\"id\":1,\"name\":\"mercyblitz\"}"); - int cnt = 3; - while (cnt >= 0 && !received) { - Thread.sleep(1000); - cnt --; - } - } - - @NacosConfigListener(dataId = "user", converter = UserNacosConfigConverter.class) - public void onUser(User user) { - assertEquals(Long.valueOf(1L), user.getId()); - assertEquals("mercyblitz", user.getName()); - received = true; - } +public class NacosConfigListenerMethodProcessorTest + extends AbstractNacosHttpServerTestExecutionListener { + + @Bean(name = ApplicationContextHolder.BEAN_NAME) + public ApplicationContextHolder applicationContextHolder( + ApplicationContext applicationContext) { + ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); + applicationContextHolder.setApplicationContext(applicationContext); + return applicationContextHolder; + } + + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } + + @Autowired + private Listeners listeners; + + @NacosInjected + private ConfigService configService; + + private volatile boolean received = false; + + @PostConstruct + public void initListener() throws NacosException { + configService.addListener(DATA_ID, DEFAULT_GROUP, new AbstractListener() { + @Override + public void receiveConfigInfo(String config) { + assertEquals("9527", config); // asserts true + } + }); + } + + @NacosConfigListener(dataId = DATA_ID) + public void onMessage(String config) { + assertEquals("9527", config); // asserts true + } + + @NacosConfigListener(dataId = DATA_ID) + public void onInteger(Integer value) { + assertEquals(Integer.valueOf(9527), value); // asserts true + } + + @NacosConfigListener(dataId = DATA_ID) + public void onInt(int value) { + assertEquals(9527, value); // asserts true + } + + @Test + public void testPublishConfig() throws NacosException, InterruptedException { + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527"); + + Thread.sleep(3000); + + assertNull(listeners.getIntegerValue()); // asserts true + assertEquals(Double.valueOf(9527), listeners.getDoubleValue()); // asserts true + } + + @Test + public void testPublishUser() throws NacosException, InterruptedException { + configService.publishConfig("user", DEFAULT_GROUP, + "{\"id\":1,\"name\":\"mercyblitz\"}"); + int cnt = 3; + while (cnt >= 0 && !received) { + Thread.sleep(1000); + cnt--; + } + } + + @NacosConfigListener(dataId = "user", converter = UserNacosConfigConverter.class) + public void onUser(User user) { + assertEquals(Long.valueOf(1L), user.getId()); + assertEquals("mercyblitz", user.getName()); + received = true; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerTest.java index ce2afa6f..633fbe08 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosConfigListenerTest.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.concurrent.TimeUnit; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -26,74 +28,73 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.concurrent.TimeUnit; - /** * @author liaochuntao * @since */ @RunWith(SpringJUnit4ClassRunner.class) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosConfigListenerTest.class}) -@ContextConfiguration(classes = {NacosConfigListenerTest.NacosConfiguration.class, NacosConfigListenerTest.class}) -public class NacosConfigListenerTest extends AbstractNacosHttpServerTestExecutionListener { +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosConfigListenerTest.class }) +@ContextConfiguration(classes = { NacosConfigListenerTest.NacosConfiguration.class, + NacosConfigListenerTest.class }) +public class NacosConfigListenerTest + extends AbstractNacosHttpServerTestExecutionListener { - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - private static volatile String content = ""; - private static volatile boolean receive = false; + private static volatile String content = ""; + private static volatile boolean receive = false; - @NacosConfigListener(dataId = "com.alibaba.nacos.example.properties", timeout = 2000L) - public void onMessage(String config) { - System.out.println("onMessage: " + config); - receive = true; - content = config; - } + @NacosConfigListener(dataId = "com.alibaba.nacos.example.properties", timeout = 2000L) + public void onMessage(String config) { + System.out.println("onMessage: " + config); + receive = true; + content = config; + } - @Before - public void before() { + @Before + public void before() { - } + } - @Test - public void testConfigListener() throws InterruptedException { + @Test + public void testConfigListener() throws InterruptedException { - final long currentTimeMillis = System.currentTimeMillis(); + final long currentTimeMillis = System.currentTimeMillis(); - boolean result = false; - try { - result = configService.publishConfig("com.alibaba.nacos.example.properties", "DEFAULT_GROUP", - "" + currentTimeMillis); - } catch (NacosException e) { - e.printStackTrace(); - } - Assert.assertTrue(result); - while (!receive) { - TimeUnit.SECONDS.sleep(3); - } - Assert.assertEquals("" + currentTimeMillis, content); - } + boolean result = false; + try { + result = configService.publishConfig("com.alibaba.nacos.example.properties", + "DEFAULT_GROUP", "" + currentTimeMillis); + } + catch (NacosException e) { + e.printStackTrace(); + } + Assert.assertTrue(result); + while (!receive) { + TimeUnit.SECONDS.sleep(3); + } + Assert.assertEquals("" + currentTimeMillis, content); + } - @Configuration - // 在命名空间详情处可以获取到 endpoint 和 namespace;accessKey 和 secretKey 推荐使用 RAM 账户的 - @EnableNacosConfig(globalProperties = @NacosProperties( - serverAddr = "${server.addr}" - )) - public static class NacosConfiguration { + @Configuration + // 在命名空间详情处可以获取到 endpoint 和 namespace;accessKey 和 secretKey 推荐使用 RAM 账户的 + @EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) + public static class NacosConfiguration { - } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertiesTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertiesTest.java index 527f6b4a..cc7f2d5c 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertiesTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertiesTest.java @@ -20,6 +20,7 @@ import com.alibaba.nacos.spring.context.annotation.EnableNacos; import org.junit.Assert; import org.junit.Test; + import org.springframework.mock.env.MockEnvironment; /** @@ -31,107 +32,113 @@ */ public class NacosPropertiesTest { - @EnableNacos(globalProperties = @NacosProperties) - private static class NacosPropertiesDefaultValues { - } + @EnableNacos(globalProperties = @NacosProperties) + private static class NacosPropertiesDefaultValues { + } - @EnableNacos( - globalProperties = - @NacosProperties( - endpoint = "e", - namespace = "n", - accessKey = "a", - secretKey = "s", - serverAddr = "127.0.0.1", - contextPath = "/", - clusterName = "c", - encode = "GBK" - ) - ) - private static class NacosPropertiesValues { - } + @EnableNacos(globalProperties = @NacosProperties(endpoint = "e", namespace = "n", accessKey = "a", secretKey = "s", serverAddr = "127.0.0.1", contextPath = "/", clusterName = "c", encode = "GBK")) + private static class NacosPropertiesValues { + } - @Test - public void testConstants() { - Assert.assertEquals("nacos.", NacosProperties.PREFIX); - Assert.assertEquals("endpoint", NacosProperties.ENDPOINT); - Assert.assertEquals("namespace", NacosProperties.NAMESPACE); - Assert.assertEquals("access-key", NacosProperties.ACCESS_KEY); - Assert.assertEquals("secret-key", NacosProperties.SECRET_KEY); - Assert.assertEquals("server-addr", NacosProperties.SERVER_ADDR); - Assert.assertEquals("context-path", NacosProperties.CONTEXT_PATH); - Assert.assertEquals("cluster-name", NacosProperties.CLUSTER_NAME); - Assert.assertEquals("encode", NacosProperties.ENCODE); - } + @Test + public void testConstants() { + Assert.assertEquals("nacos.", NacosProperties.PREFIX); + Assert.assertEquals("endpoint", NacosProperties.ENDPOINT); + Assert.assertEquals("namespace", NacosProperties.NAMESPACE); + Assert.assertEquals("access-key", NacosProperties.ACCESS_KEY); + Assert.assertEquals("secret-key", NacosProperties.SECRET_KEY); + Assert.assertEquals("server-addr", NacosProperties.SERVER_ADDR); + Assert.assertEquals("context-path", NacosProperties.CONTEXT_PATH); + Assert.assertEquals("cluster-name", NacosProperties.CLUSTER_NAME); + Assert.assertEquals("encode", NacosProperties.ENCODE); + } - @Test - public void testAttributeDefaultValues() { - NacosProperties nacosProperties = getDefaultNacosProperties(); - Assert.assertEquals("${nacos.endpoint:}", nacosProperties.endpoint()); - Assert.assertEquals("${nacos.namespace:}", nacosProperties.namespace()); - Assert.assertEquals("${nacos.access-key:}", nacosProperties.accessKey()); - Assert.assertEquals("${nacos.secret-key:}", nacosProperties.secretKey()); - Assert.assertEquals("${nacos.server-addr:}", nacosProperties.serverAddr()); - Assert.assertEquals("${nacos.context-path:}", nacosProperties.contextPath()); - Assert.assertEquals("${nacos.cluster-name:}", nacosProperties.clusterName()); - Assert.assertEquals("${nacos.encode:UTF-8}", nacosProperties.encode()); - } + @Test + public void testAttributeDefaultValues() { + NacosProperties nacosProperties = getDefaultNacosProperties(); + Assert.assertEquals("${nacos.endpoint:}", nacosProperties.endpoint()); + Assert.assertEquals("${nacos.namespace:}", nacosProperties.namespace()); + Assert.assertEquals("${nacos.access-key:}", nacosProperties.accessKey()); + Assert.assertEquals("${nacos.secret-key:}", nacosProperties.secretKey()); + Assert.assertEquals("${nacos.server-addr:}", nacosProperties.serverAddr()); + Assert.assertEquals("${nacos.context-path:}", nacosProperties.contextPath()); + Assert.assertEquals("${nacos.cluster-name:}", nacosProperties.clusterName()); + Assert.assertEquals("${nacos.encode:UTF-8}", nacosProperties.encode()); + } - @Test - public void testAttributeValues() { - EnableNacos enableNacos = NacosPropertiesValues.class.getAnnotation(EnableNacos.class); - NacosProperties nacosProperties = enableNacos.globalProperties(); - Assert.assertEquals("e", nacosProperties.endpoint()); - Assert.assertEquals("n", nacosProperties.namespace()); - Assert.assertEquals("a", nacosProperties.accessKey()); - Assert.assertEquals("s", nacosProperties.secretKey()); - Assert.assertEquals("127.0.0.1", nacosProperties.serverAddr()); - Assert.assertEquals("/", nacosProperties.contextPath()); - Assert.assertEquals("c", nacosProperties.clusterName()); - Assert.assertEquals("GBK", nacosProperties.encode()); - } + @Test + public void testAttributeValues() { + EnableNacos enableNacos = NacosPropertiesValues.class + .getAnnotation(EnableNacos.class); + NacosProperties nacosProperties = enableNacos.globalProperties(); + Assert.assertEquals("e", nacosProperties.endpoint()); + Assert.assertEquals("n", nacosProperties.namespace()); + Assert.assertEquals("a", nacosProperties.accessKey()); + Assert.assertEquals("s", nacosProperties.secretKey()); + Assert.assertEquals("127.0.0.1", nacosProperties.serverAddr()); + Assert.assertEquals("/", nacosProperties.contextPath()); + Assert.assertEquals("c", nacosProperties.clusterName()); + Assert.assertEquals("GBK", nacosProperties.encode()); + } - @Test - public void testAttributeResolvedDefaultValues() { - NacosProperties nacosProperties = getDefaultNacosProperties(); - MockEnvironment environment = new MockEnvironment(); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.endpoint())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.namespace())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.accessKey())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.secretKey())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.serverAddr())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.contextPath())); - Assert.assertEquals("", environment.resolvePlaceholders(nacosProperties.clusterName())); - Assert.assertEquals("UTF-8", environment.resolvePlaceholders(nacosProperties.encode())); - } + @Test + public void testAttributeResolvedDefaultValues() { + NacosProperties nacosProperties = getDefaultNacosProperties(); + MockEnvironment environment = new MockEnvironment(); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.endpoint())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.namespace())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.accessKey())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.secretKey())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.serverAddr())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.contextPath())); + Assert.assertEquals("", + environment.resolvePlaceholders(nacosProperties.clusterName())); + Assert.assertEquals("UTF-8", + environment.resolvePlaceholders(nacosProperties.encode())); + } - @Test - public void testAttributeResolvedPropertyValues() { - NacosProperties nacosProperties = getDefaultNacosProperties(); - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("nacos.endpoint", "e"); - environment.setProperty("nacos.namespace", "n"); - environment.setProperty("nacos.access-key", "a"); - environment.setProperty("nacos.secret-key", "s"); - environment.setProperty("nacos.server-addr", "127.0.0.1"); - environment.setProperty("nacos.context-path", "/"); - environment.setProperty("nacos.cluster-name", "c"); - environment.setProperty("nacos.encode", "GBK"); + @Test + public void testAttributeResolvedPropertyValues() { + NacosProperties nacosProperties = getDefaultNacosProperties(); + MockEnvironment environment = new MockEnvironment(); + environment.setProperty("nacos.endpoint", "e"); + environment.setProperty("nacos.namespace", "n"); + environment.setProperty("nacos.access-key", "a"); + environment.setProperty("nacos.secret-key", "s"); + environment.setProperty("nacos.server-addr", "127.0.0.1"); + environment.setProperty("nacos.context-path", "/"); + environment.setProperty("nacos.cluster-name", "c"); + environment.setProperty("nacos.encode", "GBK"); - Assert.assertEquals("e", environment.resolvePlaceholders(nacosProperties.endpoint())); - Assert.assertEquals("n", environment.resolvePlaceholders(nacosProperties.namespace())); - Assert.assertEquals("a", environment.resolvePlaceholders(nacosProperties.accessKey())); - Assert.assertEquals("s", environment.resolvePlaceholders(nacosProperties.secretKey())); - Assert.assertEquals("127.0.0.1", environment.resolvePlaceholders(nacosProperties.serverAddr())); - Assert.assertEquals("/", environment.resolvePlaceholders(nacosProperties.contextPath())); - Assert.assertEquals("c", environment.resolvePlaceholders(nacosProperties.clusterName())); - Assert.assertEquals("GBK", environment.resolvePlaceholders(nacosProperties.encode())); - } + Assert.assertEquals("e", + environment.resolvePlaceholders(nacosProperties.endpoint())); + Assert.assertEquals("n", + environment.resolvePlaceholders(nacosProperties.namespace())); + Assert.assertEquals("a", + environment.resolvePlaceholders(nacosProperties.accessKey())); + Assert.assertEquals("s", + environment.resolvePlaceholders(nacosProperties.secretKey())); + Assert.assertEquals("127.0.0.1", + environment.resolvePlaceholders(nacosProperties.serverAddr())); + Assert.assertEquals("/", + environment.resolvePlaceholders(nacosProperties.contextPath())); + Assert.assertEquals("c", + environment.resolvePlaceholders(nacosProperties.clusterName())); + Assert.assertEquals("GBK", + environment.resolvePlaceholders(nacosProperties.encode())); + } - private NacosProperties getDefaultNacosProperties() { - EnableNacos enableNacos = NacosPropertiesDefaultValues.class.getAnnotation(EnableNacos.class); - NacosProperties nacosProperties = enableNacos.globalProperties(); - return nacosProperties; - } + private NacosProperties getDefaultNacosProperties() { + EnableNacos enableNacos = NacosPropertiesDefaultValues.class + .getAnnotation(EnableNacos.class); + NacosProperties nacosProperties = enableNacos.globalProperties(); + return nacosProperties; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource4NacosRefreshTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource4NacosRefreshTest.java new file mode 100644 index 00000000..efc22679 --- /dev/null +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySource4NacosRefreshTest.java @@ -0,0 +1,173 @@ +/* + * 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.util.HashMap; +import java.util.Map; + +import com.alibaba.nacos.api.annotation.NacosInjected; +import com.alibaba.nacos.api.annotation.NacosProperties; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; +import com.alibaba.nacos.spring.context.annotation.EnableNacos; +import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; + +import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.GROUP_ID_PARAM_NAME; + +/** + * @author liaochuntao + * @since 0.3.5 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { NacosPropertySource4NacosRefreshTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosPropertySource4NacosRefreshTest.class }) +@NacosPropertySources({ + @NacosPropertySource(dataId = NacosPropertySource4NacosRefreshTest.DATA_ID, autoRefreshed = true) }) +@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}", enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "2600", configLongPollTimeout = "26000")) +@Component +public class NacosPropertySource4NacosRefreshTest + extends AbstractNacosHttpServerTestExecutionListener { + + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); + + public static final String DATA_ID = "app"; + + private static final String APP_NAME = "Nacos-Spring"; + + private static final String ANOTHER_APP_NAME = "Nacos-Spring-1"; + + private static final int VALUE_1 = 1; + + private static final int VALUE_2 = 2; + + private static final int VALUE_3 = 3; + + private static final int VALUE_4 = 4; + + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, DATA_ID); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + + config.put(CONTENT_PARAM_NAME, "app.name=" + APP_NAME + LINE_SEPARATOR + + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_1 + LINE_SEPARATOR + + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_2); + httpServer.initConfig(config); + } + + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } + + @NacosRefresh + public static class TApp { + + @Value("${app.name}") + private String name; + + @Value("${app.nacosFieldIntValue:" + VALUE_1 + "}") + private int nacosFieldIntValue; + + @Value(value = "${app.nacosFieldIntValueAutoRefreshed}") + private int nacosFieldIntValueAutoRefreshed; + + private int nacosMethodIntValue; + + @Value("${app.nacosMethodIntValue:" + VALUE_2 + "}") + public void setNacosMethodIntValue(int nacosMethodIntValue) { + this.nacosMethodIntValue = nacosMethodIntValue; + } + + private int nacosMethodIntValueAutoRefreshed; + + @Value(value = "${app.nacosMethodIntValueAutoRefreshed}") + public void setNacosMethodIntValueAutoRefreshed( + int nacosMethodIntValueAutoRefreshed) { + this.nacosMethodIntValueAutoRefreshed = nacosMethodIntValueAutoRefreshed; + } + } + + @Bean + public TApp app() { + return new TApp(); + } + + @NacosInjected + private ConfigService configService; + + @Autowired + private TApp app; + + @Autowired + private Environment environment; + + @Test + public void testValue() throws NacosException, InterruptedException { + Assert.assertEquals(APP_NAME, app.name); + + Assert.assertEquals(APP_NAME, environment.getProperty("app.name")); + + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + + Assert.assertEquals(VALUE_1, app.nacosFieldIntValueAutoRefreshed); + + Assert.assertEquals(VALUE_2, app.nacosMethodIntValueAutoRefreshed); + + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "app.name=" + ANOTHER_APP_NAME + + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_3 + + LINE_SEPARATOR + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_4); + + Thread.sleep(1000); + + Assert.assertEquals(ANOTHER_APP_NAME, environment.getProperty("app.name")); + + Assert.assertEquals(ANOTHER_APP_NAME, app.name); + + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + + Assert.assertEquals(VALUE_3, app.nacosFieldIntValueAutoRefreshed); + + Assert.assertEquals(VALUE_4, app.nacosMethodIntValueAutoRefreshed); + } + +} diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceJsonTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceJsonTest.java index c584c702..2a846c1b 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceJsonTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceJsonTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -28,8 +31,8 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @@ -39,9 +42,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; @@ -52,94 +52,87 @@ * @since */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourceJsonTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceJsonTest.class}) +@ContextConfiguration(classes = { NacosPropertySourceJsonTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosPropertySourceJsonTest.class }) @NacosPropertySource(dataId = NacosPropertySourceJsonTest.DATA_ID, autoRefreshed = true, type = ConfigType.JSON) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) @Component -public class NacosPropertySourceJsonTest extends AbstractNacosHttpServerTestExecutionListener { +public class NacosPropertySourceJsonTest + extends AbstractNacosHttpServerTestExecutionListener { - public static final String DATA_ID = "data_json"; + public static final String DATA_ID = "data_json"; - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - private String configStr = "{\n" + - " \"people\":{\n" + - " \"a\":\"liaochuntao\",\n" + - " \"b\":\"this is test\"\n" + - " }\n" + - "}"; + private String configStr = "{\n" + " \"people\":{\n" + + " \"a\":\"liaochuntao\",\n" + " \"b\":\"this is test\"\n" + + " }\n" + "}"; - private String newConfigStr = "{\n" + - " \"people\":{\n" + - " \"a\":\"liaochuntao\",\n" + - " \"b\":\"refresh this is test\"\n" + - " }\n" + - "}"; + private String newConfigStr = "{\n" + " \"people\":{\n" + + " \"a\":\"liaochuntao\",\n" + + " \"b\":\"refresh this is test\"\n" + " }\n" + "}"; - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, DATA_ID); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, configStr); + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, DATA_ID); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, configStr); - httpServer.initConfig(config); - } + httpServer.initConfig(config); + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - public static class App { + public static class App { - @Value("${people.a}") - private String a; - @NacosValue(value = "${people.b}", autoRefreshed = true) - private String b; + @Value("${people.a}") + private String a; + @NacosValue(value = "${people.b}", autoRefreshed = true) + private String b; - public String getA() { - return a; - } + public String getA() { + return a; + } - public void setA(String a) { - this.a = a; - } + public void setA(String a) { + this.a = a; + } - public String getB() { - return b; - } + public String getB() { + return b; + } - public void setB(String b) { - this.b = b; - } - } + public void setB(String b) { + this.b = b; + } + } - @Bean - public App app() { - return new App(); - } + @Bean + public App app() { + return new App(); + } - @Autowired - private App app; + @Autowired + private App app; - @Test - public void testValue() throws NacosException, InterruptedException { + @Test + public void testValue() throws NacosException, InterruptedException { - Assert.assertEquals("liaochuntao", app.a); - Assert.assertEquals("this is test", app.b); + Assert.assertEquals("liaochuntao", app.a); + Assert.assertEquals("this is test", app.b); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, newConfigStr); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, newConfigStr); - Thread.sleep(2000); + Thread.sleep(2000); - Assert.assertEquals("liaochuntao", app.a); - Assert.assertEquals("refresh this is test", app.b); - } + Assert.assertEquals("liaochuntao", app.a); + Assert.assertEquals("refresh this is test", app.b); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourcePostProcessorTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourcePostProcessorTest.java index cd59a870..d1ca1f8a 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourcePostProcessorTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourcePostProcessorTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -28,12 +31,12 @@ import com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor; import com.alibaba.nacos.spring.factory.ApplicationContextHolder; import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; -import com.alibaba.nacos.spring.test.MockConfigService; import com.alibaba.nacos.spring.test.TestApplicationHolder; import com.alibaba.nacos.spring.test.TestConfiguration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -46,9 +49,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; @@ -66,148 +66,138 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourcePostProcessorTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourcePostProcessorTest.class}) +@ContextConfiguration(classes = { NacosPropertySourcePostProcessorTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosPropertySourcePostProcessorTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) -public class NacosPropertySourcePostProcessorTest extends AbstractNacosHttpServerTestExecutionListener { - - private static final String TEST_PROPERTY_NAME = "user.name"; +public class NacosPropertySourcePostProcessorTest + extends AbstractNacosHttpServerTestExecutionListener { - private static final String TEST_PROPERTY_VALUE = "mercyblitz@" + System.currentTimeMillis(); + private static final String TEST_PROPERTY_NAME = "user.name"; - private static final String TEST_CONTENT = TEST_PROPERTY_NAME + "=" + TEST_PROPERTY_VALUE - + System.getProperty("line.separator") - + "PATH = /My/Path"; + private static final String TEST_PROPERTY_VALUE = "mercyblitz@" + + System.currentTimeMillis(); - @NacosPropertySources({ - @NacosPropertySource( - name = "second", - dataId = DATA_ID, - first = true, - before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, - after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), - @NacosPropertySource( - name = "first", - dataId = DATA_ID, - first = true, - before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, - after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) - }) - @NacosPropertySource( - dataId = DATA_ID, - before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) - private static class FirstOrderNacosPropertySource { + private static final String TEST_CONTENT = TEST_PROPERTY_NAME + "=" + + TEST_PROPERTY_VALUE + System.getProperty("line.separator") + + "PATH = /My/Path"; - } + @NacosPropertySources({ + @NacosPropertySource(name = "second", dataId = DATA_ID, first = true, before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), + @NacosPropertySource(name = "first", dataId = DATA_ID, first = true, before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) }) + @NacosPropertySource(dataId = DATA_ID, before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) + private static class FirstOrderNacosPropertySource { - @NacosPropertySource( - dataId = DATA_ID, - before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, - after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) - private static class RelativeOrderNacosPropertySource { + } - } + @NacosPropertySource(dataId = DATA_ID, before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) + private static class RelativeOrderNacosPropertySource { - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, DATA_ID); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, TEST_CONTENT); - httpServer.initConfig(config); - } + } - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, DATA_ID); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, TEST_CONTENT); + httpServer.initConfig(config); + } - @Bean(name = ApplicationContextHolder.BEAN_NAME) - public ApplicationContextHolder applicationContextHolder(ApplicationContext applicationContext) { - ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); - applicationContextHolder.setApplicationContext(applicationContext); - return applicationContextHolder; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - @NacosInjected - private ConfigService configService; + @Bean(name = ApplicationContextHolder.BEAN_NAME) + public ApplicationContextHolder applicationContextHolder( + ApplicationContext applicationContext) { + ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); + applicationContextHolder.setApplicationContext(applicationContext); + return applicationContextHolder; + } + @NacosInjected + private ConfigService configService; - @Test - public void testFirstOrder() throws NacosException { + @Test + public void testFirstOrder() throws NacosException { - AnnotationConfigApplicationContext context = createContext(DATA_ID, DEFAULT_GROUP, TEST_CONTENT); + AnnotationConfigApplicationContext context = createContext(DATA_ID, DEFAULT_GROUP, + TEST_CONTENT); - context.register(FirstOrderNacosPropertySource.class); + context.register(FirstOrderNacosPropertySource.class); - context.refresh(); + context.refresh(); - ConfigurableEnvironment environment = context.getEnvironment(); + ConfigurableEnvironment environment = context.getEnvironment(); - PropertySource propertySource = environment.getPropertySources().get("first"); + PropertySource propertySource = environment.getPropertySources().get("first"); - PropertySource firstPropertySource = environment.getPropertySources().iterator().next(); + PropertySource firstPropertySource = environment.getPropertySources().iterator() + .next(); - Assert.assertNotNull(propertySource); + Assert.assertNotNull(propertySource); - Assert.assertEquals(propertySource, firstPropertySource); + Assert.assertEquals(propertySource, firstPropertySource); - String systemProperty = System.getProperty(TEST_PROPERTY_NAME); + String systemProperty = System.getProperty(TEST_PROPERTY_NAME); - String propertyValue = environment.getProperty(TEST_PROPERTY_NAME); + String propertyValue = environment.getProperty(TEST_PROPERTY_NAME); - Assert.assertNotEquals(systemProperty, propertyValue); + Assert.assertNotEquals(systemProperty, propertyValue); - Assert.assertEquals(TEST_PROPERTY_VALUE, propertyValue); + Assert.assertEquals(TEST_PROPERTY_VALUE, propertyValue); - Assert.assertEquals(TEST_PROPERTY_VALUE, propertySource.getProperty(TEST_PROPERTY_NAME)); + Assert.assertEquals(TEST_PROPERTY_VALUE, + propertySource.getProperty(TEST_PROPERTY_NAME)); - } + } - @Test - public void testRelativeOrder() throws NacosException { + @Test + public void testRelativeOrder() throws NacosException { - AnnotationConfigApplicationContext context = createContext(DATA_ID, DEFAULT_GROUP, TEST_CONTENT); + AnnotationConfigApplicationContext context = createContext(DATA_ID, DEFAULT_GROUP, + TEST_CONTENT); - context.register(RelativeOrderNacosPropertySource.class); + context.register(RelativeOrderNacosPropertySource.class); - context.refresh(); + context.refresh(); - ConfigurableEnvironment environment = context.getEnvironment(); + ConfigurableEnvironment environment = context.getEnvironment(); - PropertySource propertySource = environment.getPropertySources().get("before"); + PropertySource propertySource = environment.getPropertySources().get("before"); - // Java System Properties before Nacos Properties - String systemProperty = System.getProperty(TEST_PROPERTY_NAME); - String propertyValue = environment.getProperty(TEST_PROPERTY_NAME); + // Java System Properties before Nacos Properties + String systemProperty = System.getProperty(TEST_PROPERTY_NAME); + String propertyValue = environment.getProperty(TEST_PROPERTY_NAME); - Assert.assertEquals(systemProperty, propertyValue); - Assert.assertNotNull(TEST_PROPERTY_VALUE, propertyValue); + Assert.assertEquals(systemProperty, propertyValue); + Assert.assertNotNull(TEST_PROPERTY_VALUE, propertyValue); - // Environment Variables after Nacos Properties - String path = System.getenv().get("PATH"); - propertyValue = environment.getProperty("PATH"); + // Environment Variables after Nacos Properties + String path = System.getenv().get("PATH"); + propertyValue = environment.getProperty("PATH"); - Assert.assertNotNull(path, propertyValue); - Assert.assertEquals("/My/Path", propertyValue); - } + Assert.assertNotNull(path, propertyValue); + Assert.assertEquals("/My/Path", propertyValue); + } - private AnnotationConfigApplicationContext createContext(String dataId, String groupId, String content) throws NacosException { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + private AnnotationConfigApplicationContext createContext(String dataId, + String groupId, String content) throws NacosException { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - configService.publishConfig(dataId, groupId, content); + configService.publishConfig(dataId, groupId, content); - beanFactory.registerSingleton(CONFIG_SERVICE_BEAN_NAME, configService); + beanFactory.registerSingleton(CONFIG_SERVICE_BEAN_NAME, configService); - context.register(AnnotationNacosInjectedBeanPostProcessor.class, - NacosPropertySourcePostProcessor.class, ConfigServiceBeanBuilder.class, - AnnotationNacosPropertySourceBuilder.class, TestConfiguration.class, TestApplicationHolder.class); - return context; - } + context.register(AnnotationNacosInjectedBeanPostProcessor.class, + NacosPropertySourcePostProcessor.class, ConfigServiceBeanBuilder.class, + AnnotationNacosPropertySourceBuilder.class, TestConfiguration.class, + TestApplicationHolder.class); + return context; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceReadFromEnvironmentTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceReadFromEnvironmentTest.java index dd6b3edf..00f75e82 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceReadFromEnvironmentTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceReadFromEnvironmentTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -29,6 +32,7 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -40,9 +44,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; @@ -54,157 +55,155 @@ */ @Ignore @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourceReadFromEnvironmentTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceReadFromEnvironmentTest.class}) +@ContextConfiguration(classes = { NacosPropertySourceReadFromEnvironmentTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosPropertySourceReadFromEnvironmentTest.class }) @NacosPropertySource(dataId = NacosPropertySourceReadFromEnvironmentTest.ENV_DATA_ID, autoRefreshed = true) -@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}", enableRemoteSyncConfig = "true", - maxRetry = "5", - configRetryTime = "2600", - configLongPollTimeout = "26000")) +@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}", enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "2600", configLongPollTimeout = "26000")) @Component -public class NacosPropertySourceReadFromEnvironmentTest extends AbstractNacosHttpServerTestExecutionListener { +public class NacosPropertySourceReadFromEnvironmentTest + extends AbstractNacosHttpServerTestExecutionListener { - private static final String LINE_SEPARATOR = System.getProperty("line.separator"); + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final String ENV_DATA_ID = "${data-id}"; + public static final String ENV_DATA_ID = "${data-id}"; - public static final String DATA_ID = "app.properties"; + public static final String DATA_ID = "app.properties"; - private static final String APP_NAME = "Nacos-Spring"; + private static final String APP_NAME = "Nacos-Spring"; - private static final String ANOTHER_APP_NAME = "Nacos-Spring-1"; + private static final String ANOTHER_APP_NAME = "Nacos-Spring-1"; - private static final int VALUE_1 = 1; + private static final int VALUE_1 = 1; - private static final int VALUE_2 = 2; + private static final int VALUE_2 = 2; - private static final int VALUE_3 = 3; + private static final int VALUE_3 = 3; - private static final int VALUE_4 = 4; + private static final int VALUE_4 = 4; - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, DATA_ID); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, - "app.name=" + APP_NAME + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_1 + LINE_SEPARATOR - + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_2); - httpServer.initConfig(config); - } + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, DATA_ID); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, "app.name=" + APP_NAME + LINE_SEPARATOR + + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_1 + LINE_SEPARATOR + + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_2); + httpServer.initConfig(config); + } - @BeforeClass - public static void init() { - System.setProperty("data-id", "app.properties"); - } + @BeforeClass + public static void init() { + System.setProperty("data-id", "app.properties"); + } - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - public static class App { + public static class App { - @Value("${app.name}") - private String name; + @Value("${app.name}") + private String name; - @Value("${app.name:Nacos}") - private String nameWithDefaultValue; + @Value("${app.name:Nacos}") + private String nameWithDefaultValue; - @NacosValue(value = "${app.name}", autoRefreshed = true) - private String nacosNameAutoRefreshed; + @NacosValue(value = "${app.name}", autoRefreshed = true) + private String nacosNameAutoRefreshed; - @NacosValue(value = "${app.name:Nacos}", autoRefreshed = true) - private String nacosNameAutoRefreshedWithDefaultValue; + @NacosValue(value = "${app.name:Nacos}", autoRefreshed = true) + private String nacosNameAutoRefreshedWithDefaultValue; - @NacosValue("${app.name}") - private String nacosNameNotAutoRefreshed; + @NacosValue("${app.name}") + private String nacosNameNotAutoRefreshed; - @NacosValue("${app.nacosFieldIntValue:" + VALUE_1 + "}") - private int nacosFieldIntValue; + @NacosValue("${app.nacosFieldIntValue:" + VALUE_1 + "}") + private int nacosFieldIntValue; - @NacosValue(value = "${app.nacosFieldIntValueAutoRefreshed}", autoRefreshed = true) - private int nacosFieldIntValueAutoRefreshed; + @NacosValue(value = "${app.nacosFieldIntValueAutoRefreshed}", autoRefreshed = true) + private int nacosFieldIntValueAutoRefreshed; - private int nacosMethodIntValue; + private int nacosMethodIntValue; - @NacosValue("${app.nacosMethodIntValue:" + VALUE_2 + "}") - public void setNacosMethodIntValue(int nacosMethodIntValue) { - this.nacosMethodIntValue = nacosMethodIntValue; - } + @NacosValue("${app.nacosMethodIntValue:" + VALUE_2 + "}") + public void setNacosMethodIntValue(int nacosMethodIntValue) { + this.nacosMethodIntValue = nacosMethodIntValue; + } - private int nacosMethodIntValueAutoRefreshed; + private int nacosMethodIntValueAutoRefreshed; - @NacosValue(value = "${app.nacosMethodIntValueAutoRefreshed}", autoRefreshed = true) - public void setNacosMethodIntValueAutoRefreshed(int nacosMethodIntValueAutoRefreshed) { - this.nacosMethodIntValueAutoRefreshed = nacosMethodIntValueAutoRefreshed; - } - } + @NacosValue(value = "${app.nacosMethodIntValueAutoRefreshed}", autoRefreshed = true) + public void setNacosMethodIntValueAutoRefreshed( + int nacosMethodIntValueAutoRefreshed) { + this.nacosMethodIntValueAutoRefreshed = nacosMethodIntValueAutoRefreshed; + } + } - @Bean - public App app() { - return new App(); - } + @Bean + public App app() { + return new App(); + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @Autowired - private App app; + @Autowired + private App app; - @Autowired - private ConfigurableEnvironment environment; + @Autowired + private ConfigurableEnvironment environment; - @Test - public void testValue() throws NacosException, InterruptedException { - Assert.assertEquals(APP_NAME, app.name); + @Test + public void testValue() throws NacosException, InterruptedException { + Assert.assertEquals(APP_NAME, app.name); - Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshed); - Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); - Assert.assertEquals(APP_NAME, environment.getProperty("app.name")); + Assert.assertEquals(APP_NAME, environment.getProperty("app.name")); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValueAutoRefreshed); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValueAutoRefreshed); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValueAutoRefreshed); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValueAutoRefreshed); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, - "app.name=" + ANOTHER_APP_NAME + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_3 - + LINE_SEPARATOR + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_4); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "app.name=" + ANOTHER_APP_NAME + + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_3 + + LINE_SEPARATOR + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_4); - Thread.sleep(1000); + Thread.sleep(1000); - Assert.assertEquals(APP_NAME, app.name); + Assert.assertEquals(APP_NAME, app.name); - Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); - Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshed); + Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshed); - Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); + Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); - Assert.assertEquals(ANOTHER_APP_NAME, environment.getProperty("app.name")); + Assert.assertEquals(ANOTHER_APP_NAME, environment.getProperty("app.name")); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); - Assert.assertEquals(VALUE_3, app.nacosFieldIntValueAutoRefreshed); + Assert.assertEquals(VALUE_3, app.nacosFieldIntValueAutoRefreshed); - Assert.assertEquals(VALUE_4, app.nacosMethodIntValueAutoRefreshed); - } + Assert.assertEquals(VALUE_4, app.nacosMethodIntValueAutoRefreshed); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceTest.java index b1376dfd..a612c433 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceTest.java @@ -16,6 +16,9 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; @@ -27,6 +30,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -38,9 +42,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; @@ -55,152 +56,149 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourceTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceTest.class}) -@NacosPropertySource(dataId = NacosPropertySourceTest.DATA_ID, autoRefreshed = true) -@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}", enableRemoteSyncConfig = "true", - maxRetry = "5", - configRetryTime = "2600", - configLongPollTimeout = "26000")) +@ContextConfiguration(classes = { NacosPropertySourceTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosPropertySourceTest.class }) +@NacosPropertySources({ + @NacosPropertySource(dataId = NacosPropertySourceTest.DATA_ID, autoRefreshed = true) }) +@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}", enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "2600", configLongPollTimeout = "26000")) @Component -public class NacosPropertySourceTest extends AbstractNacosHttpServerTestExecutionListener { - - private static final String LINE_SEPARATOR = System.getProperty("line.separator"); +public class NacosPropertySourceTest + extends AbstractNacosHttpServerTestExecutionListener { - public static final String DATA_ID = "app"; + private static final String LINE_SEPARATOR = System.getProperty("line.separator"); - private static final String APP_NAME = "Nacos-Spring"; + public static final String DATA_ID = "app"; - private static final String ANOTHER_APP_NAME = "Nacos-Spring-1"; + private static final String APP_NAME = "Nacos-Spring"; - private static final int VALUE_1 = 1; + private static final String ANOTHER_APP_NAME = "Nacos-Spring-1"; - private static final int VALUE_2 = 2; + private static final int VALUE_1 = 1; - private static final int VALUE_3 = 3; + private static final int VALUE_2 = 2; - private static final int VALUE_4 = 4; + private static final int VALUE_3 = 3; - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, DATA_ID); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + private static final int VALUE_4 = 4; + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, DATA_ID); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, - "app.name=" + APP_NAME + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_1 + LINE_SEPARATOR - + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_2); - httpServer.initConfig(config); - } + config.put(CONTENT_PARAM_NAME, "app.name=" + APP_NAME + LINE_SEPARATOR + + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_1 + LINE_SEPARATOR + + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_2); + httpServer.initConfig(config); + } - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - public static class App { + public static class App { - @Value("${app.name}") - private String name; + @Value("${app.name}") + private String name; - @Value("${app.name:Nacos}") - private String nameWithDefaultValue; + @Value("${app.name:Nacos}") + private String nameWithDefaultValue; - @NacosValue(value = "${app.name}", autoRefreshed = true) - private String nacosNameAutoRefreshed; + @NacosValue(value = "${app.name}", autoRefreshed = true) + private String nacosNameAutoRefreshed; - @NacosValue(value = "${app.name:Nacos}", autoRefreshed = true) - private String nacosNameAutoRefreshedWithDefaultValue; + @NacosValue(value = "${app.name:Nacos}", autoRefreshed = true) + private String nacosNameAutoRefreshedWithDefaultValue; - @NacosValue("${app.name}") - private String nacosNameNotAutoRefreshed; + @NacosValue("${app.name}") + private String nacosNameNotAutoRefreshed; - @NacosValue("${app.nacosFieldIntValue:" + VALUE_1 + "}") - private int nacosFieldIntValue; + @NacosValue("${app.nacosFieldIntValue:" + VALUE_1 + "}") + private int nacosFieldIntValue; - @NacosValue(value = "${app.nacosFieldIntValueAutoRefreshed}", autoRefreshed = true) - private int nacosFieldIntValueAutoRefreshed; + @NacosValue(value = "${app.nacosFieldIntValueAutoRefreshed}", autoRefreshed = true) + private int nacosFieldIntValueAutoRefreshed; - private int nacosMethodIntValue; + private int nacosMethodIntValue; - @NacosValue("${app.nacosMethodIntValue:" + VALUE_2 + "}") - public void setNacosMethodIntValue(int nacosMethodIntValue) { - this.nacosMethodIntValue = nacosMethodIntValue; - } + @NacosValue("${app.nacosMethodIntValue:" + VALUE_2 + "}") + public void setNacosMethodIntValue(int nacosMethodIntValue) { + this.nacosMethodIntValue = nacosMethodIntValue; + } - private int nacosMethodIntValueAutoRefreshed; + private int nacosMethodIntValueAutoRefreshed; - @NacosValue(value = "${app.nacosMethodIntValueAutoRefreshed}", autoRefreshed = true) - public void setNacosMethodIntValueAutoRefreshed(int nacosMethodIntValueAutoRefreshed) { - this.nacosMethodIntValueAutoRefreshed = nacosMethodIntValueAutoRefreshed; - } - } + @NacosValue(value = "${app.nacosMethodIntValueAutoRefreshed}", autoRefreshed = true) + public void setNacosMethodIntValueAutoRefreshed( + int nacosMethodIntValueAutoRefreshed) { + this.nacosMethodIntValueAutoRefreshed = nacosMethodIntValueAutoRefreshed; + } + } - @Bean - public App app() { - return new App(); - } + @Bean + public App app() { + return new App(); + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @Autowired - private App app; + @Autowired + private App app; - @Autowired - private Environment environment; + @Autowired + private Environment environment; - @Test - public void testValue() throws NacosException, InterruptedException { - Assert.assertEquals(APP_NAME, app.name); + @Test + public void testValue() throws NacosException, InterruptedException { + Assert.assertEquals(APP_NAME, app.name); - Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshed); - Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); - Assert.assertEquals(APP_NAME, environment.getProperty("app.name")); + Assert.assertEquals(APP_NAME, environment.getProperty("app.name")); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValueAutoRefreshed); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValueAutoRefreshed); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValueAutoRefreshed); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValueAutoRefreshed); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, - "app.name=" + ANOTHER_APP_NAME + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_3 - + LINE_SEPARATOR + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_4); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "app.name=" + ANOTHER_APP_NAME + + LINE_SEPARATOR + "app.nacosFieldIntValueAutoRefreshed=" + VALUE_3 + + LINE_SEPARATOR + "app.nacosMethodIntValueAutoRefreshed=" + VALUE_4); - Thread.sleep(1000); + Thread.sleep(1000); - Assert.assertEquals(APP_NAME, app.name); + Assert.assertEquals(APP_NAME, app.name); - Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); + Assert.assertEquals(APP_NAME, app.nameWithDefaultValue); - Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshed); + Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshed); - Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); + Assert.assertEquals(ANOTHER_APP_NAME, app.nacosNameAutoRefreshedWithDefaultValue); - Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); + Assert.assertEquals(APP_NAME, app.nacosNameNotAutoRefreshed); - Assert.assertEquals(ANOTHER_APP_NAME, environment.getProperty("app.name")); + Assert.assertEquals(ANOTHER_APP_NAME, environment.getProperty("app.name")); - Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); + Assert.assertEquals(VALUE_1, app.nacosFieldIntValue); - Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); + Assert.assertEquals(VALUE_2, app.nacosMethodIntValue); - Assert.assertEquals(VALUE_3, app.nacosFieldIntValueAutoRefreshed); + Assert.assertEquals(VALUE_3, app.nacosFieldIntValueAutoRefreshed); - Assert.assertEquals(VALUE_4, app.nacosMethodIntValueAutoRefreshed); - } + Assert.assertEquals(VALUE_4, app.nacosMethodIntValueAutoRefreshed); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceXmlTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceXmlTest.java index eac992fb..7813490b 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceXmlTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceXmlTest.java @@ -16,10 +16,12 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; 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.exception.NacosException; import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; import com.alibaba.nacos.spring.context.annotation.EnableNacos; @@ -28,6 +30,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @@ -37,85 +40,66 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.GROUP_ID_PARAM_NAME; -import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; /** * @author liaochuntao * @since */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourceXmlTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceXmlTest.class}) +@ContextConfiguration(classes = { NacosPropertySourceXmlTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosPropertySourceXmlTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) @Component -public class NacosPropertySourceXmlTest extends AbstractNacosHttpServerTestExecutionListener { - - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } - - private String xml = - "" + - "" + - "lct-1" + - "1006010022" + - "" + - "" + - "lct-2" + - "1006010033" + - "" + - "" + - "lct-3" + - "1006010044" + - "" + - "" + - "lct-4" + - "1006010055" + - "" + - ""; - - private final String except = "XmlApp{students=[Student{name='lct-1', num='1006010022'}, Student{name='lct-3', num='1006010044'}, Student{name='lct-4', num='1006010055'}]}"; - - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, XmlApp.DATA_ID_XML); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, xml); - - httpServer.initConfig(config); - } - - @Bean - public XmlApp xmlApp() { - return new XmlApp(); - } - - @NacosInjected - private ConfigService configService; - - @Autowired - private XmlApp xmlApp; - - @Test - public void testValue() throws NacosException, InterruptedException { - - configService.publishConfig(XmlApp.DATA_ID_XML, DEFAULT_GROUP, xml); - - Thread.sleep(2000); - - Assert.assertEquals(except, xmlApp.toString()); - } +public class NacosPropertySourceXmlTest + extends AbstractNacosHttpServerTestExecutionListener { + + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } + + private String xml = "" + "" + "lct-1" + + "1006010022" + "" + "" + "lct-2" + + "1006010033" + "" + "" + "lct-3" + + "1006010044" + "" + "" + "lct-4" + + "1006010055" + "" + ""; + + private final String except = "XmlApp{students=[Student{name='lct-1', num='1006010022'}, Student{name='lct-3', num='1006010044'}, Student{name='lct-4', num='1006010055'}]}"; + + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, XmlApp.DATA_ID_XML); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, xml); + + httpServer.initConfig(config); + } + + @Bean + public XmlApp xmlApp() { + return new XmlApp(); + } + + @NacosInjected + private ConfigService configService; + + @Autowired + private XmlApp xmlApp; + + @Test + public void testValue() throws NacosException, InterruptedException { + + configService.publishConfig(XmlApp.DATA_ID_XML, DEFAULT_GROUP, xml); + + Thread.sleep(2000); + + Assert.assertEquals(except, xmlApp.toString()); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceYamlTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceYamlTest.java index 20204dfb..ccd10388 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceYamlTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/config/NacosPropertySourceYamlTest.java @@ -16,10 +16,12 @@ */ package com.alibaba.nacos.spring.context.annotation.config; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.api.annotation.NacosInjected; 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.NacosValue; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; @@ -29,6 +31,7 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; @@ -40,101 +43,92 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.GROUP_ID_PARAM_NAME; -import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; /** * @author liaochuntao * @since 0.3.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - NacosPropertySourceYamlTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceYamlTest.class}) +@ContextConfiguration(classes = { NacosPropertySourceYamlTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, NacosPropertySourceYamlTest.class }) @NacosPropertySources(value = { - @NacosPropertySource(dataId = YamlApp.DATA_ID_YAML + "_not_exist.yaml", autoRefreshed = true), - @NacosPropertySource(dataId = YamlApp.DATA_ID_YAML + ".yml", autoRefreshed = true) -}) + @NacosPropertySource(dataId = YamlApp.DATA_ID_YAML + + "_not_exist.yaml", autoRefreshed = true), + @NacosPropertySource(dataId = YamlApp.DATA_ID_YAML + + ".yml", autoRefreshed = true) }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) @Component -public class NacosPropertySourceYamlTest extends AbstractNacosHttpServerTestExecutionListener { - - private String yaml = "students:\n" + - " - {name: lct-1,num: 12}\n" + - " - {name: lct-2,num: 13}\n" + - " - {name: lct-3,num: 14}"; +public class NacosPropertySourceYamlTest + extends AbstractNacosHttpServerTestExecutionListener { - private String configStr = "people:\n" + - " a: 1\n" + - " b: 1"; + private String yaml = "students:\n" + " - {name: lct-1,num: 12}\n" + + " - {name: lct-2,num: 13}\n" + " - {name: lct-3,num: 14}"; - private String except = "YamlApp{students=[Student{name='lct-1', num='12'}, Student{name='lct-2', num='13'}, Student{name='lct-3', num='14'}]}"; + private String configStr = "people:\n" + " a: 1\n" + " b: 1"; - @Override - public void init(EmbeddedNacosHttpServer httpServer) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, YamlApp.DATA_ID_YAML + ".yml"); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, configStr); + private String except = "YamlApp{students=[Student{name='lct-1', num='12'}, Student{name='lct-2', num='13'}, Student{name='lct-3', num='14'}]}"; - httpServer.initConfig(config); - } + @Override + public void init(EmbeddedNacosHttpServer httpServer) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, YamlApp.DATA_ID_YAML + ".yml"); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, configStr); - private static class App { + httpServer.initConfig(config); + } - @Value("${people.a}") - private String a; - @NacosValue("${people.b}") - private String b; + private static class App { - } + @Value("${people.a}") + private String a; + @NacosValue("${people.b}") + private String b; - @Bean(name = "myApp") - public App app() { - return new App(); - } + } - @Bean - public YamlApp yamlApp() { - return new YamlApp(); - } + @Bean(name = "myApp") + public App app() { + return new App(); + } - @NacosInjected - private ConfigService configService; + @Bean + public YamlApp yamlApp() { + return new YamlApp(); + } - @Autowired - private YamlApp yamlApp; + @NacosInjected + private ConfigService configService; - @Autowired - @Qualifier(value = "myApp") - private App app; + @Autowired + private YamlApp yamlApp; - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Autowired + @Qualifier(value = "myApp") + private App app; - @Test - public void testValue() throws NacosException, InterruptedException { + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } - Assert.assertEquals("1", app.a); - Assert.assertEquals("1", app.b); + @Test + public void testValue() throws NacosException, InterruptedException { + Assert.assertEquals("1", app.a); + Assert.assertEquals("1", app.b); - configService.publishConfig(YamlApp.DATA_ID_YAML + ".yml", DEFAULT_GROUP, yaml); + configService.publishConfig(YamlApp.DATA_ID_YAML + ".yml", DEFAULT_GROUP, yaml); - Thread.sleep(2000); + Thread.sleep(2000); - Assert.assertEquals(except, yamlApp.toString()); + Assert.assertEquals(except, yamlApp.toString()); - } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscoveryTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscoveryTest.java index 7defd529..c64f4e29 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscoveryTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/annotation/discovery/EnableNacosDiscoveryTest.java @@ -18,10 +18,17 @@ import org.junit.Assert; import org.junit.Test; -import org.springframework.mock.env.MockEnvironment; -import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.*; +import org.springframework.mock.env.MockEnvironment; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.ACCESS_KEY_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.CLUSTER_NAME_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.CONTEXT_PATH_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.ENCODE_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.ENDPOINT_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.NAMESPACE_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.SECRET_KEY_PLACEHOLDER; +import static com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery.SERVER_ADDR_PLACEHOLDER; /** * {@link EnableNacosDiscovery} Test @@ -31,57 +38,82 @@ */ public class EnableNacosDiscoveryTest { - @Test - public void testPlaceholders() { - Assert.assertEquals("${nacos.discovery.endpoint:${nacos.endpoint:}}", ENDPOINT_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.namespace:${nacos.namespace:}}", NAMESPACE_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.access-key:${nacos.access-key:}}", ACCESS_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.secret-key:${nacos.secret-key:}}", SECRET_KEY_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.server-addr:${nacos.server-addr:}}", SERVER_ADDR_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.context-path:${nacos.context-path:}}", CONTEXT_PATH_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.cluster-name:${nacos.cluster-name:}}", CLUSTER_NAME_PLACEHOLDER); - Assert.assertEquals("${nacos.discovery.encode:${nacos.encode:UTF-8}}", ENCODE_PLACEHOLDER); - } + @Test + public void testPlaceholders() { + Assert.assertEquals("${nacos.discovery.endpoint:${nacos.endpoint:}}", + ENDPOINT_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.namespace:${nacos.namespace:}}", + NAMESPACE_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.access-key:${nacos.access-key:}}", + ACCESS_KEY_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.secret-key:${nacos.secret-key:}}", + SECRET_KEY_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.server-addr:${nacos.server-addr:}}", + SERVER_ADDR_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.context-path:${nacos.context-path:}}", + CONTEXT_PATH_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.cluster-name:${nacos.cluster-name:}}", + CLUSTER_NAME_PLACEHOLDER); + Assert.assertEquals("${nacos.discovery.encode:${nacos.encode:UTF-8}}", + ENCODE_PLACEHOLDER); + } - @Test - public void testResolvePlaceholders() { - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.discovery.endpoint", "test-value", "test-value"); - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.endpoint", "test-value", "test-value"); - testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "", "test-value", ""); + @Test + public void testResolvePlaceholders() { + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.discovery.endpoint", + "test-value", "test-value"); + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "nacos.endpoint", "test-value", + "test-value"); + testResolvePlaceholder(ENDPOINT_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.discovery.namespace", "test-value", "test-value"); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.namespace", "test-value", "test-value"); - testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.discovery.namespace", + "test-value", "test-value"); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "nacos.namespace", "test-value", + "test-value"); + testResolvePlaceholder(NAMESPACE_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.discovery.access-key", "test-value", "test-value"); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.access-key", "test-value", "test-value"); - testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.discovery.access-key", + "test-value", "test-value"); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "nacos.access-key", "test-value", + "test-value"); + testResolvePlaceholder(ACCESS_KEY_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.discovery.secret-key", "test-value", "test-value"); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.secret-key", "test-value", "test-value"); - testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.discovery.secret-key", + "test-value", "test-value"); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "nacos.secret-key", "test-value", + "test-value"); + testResolvePlaceholder(SECRET_KEY_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.discovery.server-addr", "test-value", "test-value"); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.server-addr", "test-value", "test-value"); - testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.discovery.server-addr", + "test-value", "test-value"); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "nacos.server-addr", "test-value", + "test-value"); + testResolvePlaceholder(SERVER_ADDR_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.discovery.context-path", "test-value", "test-value"); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.context-path", "test-value", "test-value"); - testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.discovery.context-path", + "test-value", "test-value"); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "nacos.context-path", + "test-value", "test-value"); + testResolvePlaceholder(CONTEXT_PATH_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.discovery.cluster-name", "test-value", "test-value"); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.cluster-name", "test-value", "test-value"); - testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "", "test-value", ""); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.discovery.cluster-name", + "test-value", "test-value"); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "nacos.cluster-name", + "test-value", "test-value"); + testResolvePlaceholder(CLUSTER_NAME_PLACEHOLDER, "", "test-value", ""); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.discovery.encode", "test-value", "test-value"); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.encode", "test-value", "test-value"); - testResolvePlaceholder(ENCODE_PLACEHOLDER, "", "test-value", "UTF-8"); - } + testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.discovery.encode", "test-value", + "test-value"); + testResolvePlaceholder(ENCODE_PLACEHOLDER, "nacos.encode", "test-value", + "test-value"); + testResolvePlaceholder(ENCODE_PLACEHOLDER, "", "test-value", "UTF-8"); + } - private void testResolvePlaceholder(String placeholder, String propertyName, String propertyValue, String expectValue) { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty(propertyName, propertyValue); - String resolvedValue = environment.resolvePlaceholders(placeholder); - Assert.assertEquals(expectValue, resolvedValue); - } + private void testResolvePlaceholder(String placeholder, String propertyName, + String propertyValue, String expectValue) { + MockEnvironment environment = new MockEnvironment(); + environment.setProperty(propertyName, propertyValue); + String resolvedValue = environment.resolvePlaceholders(placeholder); + Assert.assertEquals(expectValue, resolvedValue); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParserTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParserTest.java index 2c87d966..5de6f418 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParserTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/GlobalNacosPropertiesBeanDefinitionParserTest.java @@ -16,19 +16,27 @@ */ package com.alibaba.nacos.spring.context.config.xml; +import java.util.Properties; + import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Properties; - -import static com.alibaba.nacos.api.PropertyKeyConst.*; +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH; +import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.spring.util.NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME; /** @@ -39,36 +47,33 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "classpath:/META-INF/nacos-global-properties.xml" -}) +@ContextConfiguration(locations = { "classpath:/META-INF/nacos-global-properties.xml" }) public class GlobalNacosPropertiesBeanDefinitionParserTest { - @BeforeClass - public static void init() { - System.setProperty("nacos.server-addr", "127.0.0.1:8080"); - } - - @AfterClass - public static void afterClass() { - System.getProperties().remove("nacos.server-addr"); - } + @BeforeClass + public static void init() { + System.setProperty("nacos.server-addr", "127.0.0.1:8080"); + } - @Autowired - @Qualifier(GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties globalNacosProperties; + @AfterClass + public static void afterClass() { + System.getProperties().remove("nacos.server-addr"); + } - @Test - public void test() { - Assert.assertNull(globalNacosProperties.get(ENDPOINT)); - Assert.assertNull(globalNacosProperties.get(NAMESPACE)); - Assert.assertNull(globalNacosProperties.get(ACCESS_KEY)); - Assert.assertNull(globalNacosProperties.get(SECRET_KEY)); - Assert.assertNotNull(globalNacosProperties.get(SERVER_ADDR)); - Assert.assertNull(globalNacosProperties.get(CONTEXT_PATH)); - Assert.assertNull(globalNacosProperties.get(CLUSTER_NAME)); - Assert.assertEquals("UTF-8", globalNacosProperties.get(ENCODE)); - } + @Autowired + @Qualifier(GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties globalNacosProperties; + @Test + public void test() { + Assert.assertNull(globalNacosProperties.get(ENDPOINT)); + Assert.assertNull(globalNacosProperties.get(NAMESPACE)); + Assert.assertNull(globalNacosProperties.get(ACCESS_KEY)); + Assert.assertNull(globalNacosProperties.get(SECRET_KEY)); + Assert.assertNotNull(globalNacosProperties.get(SERVER_ADDR)); + Assert.assertNull(globalNacosProperties.get(CONTEXT_PATH)); + Assert.assertNull(globalNacosProperties.get(CLUSTER_NAME)); + Assert.assertEquals("UTF-8", globalNacosProperties.get(ENCODE)); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParserTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParserTest.java index 7d9de7c5..ed6d3f1c 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParserTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosAnnotationDrivenBeanDefinitionParserTest.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.spring.context.config.xml; +import java.util.Properties; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.spring.beans.factory.annotation.AnnotationNacosInjectedBeanPostProcessor; @@ -23,21 +25,18 @@ import com.alibaba.nacos.spring.context.properties.config.NacosConfigurationPropertiesBindingPostProcessor; import com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor; import com.alibaba.nacos.spring.factory.ApplicationContextHolder; -import com.alibaba.nacos.spring.factory.CacheableEventPublishingNacosServiceFactory; -import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.util.NacosBeanUtils; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Properties; - /** * {@link NacosAnnotationDrivenBeanDefinitionParser} Test * @@ -46,56 +45,54 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "classpath:/META-INF/nacos-context.xml" -}) +@ContextConfiguration(locations = { "classpath:/META-INF/nacos-context.xml" }) public class NacosAnnotationDrivenBeanDefinitionParserTest { - @BeforeClass - public static void init() { - System.setProperty("nacos.server-addr", "127.0.0.1:8080"); - } + @BeforeClass + public static void init() { + System.setProperty("nacos.server-addr", "127.0.0.1:8080"); + } - @AfterClass - public static void afterClass() { - System.getProperties().remove("nacos.server-addr"); - } + @AfterClass + public static void afterClass() { + System.getProperties().remove("nacos.server-addr"); + } - @Autowired - @Qualifier(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties globalProperties; + @Autowired + @Qualifier(NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties globalProperties; - @Autowired - @Qualifier(ApplicationContextHolder.BEAN_NAME) - private ApplicationContextHolder applicationContextHolder; + @Autowired + @Qualifier(ApplicationContextHolder.BEAN_NAME) + private ApplicationContextHolder applicationContextHolder; - @Autowired - @Qualifier(AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME) - private AnnotationNacosInjectedBeanPostProcessor annotationNacosInjectedBeanPostProcessor; + @Autowired + @Qualifier(AnnotationNacosInjectedBeanPostProcessor.BEAN_NAME) + private AnnotationNacosInjectedBeanPostProcessor annotationNacosInjectedBeanPostProcessor; - @Autowired - @Qualifier(NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME) - private NacosConfigurationPropertiesBindingPostProcessor nacosConfigurationPropertiesBindingPostProcessor; + @Autowired + @Qualifier(NacosConfigurationPropertiesBindingPostProcessor.BEAN_NAME) + private NacosConfigurationPropertiesBindingPostProcessor nacosConfigurationPropertiesBindingPostProcessor; - @Autowired - @Qualifier(NacosConfigListenerMethodProcessor.BEAN_NAME) - private NacosConfigListenerMethodProcessor nacosConfigListenerMethodProcessor; + @Autowired + @Qualifier(NacosConfigListenerMethodProcessor.BEAN_NAME) + private NacosConfigListenerMethodProcessor nacosConfigListenerMethodProcessor; - @Autowired - @Qualifier(NacosPropertySourcePostProcessor.BEAN_NAME) - private NacosPropertySourcePostProcessor nacosPropertySourcePostProcessor; + @Autowired + @Qualifier(NacosPropertySourcePostProcessor.BEAN_NAME) + private NacosPropertySourcePostProcessor nacosPropertySourcePostProcessor; - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @Test - public void test() { - Assert.assertNotNull(globalProperties); - Assert.assertNotNull(applicationContextHolder); - Assert.assertNotNull(annotationNacosInjectedBeanPostProcessor); - Assert.assertNotNull(nacosConfigurationPropertiesBindingPostProcessor); - Assert.assertNotNull(nacosConfigListenerMethodProcessor); - Assert.assertNotNull(nacosPropertySourcePostProcessor); - } + @Test + public void test() { + Assert.assertNotNull(globalProperties); + Assert.assertNotNull(applicationContextHolder); + Assert.assertNotNull(annotationNacosInjectedBeanPostProcessor); + Assert.assertNotNull(nacosConfigurationPropertiesBindingPostProcessor); + Assert.assertNotNull(nacosConfigListenerMethodProcessor); + Assert.assertNotNull(nacosPropertySourcePostProcessor); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParserTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParserTest.java index ecb9db9b..cd36053c 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParserTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/config/xml/NacosPropertySourceBeanDefinitionParserTest.java @@ -16,12 +16,16 @@ */ package com.alibaba.nacos.spring.context.config.xml; +import java.util.HashMap; +import java.util.Map; + import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; import com.alibaba.nacos.spring.test.User; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -30,11 +34,10 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.HashMap; -import java.util.Map; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; -import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.*; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.CONTENT_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.DATA_ID_PARAM_NAME; +import static com.alibaba.nacos.embedded.web.server.NacosConfigHttpHandler.GROUP_ID_PARAM_NAME; /** * {@link NacosPropertySourceBeanDefinitionParser} Test @@ -45,39 +48,39 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { - "classpath:/META-INF/nacos-context.xml", - "classpath:/META-INF/nacos-property-source.xml" -}) +@ContextConfiguration(locations = { "classpath:/META-INF/nacos-context.xml", + "classpath:/META-INF/nacos-property-source.xml" }) @DirtiesContext -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosPropertySourceBeanDefinitionParserTest.class}) -public class NacosPropertySourceBeanDefinitionParserTest extends AbstractNacosHttpServerTestExecutionListener { +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosPropertySourceBeanDefinitionParserTest.class }) +public class NacosPropertySourceBeanDefinitionParserTest + extends AbstractNacosHttpServerTestExecutionListener { - private static final Long USER_ID = 1991L; - private static final String USER_NAME = "hxy"; + private static final Long USER_ID = 1991L; + private static final String USER_NAME = "hxy"; - @Override - protected void init(EmbeddedNacosHttpServer server) { - Map config = new HashMap(1); - config.put(DATA_ID_PARAM_NAME, "user"); - config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); - config.put(CONTENT_PARAM_NAME, "id=" + USER_ID + "\nname=" + USER_NAME); - server.initConfig(config); - } + @Override + protected void init(EmbeddedNacosHttpServer server) { + Map config = new HashMap(1); + config.put(DATA_ID_PARAM_NAME, "user"); + config.put(GROUP_ID_PARAM_NAME, DEFAULT_GROUP); + config.put(CONTENT_PARAM_NAME, "id=" + USER_ID + "\nname=" + USER_NAME); + server.initConfig(config); + } - @Override - protected String getServerAddressPropertyName() { - return "nacos.server-addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "nacos.server-addr"; + } - @Autowired - private User user; + @Autowired + private User user; - @Test - public void testGetConfig() { - Assert.assertEquals(USER_ID, user.getId()); - Assert.assertEquals(USER_NAME, user.getName()); - } + @Test + public void testGetConfig() { + Assert.assertEquals(USER_ID, user.getId()); + Assert.assertEquals(USER_NAME, user.getName()); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigServiceTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigServiceTest.java index 27cae126..8c030d2f 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigServiceTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/EventPublishingConfigServiceTest.java @@ -16,6 +16,9 @@ */ 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.AbstractListener; import com.alibaba.nacos.api.config.listener.Listener; @@ -26,15 +29,15 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; + import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; -import java.util.Properties; -import java.util.concurrent.Executor; - import static com.alibaba.nacos.spring.test.MockConfigService.TIMEOUT_ERROR_MESSAGE; -import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.*; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.CONTENT; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; +import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; /** * {@link EventPublishingConfigService} Test @@ -44,153 +47,162 @@ */ public class EventPublishingConfigServiceTest { - private ConfigService mockConfigService; - - private ConfigurableApplicationContext context; - - private ConfigService configService; - - private Properties properties = new Properties(); - - @Before - public void init() { - this.mockConfigService = new MockConfigService(); - this.context = new GenericApplicationContext(); - this.context.refresh(); - this.configService = new EventPublishingConfigService(mockConfigService, properties, context, new Executor() { - @Override - public void execute(Runnable command) { - command.run(); - } - }); - } - - @After - public void destroy() { - this.context.close(); - } - - @Test - public void testGetConfig() throws NacosException { - configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); - Assert.assertEquals(CONTENT, configService.getConfig(DATA_ID, GROUP_ID, 5000)); - } - - @Test(expected = NacosException.class) - public void testGetConfigOnTimeout() throws NacosException { - final long timeout = -1L; - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigTimeoutEvent event) { - assertNacosConfigEvent(event); - Assert.assertEquals(timeout, event.getTimeout()); - Assert.assertEquals(TIMEOUT_ERROR_MESSAGE, event.getErrorMessage()); - } - }); - - configService.getConfig(DATA_ID, GROUP_ID, timeout); // trigger timeout error - } - - @Test - public void testPublishConfigWithEvent() throws NacosException { - - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigPublishedEvent event) { - assertNacosConfigEvent(event); - Assert.assertEquals(CONTENT, event.getContent()); - Assert.assertTrue(event.isPublished()); - } - }); - - configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); - } - - @Test - public void testRemoveConfigWithEvent() throws NacosException { - - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigRemovedEvent event) { - assertNacosConfigEvent(event); - Assert.assertTrue(event.isRemoved()); - } - }); - - configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); - configService.removeConfig(DATA_ID, GROUP_ID); - - } - - @Test - public void testAddListener() throws NacosException { - - final Listener listener = new AbstractListener() { - @Override - public void receiveConfigInfo(String configInfo) { - Assert.assertEquals(CONTENT, configInfo); - } - }; - - // assert NacosConfigReceivedEvent - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigReceivedEvent event) { - assertNacosConfigEvent(event); - Assert.assertEquals(CONTENT, event.getContent()); - } - }); - - // assert NacosConfigListenerRegisteredEvent - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigListenerRegisteredEvent event) { - assertNacosConfigEvent(event); - Assert.assertTrue(event.isRegistered()); - Assert.assertEquals(listener, event.getListener()); - } - }); - - // Add Listener - configService.addListener(DATA_ID, GROUP_ID, listener); - // Publish Config - configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); - - } - - @Test - public void testRemoveListener() throws NacosException { - final Listener listener = new AbstractListener() { - @Override - public void receiveConfigInfo(String configInfo) { - } - }; - - // assert NacosConfigListenerRegisteredEvent - context.addApplicationListener(new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigListenerRegisteredEvent event) { - assertNacosConfigEvent(event); - Assert.assertFalse(event.isRegistered()); - Assert.assertEquals(listener, event.getListener()); - } - }); - - configService.removeListener(DATA_ID, GROUP_ID, listener); - - } - - private void assertNacosConfigEvent(NacosConfigEvent event) { - Assert.assertEquals(mockConfigService, event.getSource()); - Assert.assertEquals(DATA_ID, event.getDataId()); - Assert.assertEquals(GROUP_ID, event.getGroupId()); - } - - @Test - public void testGetProperties() { - Assert.assertSame(properties, ((NacosServiceMetaData) configService).getProperties()); - } + private ConfigService mockConfigService; + + private ConfigurableApplicationContext context; + + private ConfigService configService; + + private Properties properties = new Properties(); + + @Before + public void init() { + this.mockConfigService = new MockConfigService(); + this.context = new GenericApplicationContext(); + this.context.refresh(); + this.configService = new EventPublishingConfigService(mockConfigService, + properties, context, new Executor() { + @Override + public void execute(Runnable command) { + command.run(); + } + }); + } + + @After + public void destroy() { + this.context.close(); + } + + @Test + public void testGetConfig() throws NacosException { + configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); + Assert.assertEquals(CONTENT, configService.getConfig(DATA_ID, GROUP_ID, 5000)); + } + + @Test(expected = NacosException.class) + public void testGetConfigOnTimeout() throws NacosException { + final long timeout = -1L; + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigTimeoutEvent event) { + assertNacosConfigEvent(event); + Assert.assertEquals(timeout, event.getTimeout()); + Assert.assertEquals(TIMEOUT_ERROR_MESSAGE, + event.getErrorMessage()); + } + }); + + configService.getConfig(DATA_ID, GROUP_ID, timeout); // trigger timeout error + } + + @Test + public void testPublishConfigWithEvent() throws NacosException { + + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigPublishedEvent event) { + assertNacosConfigEvent(event); + Assert.assertEquals(CONTENT, event.getContent()); + Assert.assertTrue(event.isPublished()); + } + }); + + configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); + } + + @Test + public void testRemoveConfigWithEvent() throws NacosException { + + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigRemovedEvent event) { + assertNacosConfigEvent(event); + Assert.assertTrue(event.isRemoved()); + } + }); + + configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); + configService.removeConfig(DATA_ID, GROUP_ID); + + } + + @Test + public void testAddListener() throws NacosException { + + final Listener listener = new AbstractListener() { + @Override + public void receiveConfigInfo(String configInfo) { + Assert.assertEquals(CONTENT, configInfo); + } + }; + + // assert NacosConfigReceivedEvent + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigReceivedEvent event) { + assertNacosConfigEvent(event); + Assert.assertEquals(CONTENT, event.getContent()); + } + }); + + // assert NacosConfigListenerRegisteredEvent + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent( + NacosConfigListenerRegisteredEvent event) { + assertNacosConfigEvent(event); + Assert.assertTrue(event.isRegistered()); + Assert.assertEquals(listener, event.getListener()); + } + }); + + // Add Listener + configService.addListener(DATA_ID, GROUP_ID, listener); + // Publish Config + configService.publishConfig(DATA_ID, GROUP_ID, CONTENT); + + } + + @Test + public void testRemoveListener() throws NacosException { + final Listener listener = new AbstractListener() { + @Override + public void receiveConfigInfo(String configInfo) { + } + }; + + // assert NacosConfigListenerRegisteredEvent + context.addApplicationListener( + new ApplicationListener() { + @Override + public void onApplicationEvent( + NacosConfigListenerRegisteredEvent event) { + assertNacosConfigEvent(event); + Assert.assertFalse(event.isRegistered()); + Assert.assertEquals(listener, event.getListener()); + } + }); + + configService.removeListener(DATA_ID, GROUP_ID, listener); + + } + + private void assertNacosConfigEvent(NacosConfigEvent event) { + Assert.assertEquals(mockConfigService, event.getSource()); + Assert.assertEquals(DATA_ID, event.getDataId()); + Assert.assertEquals(GROUP_ID, event.getGroupId()); + } + + @Test + public void testGetProperties() { + Assert.assertSame(properties, + ((NacosServiceMetaData) configService).getProperties()); + } } - - diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListenerTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListenerTest.java index b5330acd..758b2560 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListenerTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/event/config/TimeoutNacosConfigListenerTest.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.spring.context.event.config; +import java.util.concurrent.atomic.AtomicReference; + import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; @@ -23,8 +25,6 @@ import org.junit.Assert; import org.junit.Test; -import java.util.concurrent.atomic.AtomicReference; - import static com.alibaba.nacos.spring.context.annotation.config.NacosPropertySourceTest.DATA_ID; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; @@ -36,62 +36,61 @@ */ public class TimeoutNacosConfigListenerTest { - private final ConfigService configService = new MockConfigService(); - - private String receiveConfig(final long executionTime, long timeout, String content) throws NacosException { - - final AtomicReference contentHolder = new AtomicReference(); + private final ConfigService configService = new MockConfigService(); - Listener listener = new TimeoutNacosConfigListener(DATA_ID, GROUP_ID, timeout) { - @Override - protected void onReceived(String config) { - doWait(executionTime); - contentHolder.set(config); - System.out.printf("[%s] %s \n", Thread.currentThread().getName(), config); - } - }; + private String receiveConfig(final long executionTime, long timeout, String content) + throws NacosException { - configService.addListener(DATA_ID, GROUP_ID, listener); + final AtomicReference contentHolder = new AtomicReference(); - configService.publishConfig(DATA_ID, GROUP_ID, content); + Listener listener = new TimeoutNacosConfigListener(DATA_ID, GROUP_ID, timeout) { + @Override + protected void onReceived(String config) { + doWait(executionTime); + contentHolder.set(config); + System.out.printf("[%s] %s \n", Thread.currentThread().getName(), config); + } + }; - return contentHolder.get(); - } + configService.addListener(DATA_ID, GROUP_ID, listener); + configService.publishConfig(DATA_ID, GROUP_ID, content); - @Test - public void test() throws NacosException { + return contentHolder.get(); + } - String content = "Hello,World"; + @Test + public void test() throws NacosException { - String receivedConfig = receiveConfig(20, 50, content); + String content = "Hello,World"; - Assert.assertEquals(content, receivedConfig); - } + String receivedConfig = receiveConfig(20, 50, content); - @Test - public void testOnTimeout() throws NacosException { + Assert.assertEquals(content, receivedConfig); + } - String content = "Hello,World"; + @Test + public void testOnTimeout() throws NacosException { - String receivedConfig = receiveConfig(100, 50, content); + String content = "Hello,World"; - Assert.assertNull(receivedConfig); + String receivedConfig = receiveConfig(100, 50, content); - } + Assert.assertNull(receivedConfig); - private static void doWait(long millis) { + } - long startTime = System.currentTimeMillis(); + private static void doWait(long millis) { - while (true) { - long costTime = System.currentTimeMillis() - startTime; - if (costTime > millis) { - break; - } + long startTime = System.currentTimeMillis(); - } - } + while (true) { + long costTime = System.currentTimeMillis() - startTime; + if (costTime > millis) { + break; + } + } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinderTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinderTest.java index 753b37e7..c9c7b800 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinderTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBinderTest.java @@ -1,12 +1,12 @@ -///* +/// * // * Licensed to the Apache Software Foundation (ASF) under one or more -// * contributor license agreements. See the NOTICE file distributed with +// * 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 +// * the License. You may obtain a copy of the License at // * -// * http://www.apache.org/licenses/LICENSE-2.0 +// * 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, @@ -14,96 +14,102 @@ // * See the License for the specific language governing permissions and // * limitations under the License. // */ -//package com.alibaba.nacos.spring.context.properties.config; -// -//import com.alibaba.nacos.api.config.ConfigService; -//import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; -//import com.alibaba.nacos.api.exception.NacosException; -//import com.alibaba.nacos.spring.context.event.config.NacosConfigurationPropertiesBeanBoundEvent; -//import com.alibaba.nacos.spring.test.Config; -//import com.alibaba.nacos.spring.test.MockNacosServiceFactory; -//import org.junit.Assert; -//import org.junit.Test; -//import org.springframework.context.ApplicationEvent; -//import org.springframework.context.ApplicationEventPublisher; -//import org.springframework.context.ApplicationListener; -//import org.springframework.context.event.ApplicationEventMulticaster; -//import org.springframework.context.event.SimpleApplicationEventMulticaster; -// -//import java.util.Properties; -//import java.util.concurrent.atomic.AtomicReference; -// -//import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; -//import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; -//import static com.alibaba.nacos.spring.test.TestConfiguration.MODIFIED_TEST_CONTEXT; -//import static com.alibaba.nacos.spring.test.TestConfiguration.TEST_CONFIG; -// -///** +// package com.alibaba.nacos.spring.context.properties.config; +// +// import com.alibaba.nacos.api.config.ConfigService; +// import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; +// import com.alibaba.nacos.api.exception.NacosException; +// import +/// com.alibaba.nacos.spring.context.event.config.NacosConfigurationPropertiesBeanBoundEvent; +// import com.alibaba.nacos.spring.test.Config; +// import com.alibaba.nacos.spring.test.MockNacosServiceFactory; +// import org.junit.Assert; +// import org.junit.Test; +// import org.springframework.context.ApplicationEvent; +// import org.springframework.context.ApplicationEventPublisher; +// import org.springframework.context.ApplicationListener; +// import org.springframework.context.event.ApplicationEventMulticaster; +// import org.springframework.context.event.SimpleApplicationEventMulticaster; +// +// import java.util.Properties; +// import java.util.concurrent.atomic.AtomicReference; +// +// import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; +// import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; +// import static com.alibaba.nacos.spring.test.TestConfiguration.MODIFIED_TEST_CONTEXT; +// import static com.alibaba.nacos.spring.test.TestConfiguration.TEST_CONFIG; +// +/// ** // * {@link NacosConfigurationPropertiesBinder} Test // * // * @author Mercy // * @since 0.1.0 // */ -//public class NacosConfigurationPropertiesBinderTest { +// public class NacosConfigurationPropertiesBinderTest { // -// private MockNacosServiceFactory nacosServiceFactory = new MockNacosServiceFactory(); +// private MockNacosServiceFactory nacosServiceFactory = new MockNacosServiceFactory(); // -// @Test -// public void testBind() throws NacosException { +// @Test +// public void testBind() throws NacosException { // -// final Config config = new Config(); +// final Config config = new Config(); // -// final String beanName = "configBean"; +// final String beanName = "configBean"; // -// ConfigService configService = nacosServiceFactory.createConfigService(new Properties()); +// ConfigService configService = nacosServiceFactory.createConfigService(new +/// Properties()); // -// final AtomicReference content = new AtomicReference(); +// final AtomicReference content = new AtomicReference(); // -// content.set(TEST_CONFIG); +// content.set(TEST_CONFIG); // -// configService.publishConfig(DATA_ID, GROUP_ID, content.get()); +// configService.publishConfig(DATA_ID, GROUP_ID, content.get()); // -// final ApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(); +// final ApplicationEventMulticaster multicaster = new +/// SimpleApplicationEventMulticaster(); // -// multicaster.addApplicationListener(new ApplicationListener() { -// @Override -// public void onApplicationEvent(NacosConfigurationPropertiesBeanBoundEvent event) { -// Assert.assertEquals(DATA_ID, event.getDataId()); -// Assert.assertEquals(GROUP_ID, event.getGroupId()); -// Assert.assertEquals(content.get(), event.getContent()); -// Assert.assertEquals(config, event.getBean()); -// Assert.assertEquals(beanName, event.getBeanName()); -// Assert.assertEquals(config.getClass().getAnnotation(NacosConfigurationProperties.class), event.getProperties()); -// } -// }); +// multicaster.addApplicationListener(new +/// ApplicationListener() { +// @Override +// public void onApplicationEvent(NacosConfigurationPropertiesBeanBoundEvent event) { +// Assert.assertEquals(DATA_ID, event.getDataId()); +// Assert.assertEquals(GROUP_ID, event.getGroupId()); +// Assert.assertEquals(content.get(), event.getContent()); +// Assert.assertEquals(config, event.getBean()); +// Assert.assertEquals(beanName, event.getBeanName()); +// Assert.assertEquals(config.getClass().getAnnotation(NacosConfigurationProperties.class), +/// event.getProperties()); +// } +// }); // -// ApplicationEventPublisher applicationEventPublisher = new ApplicationEventPublisher() { +// ApplicationEventPublisher applicationEventPublisher = new ApplicationEventPublisher() { // -// @Override -// public void publishEvent(ApplicationEvent event) { -// multicaster.multicastEvent(event); -// } -// }; +// @Override +// public void publishEvent(ApplicationEvent event) { +// multicaster.multicastEvent(event); +// } +// }; // -// NacosConfigurationPropertiesBinder binder = new NacosConfigurationPropertiesBinder(configService, applicationEventPublisher); +// NacosConfigurationPropertiesBinder binder = new +/// NacosConfigurationPropertiesBinder(configService, applicationEventPublisher); // -// binder.bind(config, beanName); +// binder.bind(config, beanName); // -// Assert.assertEquals(1, config.getId()); -// Assert.assertEquals("mercyblitz", config.getName()); -// Assert.assertTrue(0.95 == config.getValue()); -// Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); -// Assert.assertNull(config.getIntData()); +// Assert.assertEquals(1, config.getId()); +// Assert.assertEquals("mercyblitz", config.getName()); +// Assert.assertTrue(0.95 == config.getValue()); +// Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); +// Assert.assertNull(config.getIntData()); // -// // Publishing config emits change -// content.set(MODIFIED_TEST_CONTEXT); -// configService.publishConfig(DATA_ID, GROUP_ID, content.get()); +// // Publishing config emits change +// content.set(MODIFIED_TEST_CONTEXT); +// configService.publishConfig(DATA_ID, GROUP_ID, content.get()); // -// Assert.assertEquals(1, config.getId()); -// Assert.assertEquals("mercyblitz@gmail.com", config.getName()); -// Assert.assertTrue(9527 == config.getValue()); -// Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); -// Assert.assertNull(config.getIntData()); -// } +// Assert.assertEquals(1, config.getId()); +// Assert.assertEquals("mercyblitz@gmail.com", config.getName()); +// Assert.assertTrue(9527 == config.getValue()); +// Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); +// Assert.assertNull(config.getIntData()); +// } // -//} +// } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessorTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessorTest.java index 11fd71bb..12abc5a2 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessorTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/context/properties/config/NacosConfigurationPropertiesBindingPostProcessorTest.java @@ -20,15 +20,13 @@ import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.spring.beans.factory.annotation.AnnotationNacosInjectedBeanPostProcessor; -import com.alibaba.nacos.spring.beans.factory.annotation.ConfigServiceBeanBuilder; import com.alibaba.nacos.spring.context.annotation.EnableNacos; import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; import com.alibaba.nacos.spring.test.Config; -import com.alibaba.nacos.spring.test.TestConfiguration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; @@ -50,58 +48,60 @@ */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { - NacosConfigurationPropertiesBindingPostProcessorTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, NacosConfigurationPropertiesBindingPostProcessorTest.class}) + NacosConfigurationPropertiesBindingPostProcessorTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + NacosConfigurationPropertiesBindingPostProcessorTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) -public class NacosConfigurationPropertiesBindingPostProcessorTest extends AbstractNacosHttpServerTestExecutionListener { - - @Autowired - private Config config; - - @NacosInjected - private ConfigService configService; - - @Bean - public Config config() { - return new Config(); - } - - @Test - public void test() throws NacosException, InterruptedException { - - configService.publishConfig(DATA_ID, GROUP_ID, TEST_CONFIG); - - Thread.sleep(4000); - - Assert.assertEquals(1, config.getId()); - Assert.assertEquals("mercyblitz", config.getName()); - Assert.assertEquals(0.95, config.getValue(), 0.0); - Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); - Assert.assertNull(config.getIntData()); - Assert.assertArrayEquals(new Object[]{1,2,3,4,5}, config.getList().toArray()); - Assert.assertEquals("value", config.getMap().get("key-1")); - - // Publishing config emits change - configService.publishConfig(DATA_ID, GROUP_ID, MODIFIED_TEST_CONTEXT); - - Thread.sleep(2000); - - Assert.assertEquals(1, config.getId()); - Assert.assertEquals("mercyblitz@gmail.com", config.getName()); - Assert.assertEquals(9527, config.getValue(), 0.0); - Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); - Assert.assertNull(config.getIntData()); - Assert.assertArrayEquals(new Object[]{6,6,6,6}, config.getList().toArray()); - Assert.assertNull(config.getMap().get("key-1")); - Assert.assertEquals("value", config.getMap().get("key-2")); - Assert.assertEquals("value", config.getMap().get("key-3")); - } - - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } +public class NacosConfigurationPropertiesBindingPostProcessorTest + extends AbstractNacosHttpServerTestExecutionListener { + + @Autowired + private Config config; + + @NacosInjected + private ConfigService configService; + + @Bean + public Config config() { + return new Config(); + } + + @Test + public void test() throws NacosException, InterruptedException { + + configService.publishConfig(DATA_ID, GROUP_ID, TEST_CONFIG); + + Thread.sleep(4000); + + Assert.assertEquals(1, config.getId()); + Assert.assertEquals("mercyblitz", config.getName()); + Assert.assertEquals(0.95, config.getValue(), 0.0); + Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); + Assert.assertNull(config.getIntData()); + Assert.assertArrayEquals(new Object[] { 1, 2, 3, 4, 5 }, + config.getList().toArray()); + Assert.assertEquals("value", config.getMap().get("key-1")); + + // Publishing config emits change + configService.publishConfig(DATA_ID, GROUP_ID, MODIFIED_TEST_CONTEXT); + + Thread.sleep(2000); + + Assert.assertEquals(1, config.getId()); + Assert.assertEquals("mercyblitz@gmail.com", config.getName()); + Assert.assertEquals(9527, config.getValue(), 0.0); + Assert.assertEquals(Float.valueOf(1234.5f), config.getFloatData()); + Assert.assertNull(config.getIntData()); + Assert.assertArrayEquals(new Object[] { 6, 6, 6, 6 }, config.getList().toArray()); + Assert.assertNull(config.getMap().get("key-1")); + Assert.assertEquals("value", config.getMap().get("key-2")); + Assert.assertEquals("value", config.getMap().get("key-3")); + } + + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/convert/converter/config/UserNacosConfigConverter.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/convert/converter/config/UserNacosConfigConverter.java index 72b6a387..cd1e4cb8 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/convert/converter/config/UserNacosConfigConverter.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/convert/converter/config/UserNacosConfigConverter.java @@ -28,13 +28,13 @@ */ public class UserNacosConfigConverter implements NacosConfigConverter { - @Override - public boolean canConvert(Class targetType) { - return true; - } + @Override + public boolean canConvert(Class targetType) { + return true; + } - @Override - public User convert(String source) { - return JSON.parseObject(source, User.class); - } + @Override + public User convert(String source) { + return JSON.parseObject(source, User.class); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactoryTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactoryTest.java index 5cdfd9f4..d7571193 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactoryTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableEventPublishingNacosServiceFactoryTest.java @@ -16,21 +16,23 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import com.alibaba.nacos.api.PropertyKeyConst; -import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.api.naming.pojo.Service; import com.alibaba.nacos.spring.context.annotation.EnableNacos; -import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySourceTest; import com.alibaba.nacos.spring.test.AbstractNacosHttpServerTestExecutionListener; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; @@ -39,10 +41,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME; /** @@ -52,73 +50,82 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - CacheableEventPublishingNacosServiceFactory.class, - CacheableEventPublishingNacosServiceFactoryTest.class -}) -@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, CacheableEventPublishingNacosServiceFactoryTest.class}) +@ContextConfiguration(classes = { CacheableEventPublishingNacosServiceFactory.class, + CacheableEventPublishingNacosServiceFactoryTest.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + CacheableEventPublishingNacosServiceFactoryTest.class }) @EnableNacos(globalProperties = @NacosProperties(serverAddr = "${server.addr}")) -public class CacheableEventPublishingNacosServiceFactoryTest extends AbstractNacosHttpServerTestExecutionListener { +public class CacheableEventPublishingNacosServiceFactoryTest + extends AbstractNacosHttpServerTestExecutionListener { - @Bean(name = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) - public static ExecutorService executorService() { - return Executors.newSingleThreadExecutor(); - } + @Bean(name = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) + public static ExecutorService executorService() { + return Executors.newSingleThreadExecutor(); + } - @Autowired - private NacosServiceFactory nacosServiceFactory; + @Autowired + private NacosServiceFactory nacosServiceFactory; - private Properties properties = new Properties(); + private Properties properties = new Properties(); - @Before - public void init() { - properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1"); - } + @Before + public void init() { + properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1"); + } - @Test - public void testCreateConfigService() throws NacosException { - ConfigService configService = nacosServiceFactory.createConfigService(properties); - ConfigService configService2 = nacosServiceFactory.createConfigService(properties); - Assert.assertTrue(configService == configService2); - } + @Test + public void testCreateConfigService() throws NacosException { + ConfigService configService = nacosServiceFactory.createConfigService(properties); + ConfigService configService2 = nacosServiceFactory + .createConfigService(properties); + Assert.assertTrue(configService == configService2); + } - @Test - public void testCreateNamingService() throws NacosException { - NamingService namingService = nacosServiceFactory.createNamingService(properties); - NamingService namingService2 = nacosServiceFactory.createNamingService(properties); - Assert.assertTrue(namingService == namingService2); - } + @Test + public void testCreateNamingService() throws NacosException { + NamingService namingService = nacosServiceFactory.createNamingService(properties); + NamingService namingService2 = nacosServiceFactory + .createNamingService(properties); + Assert.assertTrue(namingService == namingService2); + } - @Test - public void testGetConfigServices() throws NacosException { - ConfigService configService = nacosServiceFactory.createConfigService(properties); - ConfigService configService2 = nacosServiceFactory.createConfigService(properties); - Assert.assertTrue(configService == configService2); - Assert.assertEquals(1, nacosServiceFactory.getConfigServices().size()); - Assert.assertEquals(configService, nacosServiceFactory.getConfigServices().iterator().next()); - } + @Test + public void testGetConfigServices() throws NacosException { + ConfigService configService = nacosServiceFactory.createConfigService(properties); + ConfigService configService2 = nacosServiceFactory + .createConfigService(properties); + Assert.assertTrue(configService == configService2); + Assert.assertEquals(1, nacosServiceFactory.getConfigServices().size()); + Assert.assertEquals(configService, + nacosServiceFactory.getConfigServices().iterator().next()); + } - @Test - public void testGetNamingServices() throws NacosException { - NamingService namingService = nacosServiceFactory.createNamingService(properties); - NamingService namingService2 = nacosServiceFactory.createNamingService(properties); - Assert.assertTrue(namingService == namingService2); - Assert.assertEquals(1, nacosServiceFactory.getNamingServices().size()); - Assert.assertEquals(namingService, nacosServiceFactory.getNamingServices().iterator().next()); - } + @Test + public void testGetNamingServices() throws NacosException { + NamingService namingService = nacosServiceFactory.createNamingService(properties); + NamingService namingService2 = nacosServiceFactory + .createNamingService(properties); + Assert.assertTrue(namingService == namingService2); + Assert.assertEquals(1, nacosServiceFactory.getNamingServices().size()); + Assert.assertEquals(namingService, + nacosServiceFactory.getNamingServices().iterator().next()); + } - @Test - public void testGetNamingMaintainServices() throws NacosException { - NamingMaintainService maintainService = nacosServiceFactory.createNamingMaintainService(properties); - NamingMaintainService maintainService2 = nacosServiceFactory.createNamingMaintainService(properties); - Assert.assertTrue(maintainService == maintainService2); - Assert.assertEquals(1, nacosServiceFactory.getNamingMaintainService().size()); - Assert.assertEquals(maintainService, nacosServiceFactory.getNamingMaintainService().iterator().next()); - } + @Test + public void testGetNamingMaintainServices() throws NacosException { + NamingMaintainService maintainService = nacosServiceFactory + .createNamingMaintainService(properties); + NamingMaintainService maintainService2 = nacosServiceFactory + .createNamingMaintainService(properties); + Assert.assertTrue(maintainService == maintainService2); + Assert.assertEquals(1, nacosServiceFactory.getNamingMaintainService().size()); + Assert.assertEquals(maintainService, + nacosServiceFactory.getNamingMaintainService().iterator().next()); + } - @Override - protected String getServerAddressPropertyName() { - return "server.addr"; - } + @Override + protected String getServerAddressPropertyName() { + return "server.addr"; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableNacosInjectedFactoryTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableNacosInjectedFactoryTest.java index b1b3d878..fcb3539f 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableNacosInjectedFactoryTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/factory/CacheableNacosInjectedFactoryTest.java @@ -16,24 +16,24 @@ */ package com.alibaba.nacos.spring.factory; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.api.naming.pojo.Instance; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME; /** @@ -43,52 +43,50 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { - CacheableEventPublishingNacosServiceFactory.class, - CacheableNacosInjectedFactoryTest.class -}) +@ContextConfiguration(classes = { CacheableEventPublishingNacosServiceFactory.class, + CacheableNacosInjectedFactoryTest.class }) public class CacheableNacosInjectedFactoryTest { - @Bean(name = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) - public static ExecutorService executorService() { - return Executors.newSingleThreadExecutor(); - } + @Bean(name = NACOS_CONFIG_LISTENER_EXECUTOR_BEAN_NAME) + public static ExecutorService executorService() { + return Executors.newSingleThreadExecutor(); + } - @Autowired - private CacheableEventPublishingNacosServiceFactory nacosServiceFactory; + @Autowired + private CacheableEventPublishingNacosServiceFactory nacosServiceFactory; + private Properties properties = new Properties(); - private Properties properties = new Properties(); + private Properties properties2 = new Properties(); - private Properties properties2 = new Properties(); + @Before + public void init() { + properties.setProperty(PropertyKeyConst.NAMESPACE, "nc"); + properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); + properties.setProperty(PropertyKeyConst.ACCESS_KEY, "a"); + properties.setProperty(PropertyKeyConst.SECRET_KEY, "s"); - @Before - public void init() { - properties.setProperty(PropertyKeyConst.NAMESPACE, "nc"); - properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); - properties.setProperty(PropertyKeyConst.ACCESS_KEY, "a"); - properties.setProperty(PropertyKeyConst.SECRET_KEY, "s"); + properties2.setProperty(PropertyKeyConst.CLUSTER_NAME, "nc"); + properties2.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1"); + properties2.setProperty(PropertyKeyConst.ACCESS_KEY, "a"); + properties2.setProperty(PropertyKeyConst.SECRET_KEY, "s"); + } - properties2.setProperty(PropertyKeyConst.CLUSTER_NAME, "nc"); - properties2.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1"); - properties2.setProperty(PropertyKeyConst.ACCESS_KEY, "a"); - properties2.setProperty(PropertyKeyConst.SECRET_KEY, "s"); - } + @Test + public void testCreateConfigService() throws NacosException { + ConfigService configService = nacosServiceFactory.createConfigService(properties); + ConfigService configService2 = nacosServiceFactory + .createConfigService(properties2); + // throws java.lang.AssertionError + Assert.assertTrue(configService != configService2); + } - @Test - public void testCreateConfigService() throws NacosException { - ConfigService configService = nacosServiceFactory.createConfigService(properties); - ConfigService configService2 = nacosServiceFactory.createConfigService(properties2); - // throws java.lang.AssertionError - Assert.assertTrue(configService != configService2); - } - - @Test - public void testCreateNamingService() throws NacosException, InterruptedException { - NamingService namingService = nacosServiceFactory.createNamingService(properties); - NamingService namingService2 = nacosServiceFactory.createNamingService(properties2); - // throws java.lang.AssertionError - Assert.assertTrue(namingService != namingService2); - } + @Test + public void testCreateNamingService() throws NacosException, InterruptedException { + NamingService namingService = nacosServiceFactory.createNamingService(properties); + NamingService namingService2 = nacosServiceFactory + .createNamingService(properties2); + // throws java.lang.AssertionError + Assert.assertTrue(namingService != namingService2); + } } - diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/AbstractNacosHttpServerTestExecutionListener.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/AbstractNacosHttpServerTestExecutionListener.java index ccb7b394..a401cc29 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/AbstractNacosHttpServerTestExecutionListener.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/AbstractNacosHttpServerTestExecutionListener.java @@ -18,6 +18,7 @@ import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; + import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.support.AbstractTestExecutionListener; @@ -28,48 +29,51 @@ * @author Mercy * @since 0.1.0 */ -public abstract class AbstractNacosHttpServerTestExecutionListener extends AbstractTestExecutionListener { +public abstract class AbstractNacosHttpServerTestExecutionListener + extends AbstractTestExecutionListener { - private EmbeddedNacosHttpServer httpServer; + private EmbeddedNacosHttpServer httpServer; - static { - System.setProperty("nacos.standalone", "true"); - } + static { + System.setProperty("nacos.standalone", "true"); + } - @Override - public void beforeTestClass(TestContext testContext) throws Exception { - initEnvironment(testContext); - httpServer = new EmbeddedNacosHttpServer(); - init(httpServer); - System.setProperty(getServerAddressPropertyName(), "127.0.0.1:" + httpServer.getPort()); - httpServer.start(true); - } + @Override + public void beforeTestClass(TestContext testContext) throws Exception { + initEnvironment(testContext); + httpServer = new EmbeddedNacosHttpServer(); + init(httpServer); + System.setProperty(getServerAddressPropertyName(), + "127.0.0.1:" + httpServer.getPort()); + httpServer.start(true); + } - public void initEnvironment(TestContext testContext) { + public void initEnvironment(TestContext testContext) { - } + } - @Override - public final void afterTestClass(TestContext testContext) throws Exception { - httpServer.stop(); - System.getProperties().remove(getServerAddressPropertyName()); - } + @Override + public final void afterTestClass(TestContext testContext) throws Exception { + httpServer.stop(); + System.getProperties().remove(getServerAddressPropertyName()); + } - /** - * Initialize before test , this method just will be invoked once in current test case. - * - * @param server {@link EmbeddedNacosHttpServer} - */ - protected void init(EmbeddedNacosHttpServer server) { + /** + * Initialize before test , this method just will be invoked once in current test + * case. + * + * @param server {@link EmbeddedNacosHttpServer} + */ + protected void init(EmbeddedNacosHttpServer server) { - } + } - /** - * The property name of Nacos HTTP Server Address - * - * @return non-null - * @see NacosProperties#serverAddr() - */ - protected abstract String getServerAddressPropertyName(); + /** + * The property name of Nacos HTTP Server Address + * + * @return non-null + * @see NacosProperties#serverAddr() + */ + protected abstract String getServerAddressPropertyName(); } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Config.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Config.java index 4a5f4084..454e7c42 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Config.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Config.java @@ -16,13 +16,13 @@ */ package com.alibaba.nacos.spring.test; +import java.util.List; +import java.util.Map; + 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 java.util.List; -import java.util.Map; - import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.GROUP_ID; @@ -33,92 +33,85 @@ * @see NacosConfigurationProperties * @since 0.1.0 */ -@NacosConfigurationProperties(prefix = "test", dataId = DATA_ID, groupId = GROUP_ID, - autoRefreshed = true, ignoreNestedProperties = true) +@NacosConfigurationProperties(prefix = "test", dataId = DATA_ID, groupId = GROUP_ID, autoRefreshed = true, ignoreNestedProperties = true) public class Config { - private int id; + private int id; - private String name; + private String name; - private double value; + private double value; - @NacosIgnore - private Integer intData; + @NacosIgnore + private Integer intData; - @NacosProperty("float-data") - private Float floatData; + @NacosProperty("float-data") + private Float floatData; - private List list; + private List list; - private Map map; + private Map map; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public double getValue() { - return value; - } + public double getValue() { + return value; + } - public void setValue(double value) { - this.value = value; - } + public void setValue(double value) { + this.value = value; + } - public Integer getIntData() { - return intData; - } + public Integer getIntData() { + return intData; + } - public void setIntData(Integer intData) { - this.intData = intData; - } + public void setIntData(Integer intData) { + this.intData = intData; + } - public Float getFloatData() { - return floatData; - } + public Float getFloatData() { + return floatData; + } - public void setFloatData(Float floatData) { - this.floatData = floatData; - } + public void setFloatData(Float floatData) { + this.floatData = floatData; + } - public List getList() { - return list; - } + public List getList() { + return list; + } - public void setList(List list) { - this.list = list; - } + public void setList(List list) { + this.list = list; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } - public void setMap(Map map) { - this.map = map; - } + public void setMap(Map map) { + this.map = map; + } - @Override - public String toString() { - return "Config{" + - "id=" + id + - ", name='" + name + '\'' + - ", value=" + value + - ", intData=" + intData + - ", floatData=" + floatData + - ", list=" + list + - ", map=" + map + - '}'; - } + @Override + public String toString() { + return "Config{" + "id=" + id + ", name='" + name + '\'' + ", value=" + value + + ", intData=" + intData + ", floatData=" + floatData + ", list=" + list + + ", map=" + map + '}'; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Listeners.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Listeners.java index 3882d2d4..b293254f 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Listeners.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/Listeners.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.spring.test; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; + import org.springframework.context.annotation.Configuration; import static com.alibaba.nacos.spring.test.MockNacosServiceFactory.DATA_ID; @@ -30,27 +31,27 @@ @Configuration public class Listeners { - private Integer integerValue; + private Integer integerValue; - private Double doubleValue; + private Double doubleValue; - @NacosConfigListener(dataId = DATA_ID, timeout = 50) - public void onInteger(Integer value) throws Exception { - Thread.sleep(100); // timeout of execution - this.integerValue = value; - } + @NacosConfigListener(dataId = DATA_ID, timeout = 50) + public void onInteger(Integer value) throws Exception { + Thread.sleep(100); // timeout of execution + this.integerValue = value; + } - @NacosConfigListener(dataId = DATA_ID, timeout = 200) - public void onDouble(Double value) throws Exception { - Thread.sleep(100); // normal execution - this.doubleValue = value; - } + @NacosConfigListener(dataId = DATA_ID, timeout = 200) + public void onDouble(Double value) throws Exception { + Thread.sleep(100); // normal execution + this.doubleValue = value; + } - public Integer getIntegerValue() { - return integerValue; - } + public Integer getIntegerValue() { + return integerValue; + } - public Double getDoubleValue() { - return doubleValue; - } + public Double getDoubleValue() { + return doubleValue; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockConfigService.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockConfigService.java index 56a83242..b2277e42 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockConfigService.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockConfigService.java @@ -16,17 +16,18 @@ */ package com.alibaba.nacos.spring.test; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.config.listener.Listener; -import com.alibaba.nacos.api.exception.NacosException; -import org.springframework.util.CollectionUtils; - import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; 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 org.springframework.util.CollectionUtils; + /** * Mock {@link ConfigService} * @@ -35,80 +36,85 @@ */ public class MockConfigService implements ConfigService { - private Map> listenersCache = new LinkedHashMap>(); - - private Map contentCache = new LinkedHashMap(); - - public static final String TIMEOUT_ERROR_MESSAGE = "Timeout must not be less then zero."; - - @Override - public String getConfig(String dataId, String group, long timeoutMs) throws NacosException { - String key = createKey(dataId, group); - if (timeoutMs < 0) { - throw new NacosException(NacosException.SERVER_ERROR, TIMEOUT_ERROR_MESSAGE); - } - return contentCache.get(key); - } - - @Override - public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException { - return null; - } - - @Override - public void addListener(String dataId, String group, Listener listener) throws NacosException { - String key = createKey(dataId, group); - List listeners = listenersCache.get(key); - if (listeners == null) { - listeners = new LinkedList(); - listenersCache.put(key, listeners); - } - listeners.add(listener); - } - - @Override - public boolean publishConfig(String dataId, String group, final String content) throws NacosException { - String key = createKey(dataId, group); - contentCache.put(key, content); - - List listeners = listenersCache.get(key); - if (!CollectionUtils.isEmpty(listeners)) { - for (final Listener listener : listeners) { - Executor executor = listener.getExecutor(); - if (executor != null) { - executor.execute(new Runnable() { - @Override - public void run() { - listener.receiveConfigInfo(content); - } - }); - } else { - listener.receiveConfigInfo(content); - } - } - } - - return true; - } - - @Override - public boolean removeConfig(String dataId, String group) throws NacosException { - String key = createKey(dataId, group); - return contentCache.remove(key) != null; - } - - @Override - public void removeListener(String dataId, String group, Listener listener) { - String key = createKey(dataId, group); - listenersCache.remove(key); - } - - @Override - public String getServerStatus() { - return "UP"; - } - - private String createKey(String dataId, String groupId) { - return dataId + "&" + groupId; - } + private Map> listenersCache = new LinkedHashMap>(); + + private Map contentCache = new LinkedHashMap(); + + public static final String TIMEOUT_ERROR_MESSAGE = "Timeout must not be less then zero."; + + @Override + public String getConfig(String dataId, String group, long timeoutMs) + throws NacosException { + String key = createKey(dataId, group); + if (timeoutMs < 0) { + throw new NacosException(NacosException.SERVER_ERROR, TIMEOUT_ERROR_MESSAGE); + } + return contentCache.get(key); + } + + @Override + public String getConfigAndSignListener(String dataId, String group, long timeoutMs, + Listener listener) throws NacosException { + return null; + } + + @Override + public void addListener(String dataId, String group, Listener listener) + throws NacosException { + String key = createKey(dataId, group); + List listeners = listenersCache.get(key); + if (listeners == null) { + listeners = new LinkedList(); + listenersCache.put(key, listeners); + } + listeners.add(listener); + } + + @Override + public boolean publishConfig(String dataId, String group, final String content) + throws NacosException { + String key = createKey(dataId, group); + contentCache.put(key, content); + + List listeners = listenersCache.get(key); + if (!CollectionUtils.isEmpty(listeners)) { + for (final Listener listener : listeners) { + Executor executor = listener.getExecutor(); + if (executor != null) { + executor.execute(new Runnable() { + @Override + public void run() { + listener.receiveConfigInfo(content); + } + }); + } + else { + listener.receiveConfigInfo(content); + } + } + } + + return true; + } + + @Override + public boolean removeConfig(String dataId, String group) throws NacosException { + String key = createKey(dataId, group); + return contentCache.remove(key) != null; + } + + @Override + public void removeListener(String dataId, String group, Listener listener) { + String key = createKey(dataId, group); + listenersCache.remove(key); + } + + @Override + public String getServerStatus() { + return "UP"; + } + + private String createKey(String dataId, String groupId) { + return dataId + "&" + groupId; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockNacosServiceFactory.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockNacosServiceFactory.java index 1245db6f..6182e7fa 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockNacosServiceFactory.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/MockNacosServiceFactory.java @@ -16,6 +16,12 @@ */ package com.alibaba.nacos.spring.test; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingMaintainService; @@ -24,8 +30,6 @@ import com.alibaba.nacos.spring.factory.NacosServiceFactory; import org.mockito.Mockito; -import java.util.*; - import static com.alibaba.nacos.spring.util.NacosUtils.DEFAULT_TIMEOUT; import static com.alibaba.nacos.spring.util.NacosUtils.identify; @@ -37,102 +41,106 @@ */ public class MockNacosServiceFactory implements NacosServiceFactory { - public final static String DATA_ID = "testDataId"; + public final static String DATA_ID = "testDataId"; - public final static String GROUP_ID = "testGroupId"; + public final static String GROUP_ID = "testGroupId"; - public final static String CONTENT = "Hello,World 2018"; + public final static String CONTENT = "Hello,World 2018"; - private String dataId; + private String dataId; - private String groupId; + private String groupId; - private long timeout; + private long timeout; - private String content; + private String content; - private ConfigService configService; + private ConfigService configService; - private Map configServiceCache = new HashMap(); + private Map configServiceCache = new HashMap(); - public MockNacosServiceFactory() { - this(DATA_ID, GROUP_ID, DEFAULT_TIMEOUT, CONTENT); - } + public MockNacosServiceFactory() { + this(DATA_ID, GROUP_ID, DEFAULT_TIMEOUT, CONTENT); + } - public MockNacosServiceFactory(String dataId, String groupId, long timeout, String content) { - this.dataId = dataId; - this.groupId = groupId; - this.timeout = timeout; - this.content = content; - } + public MockNacosServiceFactory(String dataId, String groupId, long timeout, + String content) { + this.dataId = dataId; + this.groupId = groupId; + this.timeout = timeout; + this.content = content; + } - public String getDataId() { - return dataId; - } + public String getDataId() { + return dataId; + } - public void setDataId(String dataId) { - this.dataId = dataId; - } + public void setDataId(String dataId) { + this.dataId = dataId; + } - public String getGroupId() { - return groupId; - } + public String getGroupId() { + return groupId; + } - public void setGroupId(String groupId) { - this.groupId = groupId; - } + public void setGroupId(String groupId) { + this.groupId = groupId; + } - public String getContent() { - return content; - } + public String getContent() { + return content; + } - public void setContent(String content) { - this.content = content; - } + public void setContent(String content) { + this.content = content; + } - public ConfigService getConfigService() { - return configService; - } + public ConfigService getConfigService() { + return configService; + } - public void setConfigService(ConfigService configService) { - this.configService = configService; - } + public void setConfigService(ConfigService configService) { + this.configService = configService; + } - @Override - public ConfigService createConfigService(Properties properties) throws NacosException { - if (configService != null) { - return configService; - } - String key = identify(properties); - ConfigService configService = configServiceCache.get(key); - if (configService == null) { - configService = new NacosConfigService(properties); - } - return configService; - } + @Override + public ConfigService createConfigService(Properties properties) + throws NacosException { + if (configService != null) { + return configService; + } + String key = identify(properties); + ConfigService configService = configServiceCache.get(key); + if (configService == null) { + configService = new NacosConfigService(properties); + } + return configService; + } - @Override - public NamingService createNamingService(Properties properties) throws NacosException { - return Mockito.mock(NamingService.class); - } + @Override + public NamingService createNamingService(Properties properties) + throws NacosException { + return Mockito.mock(NamingService.class); + } - @Override - public NamingMaintainService createNamingMaintainService(Properties properties) throws NacosException { - return Mockito.mock(NamingMaintainService.class); - } + @Override + public NamingMaintainService createNamingMaintainService(Properties properties) + throws NacosException { + return Mockito.mock(NamingMaintainService.class); + } - @Override - public Collection getConfigServices() { - return configServiceCache.values(); - } + @Override + public Collection getConfigServices() { + return configServiceCache.values(); + } - @Override - public Collection getNamingServices() { - return Collections.emptyList(); - } + @Override + public Collection getNamingServices() { + return Collections.emptyList(); + } - @Override - public Collection getNamingMaintainService() { - return Collections.emptyList(); - } + @Override + public Collection getNamingMaintainService() { + return Collections.emptyList(); + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestApplicationHolder.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestApplicationHolder.java index 38a298ac..24dcd823 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestApplicationHolder.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestApplicationHolder.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.spring.test; import com.alibaba.nacos.spring.factory.ApplicationContextHolder; + import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -28,11 +29,12 @@ @Configuration public class TestApplicationHolder { - @Bean(name = ApplicationContextHolder.BEAN_NAME) - public ApplicationContextHolder applicationContextHolder(ApplicationContext applicationContext) { - ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); - applicationContextHolder.setApplicationContext(applicationContext); - return applicationContextHolder; - } + @Bean(name = ApplicationContextHolder.BEAN_NAME) + public ApplicationContextHolder applicationContextHolder( + ApplicationContext applicationContext) { + ApplicationContextHolder applicationContextHolder = new ApplicationContextHolder(); + applicationContextHolder.setApplicationContext(applicationContext); + return applicationContextHolder; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestConfiguration.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestConfiguration.java index dc5cf420..bc70c130 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestConfiguration.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/TestConfiguration.java @@ -16,18 +16,15 @@ */ package com.alibaba.nacos.spring.test; +import java.util.Properties; + import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.spring.factory.CacheableEventPublishingNacosServiceFactory; -import com.alibaba.nacos.spring.factory.NacosServiceFactory; -import org.springframework.beans.factory.ListableBeanFactory; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; -import java.util.Map; -import java.util.Properties; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME; /** @@ -39,37 +36,29 @@ @Configuration public class TestConfiguration { - /** - * The bean name of {@link ConfigService} - */ - public static final String CONFIG_SERVICE_BEAN_NAME = "configService"; - - public static final String TEST_CONFIG = "test.id = 1\n" + - "test.name = mercyblitz\n" + - "test.value = 0.95\n" + - "test.intData = 1234\n" + - "test.float-data = 1234.5\n" + - "test.list = 1,2,3,4,5\n" + - "test.map[key-1]=value"; + /** + * The bean name of {@link ConfigService} + */ + public static final String CONFIG_SERVICE_BEAN_NAME = "configService"; - public static final String MODIFIED_TEST_CONTEXT = "id = 1\n" + - "test.name = mercyblitz@gmail.com\n" + - "test.value = 9527\n" + - "test.list[0] = 6\n" + - "test.list[1] = 6\n" + - "test.list[2] = 6\n" + - "test.list[3] = 6\n" + - "test.map[key-2]=value\n" + - "test.map[key-3]=value"; + public static final String TEST_CONFIG = "test.id = 1\n" + "test.name = mercyblitz\n" + + "test.value = 0.95\n" + "test.intData = 1234\n" + + "test.float-data = 1234.5\n" + "test.list = 1,2,3,4,5\n" + + "test.map[key-1]=value"; + public static final String MODIFIED_TEST_CONTEXT = "id = 1\n" + + "test.name = mercyblitz@gmail.com\n" + "test.value = 9527\n" + + "test.list[0] = 6\n" + "test.list[1] = 6\n" + "test.list[2] = 6\n" + + "test.list[3] = 6\n" + "test.map[key-2]=value\n" + "test.map[key-3]=value"; - @Bean(name = GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - public Properties globalNacosProperties() { - Properties properties = new Properties(); - if (!StringUtils.isEmpty(System.getProperty("server.addr"))) { - properties.put(PropertyKeyConst.SERVER_ADDR, System.getProperty("server.addr")); - } - return properties; - } + @Bean(name = GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + public Properties globalNacosProperties() { + Properties properties = new Properties(); + if (!StringUtils.isEmpty(System.getProperty("server.addr"))) { + properties.put(PropertyKeyConst.SERVER_ADDR, + System.getProperty("server.addr")); + } + return properties; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/User.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/User.java index 21e2cc51..b3781b27 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/User.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/User.java @@ -24,32 +24,29 @@ */ public class User { - private Long id; + private Long id; - private String name; + private String name; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Override - public String toString() { - return "User{" + - "id=" + id + - ", name='" + name + '\'' + - '}'; - } + @Override + public String toString() { + return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/XmlApp.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/XmlApp.java index 5923012a..d884854f 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/XmlApp.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/XmlApp.java @@ -16,11 +16,11 @@ */ package com.alibaba.nacos.spring.test; +import java.util.List; + import com.alibaba.nacos.api.config.ConfigType; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; -import java.util.List; - import static com.alibaba.nacos.spring.test.XmlApp.DATA_ID_XML; /** @@ -30,54 +30,48 @@ @NacosConfigurationProperties(dataId = DATA_ID_XML, autoRefreshed = true, ignoreNestedProperties = true, type = ConfigType.XML) public class XmlApp { - public static final String DATA_ID_XML = "xml_app"; + public static final String DATA_ID_XML = "xml_app"; - private List students; + private List students; - public List getStudents() { - return students; - } + public List getStudents() { + return students; + } - public void setStudents(List students) { - this.students = students; - } + public void setStudents(List students) { + this.students = students; + } - @Override - public String toString() { - return "XmlApp{" + - "students=" + students + - '}'; - } + @Override + public String toString() { + return "XmlApp{" + "students=" + students + '}'; + } - public static class Student { + public static class Student { - private String name; - private String num; + private String name; + private String num; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getNum() { - return num; - } + public String getNum() { + return num; + } - public void setNum(String num) { - this.num = num; - } + public void setNum(String num) { + this.num = num; + } - @Override - public String toString() { - return "Student{" + - "name='" + name + '\'' + - ", num='" + num + '\'' + - '}'; - } - } + @Override + public String toString() { + return "Student{" + "name='" + name + '\'' + ", num='" + num + '\'' + '}'; + } + } } - diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/YamlApp.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/YamlApp.java index 6942154e..2e455e42 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/YamlApp.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/test/YamlApp.java @@ -16,12 +16,10 @@ */ package com.alibaba.nacos.spring.test; -import com.alibaba.nacos.api.config.ConfigType; -import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; - import java.util.List; -import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; +import com.alibaba.nacos.api.config.ConfigType; +import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; /** * @author liaochuntao @@ -30,53 +28,48 @@ @NacosConfigurationProperties(dataId = "yaml_app.yml", autoRefreshed = true, ignoreNestedProperties = true, type = ConfigType.YAML) public class YamlApp { - public static final String DATA_ID_YAML = "yaml_app"; + public static final String DATA_ID_YAML = "yaml_app"; - private List students; + private List students; - public List getStudents() { - return students; - } + public List getStudents() { + return students; + } - public void setStudents(List students) { - this.students = students; - } + public void setStudents(List students) { + this.students = students; + } - @Override - public String toString() { - return "YamlApp{" + - "students=" + students + - '}'; - } + @Override + public String toString() { + return "YamlApp{" + "students=" + students + '}'; + } - public static class Student { + public static class Student { - private String name; - private String num; + private String name; + private String num; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getNum() { - return num; - } + public String getNum() { + return num; + } - public void setNum(String num) { - this.num = num; - } + public void setNum(String num) { + this.num = num; + } - @Override - public String toString() { - return "Student{" + - "name='" + name + '\'' + - ", num='" + num + '\'' + - '}'; - } - } + @Override + public String toString() { + return "Student{" + "name='" + name + '\'' + ", num='" + num + '\'' + '}'; + } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/ConfigParseUtilsTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/ConfigParseUtilsTest.java index f1cefaa8..caa4611e 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/ConfigParseUtilsTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/ConfigParseUtilsTest.java @@ -1,12 +1,10 @@ package com.alibaba.nacos.spring.util; -import org.junit.Assert; -import org.junit.Test; - import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.*; +import org.junit.Assert; +import org.junit.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -30,74 +28,65 @@ */ public class ConfigParseUtilsTest { - private static String dataId = "data-id-1"; - private static String group = "group"; - private static AtomicInteger atomicInteger = new AtomicInteger(0); + private static String dataId = "data-id-1"; + private static String group = "group"; + private static AtomicInteger atomicInteger = new AtomicInteger(0); - public static class CustomerParse extends AbstractConfigParse { + public static class CustomerParse extends AbstractConfigParse { - @Override - public Properties parse(String configText) { - atomicInteger.incrementAndGet(); - return new Properties(); - } + @Override + public Properties parse(String configText) { + atomicInteger.incrementAndGet(); + return new Properties(); + } - @Override - public String processType() { - return "xml"; - } + @Override + public String processType() { + return "xml"; + } - @Override - public String dataId() { - return dataId; - } + @Override + public String dataId() { + return dataId; + } - @Override - public String group() { - return group; - } - } + @Override + public String group() { + return group; + } + } - @Test - public void testConfigParse() { - String xmlConfig = "\n" + - " \n" + - " \n" + - " lct-1\n" + - " 1006010022\n" + - " major-1\n" + - "
hangzhou
\n" + - " 123456\n" + - "
\n" + - " \n" + - " lct-2\n" + - " 1006010033\n" + - " major-2\n" + - "
shengzheng
\n" + - " 234567\n" + - "
\n" + - " \n" + - " lct-3\n" + - " 1006010044\n" + - " major-3\n" + - "
wenzhou
\n" + - " 345678\n" + - "
\n" + - " \n" + - " lct-4\n" + - " 1006010055\n" + - " major-3\n" + - "
wuhan
\n" + - " 456789\n" + - "
\n" + - "
\n" + - "
"; - Assert.assertEquals(0, ConfigParseUtils.toProperties(dataId, group, xmlConfig, "xml").size()); - Assert.assertEquals(1, atomicInteger.get()); - Properties properties = ConfigParseUtils.toProperties(xmlConfig, "XML"); - Assert.assertTrue(0 != properties.size()); - System.out.println(ConfigParse.class.isAssignableFrom(CustomerParse.class)); - System.out.println(properties); - } + @Test + public void testConfigParse() { + String xmlConfig = "\n" + " \n" + " \n" + + " lct-1\n" + + " 1006010022\n" + + " major-1\n" + + "
hangzhou
\n" + + " 123456\n" + "
\n" + + " \n" + " lct-2\n" + + " 1006010033\n" + + " major-2\n" + + "
shengzheng
\n" + + " 234567\n" + "
\n" + + " \n" + " lct-3\n" + + " 1006010044\n" + + " major-3\n" + + "
wenzhou
\n" + + " 345678\n" + "
\n" + + " \n" + " lct-4\n" + + " 1006010055\n" + + " major-3\n" + + "
wuhan
\n" + + " 456789\n" + "
\n" + + "
\n" + "
"; + Assert.assertEquals(0, + ConfigParseUtils.toProperties(dataId, group, xmlConfig, "xml").size()); + Assert.assertEquals(1, atomicInteger.get()); + Properties properties = ConfigParseUtils.toProperties(xmlConfig, "XML"); + Assert.assertTrue(0 != properties.size()); + System.out.println(ConfigParse.class.isAssignableFrom(CustomerParse.class)); + System.out.println(properties); + } } \ No newline at end of file diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosBeanUtilsTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosBeanUtilsTest.java index c2a61330..b67ebd6e 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosBeanUtilsTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosBeanUtilsTest.java @@ -16,14 +16,15 @@ */ package com.alibaba.nacos.spring.util; +import java.util.Properties; + import com.alibaba.nacos.spring.factory.ApplicationContextHolder; -import com.alibaba.nacos.spring.factory.CacheableEventPublishingNacosServiceFactory; -import com.alibaba.nacos.spring.factory.NacosServiceFactory; import com.alibaba.nacos.spring.test.TestApplicationHolder; import com.alibaba.nacos.spring.test.TestConfiguration; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -31,8 +32,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.Properties; - import static com.alibaba.nacos.spring.util.NacosBeanUtils.GLOBAL_NACOS_PROPERTIES_BEAN_NAME; import static com.alibaba.nacos.spring.util.NacosBeanUtils.isBeanDefinitionPresent; @@ -43,34 +42,37 @@ * @since 0.1.0 */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {TestConfiguration.class, TestApplicationHolder.class}) +@ContextConfiguration(classes = { TestConfiguration.class, TestApplicationHolder.class }) public class NacosBeanUtilsTest { - @Autowired - private BeanFactory beanFactory; + @Autowired + private BeanFactory beanFactory; - @Autowired - @Qualifier(GLOBAL_NACOS_PROPERTIES_BEAN_NAME) - private Properties globalProperties; + @Autowired + @Qualifier(GLOBAL_NACOS_PROPERTIES_BEAN_NAME) + private Properties globalProperties; - @Autowired - private ApplicationContextHolder contextHolder; + @Autowired + private ApplicationContextHolder contextHolder; - @Test - public void testBeans() { + @Test + public void testBeans() { - Assert.assertEquals(globalProperties, NacosBeanUtils.getGlobalPropertiesBean(beanFactory)); - Assert.assertEquals(contextHolder, NacosBeanUtils.getApplicationContextHolder(beanFactory)); + Assert.assertEquals(globalProperties, + NacosBeanUtils.getGlobalPropertiesBean(beanFactory)); + Assert.assertEquals(contextHolder, + NacosBeanUtils.getApplicationContextHolder(beanFactory)); - } + } - @Test - public void testIsBeanDefinitionPresent() { + @Test + public void testIsBeanDefinitionPresent() { - BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; - Assert.assertTrue(isBeanDefinitionPresent(registry, GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)); + Assert.assertTrue(isBeanDefinitionPresent(registry, + GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)); - } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosUtilsTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosUtilsTest.java index 38134b4c..15daf50c 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosUtilsTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/NacosUtilsTest.java @@ -16,13 +16,14 @@ */ package com.alibaba.nacos.spring.util; +import java.lang.reflect.Field; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import org.junit.Assert; import org.junit.Test; -import org.springframework.util.ReflectionUtils; -import java.lang.reflect.Field; +import org.springframework.util.ReflectionUtils; /** * {@link NacosUtils} Test @@ -32,28 +33,28 @@ */ public class NacosUtilsTest { - @NacosInjected - private Object object = new Object(); + @NacosInjected + private Object object = new Object(); - @NacosInjected(properties = @NacosProperties(serverAddr = "test")) - private Object object2 = new Object(); + @NacosInjected(properties = @NacosProperties(serverAddr = "test")) + private Object object2 = new Object(); - @Test - public void testIsDefault() { + @Test + public void testIsDefault() { - testIsDefault("object", true); - testIsDefault("object2", false); - } + testIsDefault("object", true); + testIsDefault("object2", false); + } - private void testIsDefault(String fieldName, boolean expectedValue) { + private void testIsDefault(String fieldName, boolean expectedValue) { - Field objectField = ReflectionUtils.findField(getClass(), fieldName); + Field objectField = ReflectionUtils.findField(getClass(), fieldName); - NacosInjected nacosInjected = objectField.getAnnotation(NacosInjected.class); + NacosInjected nacosInjected = objectField.getAnnotation(NacosInjected.class); - NacosProperties nacosProperties = nacosInjected.properties(); + NacosProperties nacosProperties = nacosInjected.properties(); - Assert.assertEquals(expectedValue, NacosUtils.isDefault(nacosProperties)); + Assert.assertEquals(expectedValue, NacosUtils.isDefault(nacosProperties)); - } + } } diff --git a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolverTest.java b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolverTest.java index 36143695..6dd3b245 100644 --- a/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolverTest.java +++ b/nacos-spring-context/src/test/java/com/alibaba/nacos/spring/util/PropertiesPlaceholderResolverTest.java @@ -16,14 +16,15 @@ */ package com.alibaba.nacos.spring.util; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.mock.env.MockEnvironment; - import java.util.HashMap; import java.util.Map; import java.util.Properties; +import org.junit.Assert; +import org.junit.Test; + +import org.springframework.mock.env.MockEnvironment; + /** * {@link PropertiesPlaceholderResolver} Test * @@ -32,26 +33,26 @@ */ public class PropertiesPlaceholderResolverTest { - @Test - public void testResolve() { - - MockEnvironment environment = new MockEnvironment(); + @Test + public void testResolve() { - PropertiesPlaceholderResolver resolver = new PropertiesPlaceholderResolver(environment); + MockEnvironment environment = new MockEnvironment(); - Map properties = new HashMap(); - properties.put("my.name", "${my.name}"); - properties.put("my.age", 18); + PropertiesPlaceholderResolver resolver = new PropertiesPlaceholderResolver( + environment); - environment.setProperty("my.name", "mercyblitz"); - environment.setProperty("my.age", "18"); + Map properties = new HashMap(); + properties.put("my.name", "${my.name}"); + properties.put("my.age", 18); - Properties resolvedProperties = resolver.resolve(properties); + environment.setProperty("my.name", "mercyblitz"); + environment.setProperty("my.age", "18"); - Assert.assertEquals(resolvedProperties.get("my.name"), "mercyblitz"); - Assert.assertNull(resolvedProperties.get("my.age")); + Properties resolvedProperties = resolver.resolve(properties); + Assert.assertEquals(resolvedProperties.get("my.name"), "mercyblitz"); + Assert.assertNull(resolvedProperties.get("my.age")); - } + } } diff --git a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/EmbeddedNacosHttpServer.java b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/EmbeddedNacosHttpServer.java index 6aab33db..35a309cd 100644 --- a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/EmbeddedNacosHttpServer.java +++ b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/EmbeddedNacosHttpServer.java @@ -16,10 +16,6 @@ */ package com.alibaba.nacos.embedded.web.server; -import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.client.utils.ParamUtil; -import com.sun.net.httpserver.HttpServer; - import java.io.IOException; import java.net.InetSocketAddress; import java.util.Map; @@ -27,6 +23,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; +import com.alibaba.nacos.api.common.Constants; +import com.alibaba.nacos.client.utils.ParamUtil; +import com.sun.net.httpserver.HttpServer; + /** * Embedded Nacos HTTP Server * @@ -35,81 +35,87 @@ */ public class EmbeddedNacosHttpServer { - private final HttpServer httpServer; + private final HttpServer httpServer; - private final int port; + private final int port; - private final String path = "/" + ParamUtil.getDefaultContextPath() + Constants.CONFIG_CONTROLLER_PATH; + private final String path = "/" + ParamUtil.getDefaultContextPath() + + Constants.CONFIG_CONTROLLER_PATH; - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private final ExecutorService executorService = Executors.newSingleThreadExecutor(); - private Future future; + private Future future; - private NacosConfigHttpHandler nacosConfigHttpHandler; + private NacosConfigHttpHandler nacosConfigHttpHandler; - public EmbeddedNacosHttpServer() throws IOException { - this.httpServer = HttpServer.create(new InetSocketAddress(0), 0); - this.port = httpServer.getAddress().getPort(); - this.nacosConfigHttpHandler = new NacosConfigHttpHandler(); - } + public EmbeddedNacosHttpServer() throws IOException { + this.httpServer = HttpServer.create(new InetSocketAddress(0), 0); + this.port = httpServer.getAddress().getPort(); + this.nacosConfigHttpHandler = new NacosConfigHttpHandler(); + } - public EmbeddedNacosHttpServer(int port) throws IOException { - this.httpServer = HttpServer.create(new InetSocketAddress(port), 0); - this.port = port; - } + public EmbeddedNacosHttpServer(int port) throws IOException { + this.httpServer = HttpServer.create(new InetSocketAddress(port), 0); + this.port = port; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } - public void initConfig(Map map) { - nacosConfigHttpHandler.cacheConfig(map); - } + public void initConfig(Map map) { + nacosConfigHttpHandler.cacheConfig(map); + } - public EmbeddedNacosHttpServer start(boolean blocking) { + public EmbeddedNacosHttpServer start(boolean blocking) { - httpServer.createContext(path, nacosConfigHttpHandler); + httpServer.createContext(path, nacosConfigHttpHandler); - nacosConfigHttpHandler.init(); + nacosConfigHttpHandler.init(); - if (blocking) { - startServer(); - } else { - future = executorService.submit(new Runnable() { - @Override - public void run() { - startServer(); - } - }); - } + if (blocking) { + startServer(); + } + else { + future = executorService.submit(new Runnable() { + @Override + public void run() { + startServer(); + } + }); + } - return this; - } + return this; + } - private void startServer() { - httpServer.start(); - String threadName = Thread.currentThread().getName(); - System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is starting...%n", threadName, port); - System.out.printf("[%s] Embedded Nacos HTTP Server mapped request URI : %s...%n", threadName, path); - } + private void startServer() { + httpServer.start(); + String threadName = Thread.currentThread().getName(); + System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is starting...%n", + threadName, port); + System.out.printf("[%s] Embedded Nacos HTTP Server mapped request URI : %s...%n", + threadName, path); + } - public EmbeddedNacosHttpServer stop() { - String threadName = Thread.currentThread().getName(); - System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is stopping...%n", threadName, port); + public EmbeddedNacosHttpServer stop() { + String threadName = Thread.currentThread().getName(); + System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is stopping...%n", + threadName, port); - if (future != null) { - if (!future.isDone()) { - future.cancel(true); - } - executorService.shutdown(); - } + if (future != null) { + if (!future.isDone()) { + future.cancel(true); + } + executorService.shutdown(); + } - httpServer.stop(0); + httpServer.stop(0); - nacosConfigHttpHandler.destroy(); + nacosConfigHttpHandler.destroy(); - System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is stopped.%n", threadName, port); + System.out.printf("[%s] Embedded Nacos HTTP Server(port : %d) is stopped.%n", + threadName, port); - return this; - } + return this; + } } diff --git a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/NacosConfigHttpHandler.java b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/NacosConfigHttpHandler.java index 3933ef96..73502443 100644 --- a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/NacosConfigHttpHandler.java +++ b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/server/NacosConfigHttpHandler.java @@ -16,6 +16,22 @@ */ package com.alibaba.nacos.embedded.web.server; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.common.util.Md5Utils; @@ -23,19 +39,10 @@ import com.sun.net.httpserver.HttpHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.util.StreamUtils; import org.springframework.util.StringUtils; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - import static java.nio.charset.Charset.forName; /** @@ -51,273 +58,289 @@ */ public class NacosConfigHttpHandler implements HttpHandler { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private Map contentCache = new HashMap(); - - private Map longPollingMap = new HashMap(); - - private ScheduledExecutorService scheduledExecutorService; - - private volatile boolean isRunning; - - public static final String DATA_ID_PARAM_NAME = "dataId"; - - public static final String GROUP_ID_PARAM_NAME = "group"; - - public static final String CONTENT_PARAM_NAME = "content"; - - private static final Object LOCK = new Object(); - - public void init() { - isRunning = true; - final int maxWaitInSecond = 3; - scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); - scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - while (isRunning) { - synchronized (LOCK) { - Set keySet = new HashSet(longPollingMap.keySet()); - for (String contentKey : keySet) { - LongPolling longPolling = longPollingMap.get(contentKey); - if (longPolling == null) { - continue; - } - if (System.currentTimeMillis() - longPolling.date.getTime() > (maxWaitInSecond * 1000L)) { - try { - write(longPolling.httpExchange, ""); - } catch (IOException e) { - logger.error("Polling task encountered an exception, contentKey: " + contentKey, e); - } - removeLongPolling(longPolling.httpExchange); - } - } - } - } - } - }, maxWaitInSecond, maxWaitInSecond, TimeUnit.SECONDS); - } - - - @Override - public void handle(HttpExchange httpExchange) throws IOException { - String method = httpExchange.getRequestMethod(); - if ("GET".equals(method)) { - handleGetConfig(httpExchange); - } else if ("POST".equals(method)) { - String queryString = StreamUtils.copyToString(httpExchange.getRequestBody(), forName("UTF-8")); - Map params = parseParams(queryString); - String listeningConfigs = params.get("Listening-Configs"); - if (listeningConfigs != null) { - handleLongPolling(httpExchange, listeningConfigs); - } else { - handlePublishConfig(httpExchange, params); - } - } else if ("DELETE".equals(method)) { - handleRemoveConfig(httpExchange); - } - } - - /** - * Handle {@link ConfigService#publishConfig(String, String, String)} - * - * @param httpExchange {@link HttpExchange} - * @throws IOException IO error - */ - private void handlePublishConfig(HttpExchange httpExchange, Map params) throws IOException { - cacheConfig(params); - - notifyLongPolling(params); - - write(httpExchange, "true"); - } - - private void notifyLongPolling(Map params) throws IOException { - String contentKey = createContentKey(params); - synchronized (LOCK) { - LongPolling longPolling = longPollingMap.get(contentKey); - if (longPolling != null) { - String dataId = params.get(DATA_ID_PARAM_NAME); - String groupId = params.get(GROUP_ID_PARAM_NAME); - String longPollingResult = createLongPollingResult(dataId, groupId); - removeLongPolling(longPolling.httpExchange); - write(longPolling.httpExchange, longPollingResult); - } - } - } - - private void removeLongPolling(HttpExchange httpExchange) { - Set keySet = new HashSet(longPollingMap.keySet()); - for (String key : keySet) { - LongPolling longPolling = longPollingMap.get(key); - if (longPolling == null) { - continue; - } - if (longPolling.httpExchange.equals(httpExchange)) { - longPollingMap.remove(key); - } - } - } - - private String createLongPollingResult(String dataId, String groupId) throws IOException { - String sb = dataId + Constants.WORD_SEPARATOR + groupId + Constants.LINE_SEPARATOR; - return URLEncoder.encode(sb, "UTF-8"); - } - - private void handleLongPolling(HttpExchange httpExchange, String listeningConfigs) throws IOException { - // @see ClientWorker.checkUpdateDataIds - listeningConfigs = URLDecoder.decode(listeningConfigs, "UTF-8"); - - List changeDataIdList = new ArrayList(); - List changeGroupIdList = new ArrayList(); - List contentKeyList = new ArrayList(); - - String[] lines = listeningConfigs.split(Constants.LINE_SEPARATOR); - for (String line : lines) { - parseLine(changeDataIdList, changeGroupIdList, contentKeyList, line); - } - - if (!changeDataIdList.isEmpty()) { - String longPollingResult = createLongPollingResult(changeDataIdList, changeGroupIdList); - write(httpExchange, longPollingResult); - return; - } - - synchronized (LOCK) { - for (String contentKey : contentKeyList) { - longPollingMap.put(contentKey, new LongPolling(httpExchange)); - } - } - } - - private void parseLine(List changeDataIdList, List changeGroupIdList, List contentKeyList, - String line) { - String[] arr = line.split(Constants.WORD_SEPARATOR, 3); - if (arr.length < 3) { - logger.warn("Listening-Configs is wrong format, line: {}", line); - return; - } - String dataId = arr[0]; - String groupId = arr[1]; - String md5 = arr[2]; - String contentKey = createContentKey(dataId, groupId); - String content = contentCache.get(contentKey); - if (content != null) { - if (!md5.equals(Md5Utils.getMD5(content, "UTF-8"))) { - changeDataIdList.add(dataId); - changeGroupIdList.add(groupId); - return; - } - } - contentKeyList.add(contentKey); - } - - private String createLongPollingResult(List dataIdList, List groupIdList) throws IOException { - StringBuilder sb = new StringBuilder(); - int size = dataIdList.size(); - for (int i = 0; i < size; i++) { - sb.append(dataIdList.get(i)); - sb.append(Constants.WORD_SEPARATOR); - sb.append(groupIdList.get(i)); - sb.append(Constants.LINE_SEPARATOR); - } - return URLEncoder.encode(sb.toString(), "UTF-8"); - } - - public void cacheConfig(Map params) { - String content = params.get(CONTENT_PARAM_NAME); - - String key = createContentKey(params); - - contentCache.put(key, content); - } - - /** - * Handle {@link ConfigService#getConfig(String, String, long)} - * - * @param httpExchange {@link HttpExchange} - * @throws IOException IO error - */ - private void handleGetConfig(HttpExchange httpExchange) throws IOException { - - URI requestURI = httpExchange.getRequestURI(); - - String queryString = requestURI.getQuery(); - - Map params = parseParams(queryString); - - String key = createContentKey(params); - - String content = contentCache.get(key); - - write(httpExchange, content); - } - - /** - * Handle {@link ConfigService#removeConfig(String, String)} - * - * @param httpExchange {@link HttpExchange} - * @throws IOException IO error - */ - private void handleRemoveConfig(HttpExchange httpExchange) throws IOException { - - URI requestURI = httpExchange.getRequestURI(); - - String queryString = requestURI.getQuery(); - - Map params = parseParams(queryString); - - String key = createContentKey(params); - - contentCache.remove(key); - - write(httpExchange, "OK"); - } - - private String createContentKey(Map params) { - String dataId = params.get(DATA_ID_PARAM_NAME); - String groupId = params.get(GROUP_ID_PARAM_NAME); - return createContentKey(dataId, groupId); - } - - private String createContentKey(String dataId, String groupId) { - return dataId + " | " + groupId; - } - - private void write(HttpExchange httpExchange, String content) throws IOException { - if (content != null) { - OutputStream outputStream = httpExchange.getResponseBody(); - httpExchange.sendResponseHeaders(200, content.length()); - StreamUtils.copy(URLDecoder.decode(content, "UTF-8"), forName("UTF-8"), outputStream); - } - httpExchange.close(); - } - - private Map parseParams(String queryString) { - Map params = new HashMap(); - String[] parts = StringUtils.delimitedListToStringArray(queryString, "&"); - for (String part : parts) { - String[] nameAndValue = StringUtils.split(part, "="); - params.put(StringUtils.trimAllWhitespace(nameAndValue[0]), StringUtils.trimAllWhitespace(nameAndValue[1])); - } - return params; - } - - public void destroy() { - isRunning = false; - if(scheduledExecutorService != null){ - scheduledExecutorService.shutdown(); - } - } - - private static class LongPolling { - private HttpExchange httpExchange; - private Date date; - - LongPolling(HttpExchange httpExchange) { - this.httpExchange = httpExchange; - this.date = new Date(); - } - } + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private Map contentCache = new HashMap(); + + private Map longPollingMap = new HashMap(); + + private ScheduledExecutorService scheduledExecutorService; + + private volatile boolean isRunning; + + public static final String DATA_ID_PARAM_NAME = "dataId"; + + public static final String GROUP_ID_PARAM_NAME = "group"; + + public static final String CONTENT_PARAM_NAME = "content"; + + private static final Object LOCK = new Object(); + + public void init() { + isRunning = true; + final int maxWaitInSecond = 3; + scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); + scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + while (isRunning) { + synchronized (LOCK) { + Set keySet = new HashSet(longPollingMap.keySet()); + for (String contentKey : keySet) { + LongPolling longPolling = longPollingMap.get(contentKey); + if (longPolling == null) { + continue; + } + if (System.currentTimeMillis() - longPolling.date + .getTime() > (maxWaitInSecond * 1000L)) { + try { + write(longPolling.httpExchange, ""); + } + catch (IOException e) { + logger.error( + "Polling task encountered an exception, contentKey: " + + contentKey, + e); + } + removeLongPolling(longPolling.httpExchange); + } + } + } + } + } + }, maxWaitInSecond, maxWaitInSecond, TimeUnit.SECONDS); + } + + @Override + public void handle(HttpExchange httpExchange) throws IOException { + String method = httpExchange.getRequestMethod(); + if ("GET".equals(method)) { + handleGetConfig(httpExchange); + } + else if ("POST".equals(method)) { + String queryString = StreamUtils.copyToString(httpExchange.getRequestBody(), + forName("UTF-8")); + Map params = parseParams(queryString); + String listeningConfigs = params.get("Listening-Configs"); + if (listeningConfigs != null) { + handleLongPolling(httpExchange, listeningConfigs); + } + else { + handlePublishConfig(httpExchange, params); + } + } + else if ("DELETE".equals(method)) { + handleRemoveConfig(httpExchange); + } + } + + /** + * Handle {@link ConfigService#publishConfig(String, String, String)} + * + * @param httpExchange {@link HttpExchange} + * @throws IOException IO error + */ + private void handlePublishConfig(HttpExchange httpExchange, + Map params) throws IOException { + cacheConfig(params); + + notifyLongPolling(params); + + write(httpExchange, "true"); + } + + private void notifyLongPolling(Map params) throws IOException { + String contentKey = createContentKey(params); + synchronized (LOCK) { + LongPolling longPolling = longPollingMap.get(contentKey); + if (longPolling != null) { + String dataId = params.get(DATA_ID_PARAM_NAME); + String groupId = params.get(GROUP_ID_PARAM_NAME); + String longPollingResult = createLongPollingResult(dataId, groupId); + removeLongPolling(longPolling.httpExchange); + write(longPolling.httpExchange, longPollingResult); + } + } + } + + private void removeLongPolling(HttpExchange httpExchange) { + Set keySet = new HashSet(longPollingMap.keySet()); + for (String key : keySet) { + LongPolling longPolling = longPollingMap.get(key); + if (longPolling == null) { + continue; + } + if (longPolling.httpExchange.equals(httpExchange)) { + longPollingMap.remove(key); + } + } + } + + private String createLongPollingResult(String dataId, String groupId) + throws IOException { + String sb = dataId + Constants.WORD_SEPARATOR + groupId + + Constants.LINE_SEPARATOR; + return URLEncoder.encode(sb, "UTF-8"); + } + + private void handleLongPolling(HttpExchange httpExchange, String listeningConfigs) + throws IOException { + // @see ClientWorker.checkUpdateDataIds + listeningConfigs = URLDecoder.decode(listeningConfigs, "UTF-8"); + + List changeDataIdList = new ArrayList(); + List changeGroupIdList = new ArrayList(); + List contentKeyList = new ArrayList(); + + String[] lines = listeningConfigs.split(Constants.LINE_SEPARATOR); + for (String line : lines) { + parseLine(changeDataIdList, changeGroupIdList, contentKeyList, line); + } + + if (!changeDataIdList.isEmpty()) { + String longPollingResult = createLongPollingResult(changeDataIdList, + changeGroupIdList); + write(httpExchange, longPollingResult); + return; + } + + synchronized (LOCK) { + for (String contentKey : contentKeyList) { + longPollingMap.put(contentKey, new LongPolling(httpExchange)); + } + } + } + + private void parseLine(List changeDataIdList, List changeGroupIdList, + List contentKeyList, String line) { + String[] arr = line.split(Constants.WORD_SEPARATOR, 3); + if (arr.length < 3) { + logger.warn("Listening-Configs is wrong format, line: {}", line); + return; + } + String dataId = arr[0]; + String groupId = arr[1]; + String md5 = arr[2]; + String contentKey = createContentKey(dataId, groupId); + String content = contentCache.get(contentKey); + if (content != null) { + if (!md5.equals(Md5Utils.getMD5(content, "UTF-8"))) { + changeDataIdList.add(dataId); + changeGroupIdList.add(groupId); + return; + } + } + contentKeyList.add(contentKey); + } + + private String createLongPollingResult(List dataIdList, + List groupIdList) throws IOException { + StringBuilder sb = new StringBuilder(); + int size = dataIdList.size(); + for (int i = 0; i < size; i++) { + sb.append(dataIdList.get(i)); + sb.append(Constants.WORD_SEPARATOR); + sb.append(groupIdList.get(i)); + sb.append(Constants.LINE_SEPARATOR); + } + return URLEncoder.encode(sb.toString(), "UTF-8"); + } + + public void cacheConfig(Map params) { + String content = params.get(CONTENT_PARAM_NAME); + + String key = createContentKey(params); + + contentCache.put(key, content); + } + + /** + * Handle {@link ConfigService#getConfig(String, String, long)} + * + * @param httpExchange {@link HttpExchange} + * @throws IOException IO error + */ + private void handleGetConfig(HttpExchange httpExchange) throws IOException { + + URI requestURI = httpExchange.getRequestURI(); + + String queryString = requestURI.getQuery(); + + Map params = parseParams(queryString); + + String key = createContentKey(params); + + String content = contentCache.get(key); + + write(httpExchange, content); + } + + /** + * Handle {@link ConfigService#removeConfig(String, String)} + * + * @param httpExchange {@link HttpExchange} + * @throws IOException IO error + */ + private void handleRemoveConfig(HttpExchange httpExchange) throws IOException { + + URI requestURI = httpExchange.getRequestURI(); + + String queryString = requestURI.getQuery(); + + Map params = parseParams(queryString); + + String key = createContentKey(params); + + contentCache.remove(key); + + write(httpExchange, "OK"); + } + + private String createContentKey(Map params) { + String dataId = params.get(DATA_ID_PARAM_NAME); + String groupId = params.get(GROUP_ID_PARAM_NAME); + return createContentKey(dataId, groupId); + } + + private String createContentKey(String dataId, String groupId) { + return dataId + " | " + groupId; + } + + private void write(HttpExchange httpExchange, String content) throws IOException { + if (content != null) { + OutputStream outputStream = httpExchange.getResponseBody(); + httpExchange.sendResponseHeaders(200, content.length()); + StreamUtils.copy(URLDecoder.decode(content, "UTF-8"), forName("UTF-8"), + outputStream); + } + httpExchange.close(); + } + + private Map parseParams(String queryString) { + Map params = new HashMap(); + String[] parts = StringUtils.delimitedListToStringArray(queryString, "&"); + for (String part : parts) { + String[] nameAndValue = StringUtils.split(part, "="); + params.put(StringUtils.trimAllWhitespace(nameAndValue[0]), + StringUtils.trimAllWhitespace(nameAndValue[1])); + } + return params; + } + + public void destroy() { + isRunning = false; + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + } + } + + private static class LongPolling { + private HttpExchange httpExchange; + private Date date; + + LongPolling(HttpExchange httpExchange) { + this.httpExchange = httpExchange; + this.date = new Date(); + } + } } diff --git a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/servlet/EmbeddedNacosHttpServerListener.java b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/servlet/EmbeddedNacosHttpServerListener.java index 40e381d0..1c2f296b 100644 --- a/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/servlet/EmbeddedNacosHttpServerListener.java +++ b/nacos-spring-samples/nacos-embedded-webserver/src/main/java/com/alibaba/nacos/embedded/web/servlet/EmbeddedNacosHttpServerListener.java @@ -16,11 +16,12 @@ */ package com.alibaba.nacos.embedded.web.servlet; -import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; +import java.io.IOException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; -import java.io.IOException; + +import com.alibaba.nacos.embedded.web.server.EmbeddedNacosHttpServer; /** * {@link EmbeddedNacosHttpServer} {@link ServletContextListener Listener} @@ -30,28 +31,29 @@ */ public class EmbeddedNacosHttpServerListener implements ServletContextListener { - private static final String SERVER_ADDRESS_PROPERTY_NAME = "nacos.server-addr"; - - private EmbeddedNacosHttpServer httpServer; - - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - try { - if (!System.getProperties().containsKey(SERVER_ADDRESS_PROPERTY_NAME)) { - httpServer = new EmbeddedNacosHttpServer(); - httpServer.start(false); - System.setProperty(SERVER_ADDRESS_PROPERTY_NAME, "127.0.0.1:" + httpServer.getPort()); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - if (httpServer != null) { - httpServer.stop(); - } - } + private static final String SERVER_ADDRESS_PROPERTY_NAME = "nacos.server-addr"; + + private EmbeddedNacosHttpServer httpServer; + + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + try { + if (!System.getProperties().containsKey(SERVER_ADDRESS_PROPERTY_NAME)) { + httpServer = new EmbeddedNacosHttpServer(); + httpServer.start(false); + System.setProperty(SERVER_ADDRESS_PROPERTY_NAME, + "127.0.0.1:" + httpServer.getPort()); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + if (httpServer != null) { + httpServer.stop(); + } + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/pom.xml b/nacos-spring-samples/nacos-spring-webmvc-sample/pom.xml index 3b2bd5c7..0077fc97 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/pom.xml +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/pom.xml @@ -30,6 +30,7 @@ org.springframework spring-core + 4.0.5.RELEASE diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/InitSystemPropertiesListener.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/InitSystemPropertiesListener.java new file mode 100644 index 00000000..a021e7d5 --- /dev/null +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/InitSystemPropertiesListener.java @@ -0,0 +1,101 @@ +package com.alibaba.nacos.samples.spring; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * custom ServletContextListener,init nacos confg item to the System Property if you want + * use the properties files to config the nacos , but not want use the JVM -D params in + * your start shell + * @author dinglang + * @since 2019-09-19 18:23 + */ +public class InitSystemPropertiesListener implements ServletContextListener { + + /** + * the nacos server address + */ + private static final String SERVER_ADDRESS_PROPERTY_NAME = "nacos.server-addr"; + + /** + * the nacos namespace + */ + private static final String NAMESPACE_PROPERTY_NAME = "nacos.config.namespace"; + /** + * the ignoreResourceNotFound property for propertySourcesPlaceholderConfigurer + */ + public static final String IGNORE_RESOURCE_NOT_FOUND = "ignoreResourceNotFound"; + + /** + * the ignoreUnresolvablePlaceholders property for + * propertySourcesPlaceholderConfigurer + */ + public static final String IGNORE_UNRESOLVABLE_PLACEHOLDERS = "ignoreUnresolvablePlaceholders"; + + private static final Logger logger = LoggerFactory + .getLogger(InitSystemPropertiesListener.class); + + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + logger.info("InitSystemPropertiesListener#contextInitialized,开始准备初始化系统变量"); + InputStream input = null; + try { + input = servletContextEvent.getServletContext() + .getResourceAsStream("/WEB-INF/config.properties"); + Properties p = new Properties(); + p.load(input); + + String nacosServer = p.getProperty(SERVER_ADDRESS_PROPERTY_NAME); + String namespace = p.getProperty(NAMESPACE_PROPERTY_NAME); + + String ignoreResourceNotFound = p.getProperty(IGNORE_RESOURCE_NOT_FOUND); + String ignoreUnresolvablePlaceholders = p + .getProperty(IGNORE_UNRESOLVABLE_PLACEHOLDERS); + + logger.info("nacosServer:{},namespace:{}", nacosServer, namespace); + if (StringUtils.isNotEmpty(nacosServer) && !System.getProperties() + .containsKey(SERVER_ADDRESS_PROPERTY_NAME)) { + System.setProperty(SERVER_ADDRESS_PROPERTY_NAME, nacosServer); + } + if (StringUtils.isNotEmpty(namespace) + && !System.getProperties().containsKey(NAMESPACE_PROPERTY_NAME)) { + System.setProperty(NAMESPACE_PROPERTY_NAME, namespace); + } + if (StringUtils.isNotEmpty(ignoreResourceNotFound) + && !System.getProperties().containsKey(IGNORE_RESOURCE_NOT_FOUND)) { + System.setProperty(IGNORE_RESOURCE_NOT_FOUND, ignoreResourceNotFound); + } + if (StringUtils.isNotEmpty(ignoreUnresolvablePlaceholders) && !System + .getProperties().containsKey(IGNORE_UNRESOLVABLE_PLACEHOLDERS)) { + System.setProperty(IGNORE_UNRESOLVABLE_PLACEHOLDERS, + ignoreUnresolvablePlaceholders); + } + } + catch (Exception e) { + logger.error("初始化系统变量失败", e); + } + finally { + if (input != null) { + try { + input.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + + } +} diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/NacosConfiguration.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/NacosConfiguration.java index de5151c7..82c1f94f 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/NacosConfiguration.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/NacosConfiguration.java @@ -16,14 +16,15 @@ */ package com.alibaba.nacos.samples.spring; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.spring.context.annotation.EnableNacos; -import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; +import org.springframework.context.annotation.Configuration; /** * Nacos {@link Configuration} @@ -32,36 +33,28 @@ * @since 0.1.0 */ @Configuration -@EnableNacos( - globalProperties = - @NacosProperties(serverAddr = "${nacos.server-addr}", - enableRemoteSyncConfig = "true", - maxRetry = "5", - configRetryTime = "4000", - configLongPollTimeout = "26000") -) +@EnableNacos(globalProperties = @NacosProperties(serverAddr = "${nacos.server-addr}", enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "4000", configLongPollTimeout = "26000")) public class NacosConfiguration { - /** - * The data id for {@link System#currentTimeMillis()} - */ - public static final String CURRENT_TIME_DATA_ID = "time-data-id"; - - @NacosInjected - private NamingService namingService; + /** + * The data id for {@link System#currentTimeMillis()} + */ + public static final String CURRENT_TIME_DATA_ID = "time-data-id"; - @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) - private NamingService namingServiceUTF8; + @NacosInjected + private NamingService namingService; - @NacosInjected - private ConfigService configService; + @NacosInjected(properties = @NacosProperties(encode = "UTF-8")) + private NamingService namingServiceUTF8; + @NacosInjected + private ConfigService configService; - @PostConstruct - public void init() { - if (namingService != namingServiceUTF8) { - throw new RuntimeException("Why?"); - } - } + @PostConstruct + public void init() { + if (namingService != namingServiceUTF8) { + throw new RuntimeException("Why?"); + } + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/config/PojoNacosConfigConverter.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/config/PojoNacosConfigConverter.java index 452dd850..9ce4f08d 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/config/PojoNacosConfigConverter.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/config/PojoNacosConfigConverter.java @@ -16,12 +16,12 @@ */ package com.alibaba.nacos.samples.spring.config; +import java.io.IOException; + import com.alibaba.nacos.api.config.convert.NacosConfigConverter; import com.alibaba.nacos.samples.spring.domain.Pojo; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; - /** * {@link Pojo} Jackson {@link NacosConfigConverter} * @@ -30,19 +30,20 @@ */ public class PojoNacosConfigConverter implements NacosConfigConverter { - private ObjectMapper objectMapper = new ObjectMapper(); + private ObjectMapper objectMapper = new ObjectMapper(); - @Override - public boolean canConvert(Class targetType) { - return objectMapper.canSerialize(targetType); - } + @Override + public boolean canConvert(Class targetType) { + return objectMapper.canSerialize(targetType); + } - @Override - public Pojo convert(String config) { - try { - return objectMapper.readValue(config, Pojo.class); - } catch (IOException e) { - throw new RuntimeException(e); - } - } + @Override + public Pojo convert(String config) { + try { + return objectMapper.readValue(config, Pojo.class); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/domain/Pojo.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/domain/Pojo.java index 933a8df2..792a2f7d 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/domain/Pojo.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/domain/Pojo.java @@ -16,12 +16,12 @@ */ package com.alibaba.nacos.samples.spring.domain; +import java.util.Date; + 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 java.util.Date; - import static com.alibaba.nacos.samples.spring.domain.Pojo.DATA_ID; /** @@ -33,68 +33,63 @@ @NacosConfigurationProperties(dataId = DATA_ID, autoRefreshed = true) public class Pojo { - public static final String DATA_ID = "pojo-data-id"; + public static final String DATA_ID = "pojo-data-id"; - private Long id; + private Long id; - private String name; + private String name; - private Date created; + private Date created; - @NacosProperty("desc") - private String description; + @NacosProperty("desc") + private String description; - @NacosIgnore - private boolean ignored; + @NacosIgnore + private boolean ignored; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Date getCreated() { - return created; - } + public Date getCreated() { + return created; + } - public void setCreated(Date created) { - this.created = created; - } + public void setCreated(Date created) { + this.created = created; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public boolean isIgnored() { - return ignored; - } + public boolean isIgnored() { + return ignored; + } - public void setIgnored(boolean ignored) { - this.ignored = ignored; - } + public void setIgnored(boolean ignored) { + this.ignored = ignored; + } - @Override - public String toString() { - return "Pojo{" + - "id=" + id + - ", name='" + name + '\'' + - ", created=" + created + - ", description='" + description + '\'' + - ", ignored=" + ignored + - '}'; - } + @Override + public String toString() { + return "Pojo{" + "id=" + id + ", name='" + name + '\'' + ", created=" + created + + ", description='" + description + '\'' + ", ignored=" + ignored + '}'; + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/env/NacosPropertySourceConfiguration.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/env/NacosPropertySourceConfiguration.java index ff19c40e..fc67ee86 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/env/NacosPropertySourceConfiguration.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/env/NacosPropertySourceConfiguration.java @@ -16,21 +16,23 @@ */ package com.alibaba.nacos.samples.spring.env; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; -import static com.alibaba.nacos.samples.spring.env.NacosPropertySourceConfiguration.*; +import static com.alibaba.nacos.samples.spring.env.NacosPropertySourceConfiguration.AFTER_SYS_PROP_DATA_ID; +import static com.alibaba.nacos.samples.spring.env.NacosPropertySourceConfiguration.BEFORE_OS_ENV_DATA_ID; +import static com.alibaba.nacos.samples.spring.env.NacosPropertySourceConfiguration.FIRST_DATA_ID; import static org.springframework.core.env.StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME; import static org.springframework.core.env.StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME; @@ -41,66 +43,70 @@ * @since 0.1.0 */ @Configuration -@NacosPropertySource(name = "first", dataId = FIRST_DATA_ID, first = true, autoRefreshed = true) // First PropertySource +@NacosPropertySource(name = "first", dataId = FIRST_DATA_ID, first = true, autoRefreshed = true) // First + // PropertySource @NacosPropertySources({ - @NacosPropertySource(name = "before-os-env", dataId = BEFORE_OS_ENV_DATA_ID, before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), - @NacosPropertySource(name = "after-system-properties", dataId = AFTER_SYS_PROP_DATA_ID, after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME) -}) + @NacosPropertySource(name = "before-os-env", dataId = BEFORE_OS_ENV_DATA_ID, before = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME), + @NacosPropertySource(name = "after-system-properties", dataId = AFTER_SYS_PROP_DATA_ID, after = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME), + @NacosPropertySource(dataId = "people", groupId = "DEVELOP") }) public class NacosPropertySourceConfiguration { - private static final Logger logger = LoggerFactory.getLogger(NacosPropertySourceConfiguration.class); - - public static final String FIRST_DATA_ID = "first-property-source-data-id"; - - public static final String BEFORE_OS_ENV_DATA_ID = "before-os-env-property-source-data-id"; - - public static final String AFTER_SYS_PROP_DATA_ID = "after-system-properties-property-source-data-id"; - - static { - String serverAddr = System.getProperty("nacos.server-addr"); - try { - ConfigService configService = NacosFactory.createConfigService(serverAddr); - // Publish for FIRST_DATA_ID - publishConfig(configService, FIRST_DATA_ID, "user.name = Mercy Ma"); - - // Publish for BEFORE_OS_ENV_DATA_ID - publishConfig(configService, BEFORE_OS_ENV_DATA_ID, "PATH = /home/my-path"); - - // Publish for AFTER_SYS_PROP_DATA_ID - publishConfig(configService, AFTER_SYS_PROP_DATA_ID, "user.name = mercyblitz"); - - } catch (NacosException e) { - throw new RuntimeException(e); - } - } - - private static void publishConfig(ConfigService configService, String dataId, String propertiesContent) throws NacosException { - configService.publishConfig(dataId, DEFAULT_GROUP, propertiesContent); - } - - /** - * "before-os-env" overrides OS Environment variables $PATH - */ - @Value("${PATH}") - private String path; - - /** - * There are three definitions of "user.name" from - * FIRST_DATA_ID, - * SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, - * AFTER_SYS_PROP_DATA_ID - *

- * Thus, "user.name = Mercy Ma" will be loaded from FIRST_DATA_ID, others will be ignored. - */ - @Value("${user.name}") - private String userName; - - @PostConstruct - public void init() { - logger.info("${PATH} : {}", path); // -> "home/my-path" - logger.info("${user.name} : {}", userName); // -> "Mercy Ma" - logger.info("Java System ${user.name} : {}", System.getProperty("user.name")); - logger.info("OS Env ${PATH} : {}", System.getenv("PATH")); - } + private static final Logger logger = LoggerFactory + .getLogger(NacosPropertySourceConfiguration.class); + + public static final String FIRST_DATA_ID = "first-property-source-data-id"; + + public static final String BEFORE_OS_ENV_DATA_ID = "before-os-env-property-source-data-id"; + + public static final String AFTER_SYS_PROP_DATA_ID = "after-system-properties-property-source-data-id"; + + static { + String serverAddr = System.getProperty("nacos.server-addr"); + try { + ConfigService configService = NacosFactory.createConfigService(serverAddr); + // Publish for FIRST_DATA_ID + publishConfig(configService, FIRST_DATA_ID, "user.name = Mercy Ma"); + + // Publish for BEFORE_OS_ENV_DATA_ID + publishConfig(configService, BEFORE_OS_ENV_DATA_ID, "PATH = /home/my-path"); + + // Publish for AFTER_SYS_PROP_DATA_ID + publishConfig(configService, AFTER_SYS_PROP_DATA_ID, + "user.name = mercyblitz"); + + } + catch (NacosException e) { + throw new RuntimeException(e); + } + } + + private static void publishConfig(ConfigService configService, String dataId, + String propertiesContent) throws NacosException { + configService.publishConfig(dataId, DEFAULT_GROUP, propertiesContent); + } + + /** + * "before-os-env" overrides OS Environment variables $PATH + */ + @Value("${PATH}") + private String path; + + /** + * There are three definitions of "user.name" from FIRST_DATA_ID, + * SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, AFTER_SYS_PROP_DATA_ID + *

+ * Thus, "user.name = Mercy Ma" will be loaded from FIRST_DATA_ID, others will be + * ignored. + */ + @Value("${user.name}") + private String userName; + + @PostConstruct + public void init() { + logger.info("${PATH} : {}", path); // -> "home/my-path" + logger.info("${user.name} : {}", userName); // -> "Mercy Ma" + logger.info("Java System ${user.name} : {}", System.getProperty("user.name")); + logger.info("OS Env ${PATH} : {}", System.getenv("PATH")); + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/event/NacosEventListenerConfiguration.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/event/NacosEventListenerConfiguration.java index 08ee4bb9..f1def278 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/event/NacosEventListenerConfiguration.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/event/NacosEventListenerConfiguration.java @@ -16,6 +16,8 @@ */ package com.alibaba.nacos.samples.spring.event; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.AbstractListener; @@ -26,12 +28,11 @@ import com.alibaba.nacos.spring.context.event.config.NacosConfigRemovedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; - import static com.alibaba.nacos.api.common.Constants.DATAID; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; @@ -44,64 +45,74 @@ @Configuration public class NacosEventListenerConfiguration { - private static final Logger logger = LoggerFactory.getLogger(NacosEventListenerConfiguration.class); - - private static final String DATA_ID = "event-data-id"; - - @NacosInjected - private ConfigService configService; - - @PostConstruct - public void init() throws NacosException { - // for NacosConfigReceivedEvent - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "Hello,World"); - - // for NacosConfigRemovedEvent - configService.removeConfig(DATA_ID, DEFAULT_GROUP); - - Listener listener = new AbstractListener() { - @Override - public void receiveConfigInfo(String configInfo) { - } - }; - - // for NacosConfigListenerRegisteredEvent(true) - configService.addListener(DATAID, DEFAULT_GROUP, listener); - - // for NacosConfigListenerRegisteredEvent(false) - configService.removeListener(DATAID, DEFAULT_GROUP, listener); - } - - @Bean - public ApplicationListener nacosConfigReceivedEventListener() { - return new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigReceivedEvent event) { - logger.info("Listening on NacosConfigReceivedEvent - dataId : {} , groupId : {} , " + "content : {} , " - + "source : {}", event.getDataId(), event.getGroupId(), event.getContent(), event.getSource()); - } - }; - } - - @Bean - public ApplicationListener nacosConfigRemovedEventListener() { - return new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigRemovedEvent event) { - logger.info("Listening on NacosConfigRemovedEvent - dataId : {} , groupId : {} , " + "removed : {} , " - + "source : {}", event.getDataId(), event.getGroupId(), event.isRemoved(), event.getSource()); - } - }; - } - - @Bean - public ApplicationListener nacosConfigListenerRegisteredEventListener() { - return new ApplicationListener() { - @Override - public void onApplicationEvent(NacosConfigListenerRegisteredEvent event) { - logger.info("Listening on NacosConfigListenerRegisteredEvent - dataId : {} , groupId : {} , " + "registered : {} , " - + "source : {}", event.getDataId(), event.getGroupId(), event.isRegistered(), event.getSource()); - } - }; - } + private static final Logger logger = LoggerFactory + .getLogger(NacosEventListenerConfiguration.class); + + private static final String DATA_ID = "event-data-id"; + + @NacosInjected + private ConfigService configService; + + @PostConstruct + public void init() throws NacosException { + // for NacosConfigReceivedEvent + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "Hello,World"); + + // for NacosConfigRemovedEvent + configService.removeConfig(DATA_ID, DEFAULT_GROUP); + + Listener listener = new AbstractListener() { + @Override + public void receiveConfigInfo(String configInfo) { + } + }; + + // for NacosConfigListenerRegisteredEvent(true) + configService.addListener(DATAID, DEFAULT_GROUP, listener); + + // for NacosConfigListenerRegisteredEvent(false) + configService.removeListener(DATAID, DEFAULT_GROUP, listener); + } + + @Bean + public ApplicationListener nacosConfigReceivedEventListener() { + return new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigReceivedEvent event) { + logger.info( + "Listening on NacosConfigReceivedEvent - dataId : {} , groupId : {} , " + + "content : {} , " + "source : {}", + event.getDataId(), event.getGroupId(), event.getContent(), + event.getSource()); + } + }; + } + + @Bean + public ApplicationListener nacosConfigRemovedEventListener() { + return new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigRemovedEvent event) { + logger.info( + "Listening on NacosConfigRemovedEvent - dataId : {} , groupId : {} , " + + "removed : {} , " + "source : {}", + event.getDataId(), event.getGroupId(), event.isRemoved(), + event.getSource()); + } + }; + } + + @Bean + public ApplicationListener nacosConfigListenerRegisteredEventListener() { + return new ApplicationListener() { + @Override + public void onApplicationEvent(NacosConfigListenerRegisteredEvent event) { + logger.info( + "Listening on NacosConfigListenerRegisteredEvent - dataId : {} , groupId : {} , " + + "registered : {} , " + "source : {}", + event.getDataId(), event.getGroupId(), event.isRegistered(), + event.getSource()); + } + }; + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/PojoNacosConfigListener.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/PojoNacosConfigListener.java index 71573434..71b12633 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/PojoNacosConfigListener.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/PojoNacosConfigListener.java @@ -16,6 +16,10 @@ */ package com.alibaba.nacos.samples.spring.listener; +import java.util.Date; + +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; @@ -25,10 +29,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; -import java.util.Date; +import org.springframework.context.annotation.Configuration; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.samples.spring.NacosConfiguration.CURRENT_TIME_DATA_ID; @@ -43,30 +45,31 @@ @Configuration public class PojoNacosConfigListener { - public static final String POJO_DATA_ID = "pojo-data-id"; + public static final String POJO_DATA_ID = "pojo-data-id"; - private static final Logger logger = LoggerFactory.getLogger(PojoNacosConfigListener.class); + private static final Logger logger = LoggerFactory + .getLogger(PojoNacosConfigListener.class); - private Pojo pojo = new Pojo(); + private Pojo pojo = new Pojo(); - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @PostConstruct - public void init() throws Exception { - // Initialize - pojo.setId(1L); - pojo.setName("mercyblitz"); - pojo.setCreated(new Date()); - // Serialization - ObjectMapper objectMapper = new ObjectMapper(); - String content = objectMapper.writeValueAsString(pojo); - // Publish - configService.publishConfig(POJO_DATA_ID, DEFAULT_GROUP, content); - } + @PostConstruct + public void init() throws Exception { + // Initialize + pojo.setId(1L); + pojo.setName("mercyblitz"); + pojo.setCreated(new Date()); + // Serialization + ObjectMapper objectMapper = new ObjectMapper(); + String content = objectMapper.writeValueAsString(pojo); + // Publish + configService.publishConfig(POJO_DATA_ID, DEFAULT_GROUP, content); + } - @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, converter = PojoNacosConfigConverter.class) - public void onReceived(Pojo value) throws InterruptedException { - logger.info("onReceived(Pojo) : {}", value); - } + @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, converter = PojoNacosConfigConverter.class) + public void onReceived(Pojo value) throws InterruptedException { + logger.info("onReceived(Pojo) : {}", value); + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/SimpleNacosConfigListener.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/SimpleNacosConfigListener.java index 8f88c984..8ef09e7f 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/SimpleNacosConfigListener.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/SimpleNacosConfigListener.java @@ -16,6 +16,10 @@ */ package com.alibaba.nacos.samples.spring.listener; +import java.util.Properties; + +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; @@ -23,10 +27,8 @@ import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; -import java.util.Properties; +import org.springframework.context.annotation.Configuration; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; @@ -40,32 +42,34 @@ @Configuration public class SimpleNacosConfigListener { - private static final Logger logger = LoggerFactory.getLogger(SimpleNacosConfigListener.class); + private static final Logger logger = LoggerFactory + .getLogger(SimpleNacosConfigListener.class); - public static final String PROPERTIES_DATA_ID = "properties-data-id"; + public static final String PROPERTIES_DATA_ID = "properties-data-id"; - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @PostConstruct - public void init() throws Exception { - // Build Properties Content - StringBuilder builder = new StringBuilder(); - builder.append("user.id = 1"); - builder.append(SystemUtils.LINE_SEPARATOR); - builder.append("user.name = mercyblitz"); - builder.append(SystemUtils.LINE_SEPARATOR); - builder.append("user.github = https://github.com/mercyblitz"); - configService.publishConfig(PROPERTIES_DATA_ID, DEFAULT_GROUP, builder.toString()); - } + @PostConstruct + public void init() throws Exception { + // Build Properties Content + StringBuilder builder = new StringBuilder(); + builder.append("user.id = 1"); + builder.append(SystemUtils.LINE_SEPARATOR); + builder.append("user.name = mercyblitz"); + builder.append(SystemUtils.LINE_SEPARATOR); + builder.append("user.github = https://github.com/mercyblitz"); + configService.publishConfig(PROPERTIES_DATA_ID, DEFAULT_GROUP, + builder.toString()); + } - @NacosConfigListener(dataId = PROPERTIES_DATA_ID) - public void onReceived(String value) { - logger.info("onReceived(String) : {}", value); - } + @NacosConfigListener(dataId = PROPERTIES_DATA_ID) + public void onReceived(String value) { + logger.info("onReceived(String) : {}", value); + } - @NacosConfigListener(dataId = PROPERTIES_DATA_ID) - public void onReceived(Properties value) { - logger.info("onReceived(Properties) : {}", value); - } + @NacosConfigListener(dataId = PROPERTIES_DATA_ID) + public void onReceived(Properties value) { + logger.info("onReceived(Properties) : {}", value); + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/TimeoutNacosConfigListener.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/TimeoutNacosConfigListener.java index 3d369ecd..533206eb 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/TimeoutNacosConfigListener.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/listener/TimeoutNacosConfigListener.java @@ -16,15 +16,16 @@ */ package com.alibaba.nacos.samples.spring.listener; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosConfigListener; import com.alibaba.nacos.samples.spring.NacosConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; +import org.springframework.context.annotation.Configuration; import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.samples.spring.NacosConfiguration.CURRENT_TIME_DATA_ID; @@ -39,28 +40,29 @@ @Configuration public class TimeoutNacosConfigListener { - private static final Logger logger = LoggerFactory.getLogger(TimeoutNacosConfigListener.class); + private static final Logger logger = LoggerFactory + .getLogger(TimeoutNacosConfigListener.class); - public static final String TEST_DATA_ID = "timeout-data-id"; + public static final String TEST_DATA_ID = "timeout-data-id"; - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @PostConstruct - public void init() throws Exception { - configService.publishConfig(TEST_DATA_ID, DEFAULT_GROUP, "Hello,World"); - } + @PostConstruct + public void init() throws Exception { + configService.publishConfig(TEST_DATA_ID, DEFAULT_GROUP, "Hello,World"); + } - @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, timeout = 100) - public void onReceivedWithTimeout(String value) throws InterruptedException { - Thread.sleep(200); - logger.info("onReceivedWithTimeout(String) : {}", value); // Never executes - } + @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, timeout = 100) + public void onReceivedWithTimeout(String value) throws InterruptedException { + Thread.sleep(200); + logger.info("onReceivedWithTimeout(String) : {}", value); // Never executes + } - @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, timeout = 100) - public void onReceivedWithoutTimeout(String value) throws InterruptedException { - Thread.sleep(50); - logger.info("onReceivedWithoutTimeout(String) : {}", value); - } + @NacosConfigListener(dataId = CURRENT_TIME_DATA_ID, timeout = 100) + public void onReceivedWithoutTimeout(String value) throws InterruptedException { + Thread.sleep(50); + logger.info("onReceivedWithoutTimeout(String) : {}", value); + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/properties/NacosConfigurationPropertiesConfiguration.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/properties/NacosConfigurationPropertiesConfiguration.java index e0636bb1..49841e6b 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/properties/NacosConfigurationPropertiesConfiguration.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/properties/NacosConfigurationPropertiesConfiguration.java @@ -16,18 +16,19 @@ */ package com.alibaba.nacos.samples.spring.properties; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties; import com.alibaba.nacos.samples.spring.domain.Pojo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.annotation.PostConstruct; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static com.alibaba.nacos.samples.spring.domain.Pojo.DATA_ID; @@ -40,30 +41,31 @@ @Configuration public class NacosConfigurationPropertiesConfiguration { - private static final Logger logger = LoggerFactory.getLogger(NacosConfigurationPropertiesConfiguration.class); + private static final Logger logger = LoggerFactory + .getLogger(NacosConfigurationPropertiesConfiguration.class); - @Bean - public Pojo pojo() { - return new Pojo(); - } + @Bean + public Pojo pojo() { + return new Pojo(); + } - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @Autowired - private Pojo pojo; + @Autowired + private Pojo pojo; - @PostConstruct - public void init() throws Exception { - logger.info("pojo = {}", pojo); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "id = 1"); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "name = mercyblitz"); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "desc = description"); - configService.publishConfig(DATA_ID, DEFAULT_GROUP, "ignored = true"); - logger.info("pojo.id = {}", pojo.getId()); // 1 - logger.info("pojo.name = {}", pojo.getName()); // mercyblitz - logger.info("pojo.description = {}", pojo.getDescription()); // description - logger.info("pojo.ignored = {}", pojo.isIgnored()); // false - } + @PostConstruct + public void init() throws Exception { + logger.info("pojo = {}", pojo); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "id = 1"); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "name = mercyblitz"); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "desc = description"); + configService.publishConfig(DATA_ID, DEFAULT_GROUP, "ignored = true"); + logger.info("pojo.id = {}", pojo.getId()); // 1 + logger.info("pojo.name = {}", pojo.getName()); // mercyblitz + logger.info("pojo.description = {}", pojo.getDescription()); // description + logger.info("pojo.ignored = {}", pojo.isIgnored()); // false + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/webmvc/ConfigServiceController.java b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/webmvc/ConfigServiceController.java index 563cb2ef..3c860a53 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/webmvc/ConfigServiceController.java +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/java/com/alibaba/nacos/samples/spring/webmvc/ConfigServiceController.java @@ -16,17 +16,18 @@ */ package com.alibaba.nacos.samples.spring.webmvc; +import java.util.concurrent.TimeUnit; + import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosValue; import com.alibaba.nacos.api.exception.NacosException; + import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; -import java.util.concurrent.TimeUnit; - import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; @@ -40,28 +41,31 @@ @Controller public class ConfigServiceController { - @NacosValue(value = "${people.enable:false}", autoRefreshed = true) - private String enable; + @NacosValue(value = "${people.enable}", autoRefreshed = true) + private String enable; - @NacosInjected - private ConfigService configService; + @NacosInjected + private ConfigService configService; - @RequestMapping(value = "/get", method = GET) - @ResponseBody - public String get(@RequestParam String dataId, @RequestParam(defaultValue = DEFAULT_GROUP) String groupId) throws NacosException { - return configService.getConfig(dataId, groupId, TimeUnit.SECONDS.toMillis(1)); - } + @RequestMapping(value = "/get", method = GET) + @ResponseBody + public String get(@RequestParam String dataId, + @RequestParam(defaultValue = DEFAULT_GROUP) String groupId) + throws NacosException { + return configService.getConfig(dataId, groupId, TimeUnit.SECONDS.toMillis(1)); + } - @RequestMapping() - @ResponseBody - public String value() { - return enable; - } + @RequestMapping() + @ResponseBody + public String value() { + return enable; + } - @RequestMapping(value = "/publish", method = POST) - @ResponseBody - public boolean publish(@RequestParam String dataId, @RequestParam(defaultValue = DEFAULT_GROUP) String groupId, - @RequestParam String content) throws NacosException { - return configService.publishConfig(dataId, groupId, content); - } + @RequestMapping(value = "/publish", method = POST) + @ResponseBody + public boolean publish(@RequestParam String dataId, + @RequestParam(defaultValue = DEFAULT_GROUP) String groupId, + @RequestParam String content) throws NacosException { + return configService.publishConfig(dataId, groupId, content); + } } diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/config.properties b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/config.properties new file mode 100644 index 00000000..7272cb4d --- /dev/null +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/config.properties @@ -0,0 +1,4 @@ +nacos.server-addr=127.0.0.1:8848 +nacos.config.namespace= +ignoreResourceNotFound=true +ignoreUnresolvablePlaceholders=true \ No newline at end of file diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml index 225c9e11..9e133ce6 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml @@ -19,5 +19,7 @@ + + \ No newline at end of file diff --git a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/web.xml b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/web.xml index badaf317..283cb624 100644 --- a/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/web.xml +++ b/nacos-spring-samples/nacos-spring-webmvc-sample/src/main/webapp/WEB-INF/web.xml @@ -3,8 +3,12 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0"> - + + + + com.alibaba.nacos.samples.spring.InitSystemPropertiesListener diff --git a/pom.xml b/pom.xml index 671ecbbf..b9035fb5 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,8 @@ git@github.com:nacos-group/nacos-spring-project.git scm:git@github.com:nacos-group/nacos-spring-project.git - scm:git@github.com:nacos-group/nacos-spring-project.git + scm:git@github.com:nacos-group/nacos-spring-project.git + @@ -82,7 +83,8 @@ 1.6 jacoco - ${project.basedir}/../test/target/jacoco-it.exec + ${project.basedir}/../test/target/jacoco-it.exec + file:**/generated-sources/**,**/test/** 1.1.3 @@ -183,7 +185,6 @@ - @@ -194,13 +195,23 @@ sona - https://oss.sonatype.org/service/local/staging/deploy/maven2 + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + + @@ -215,6 +226,35 @@ + + org.apache.maven.plugins + maven-eclipse-plugin + + false + + + .settings/org.eclipse.jdt.ui.prefs + + ${project.basedir}/eclipse/org.eclipse.jdt.ui.prefs + + + + .settings/org.eclipse.jdt.core.prefs + + ${project.basedir}/eclipse/org.eclipse.jdt.core.prefs + + + + + + + io.spring.javaformat + spring-javaformat-maven-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + org.apache.maven.plugins maven-source-plugin