From ab9cdbc7224297def7ccbedf3ae77d98fcd95a3f Mon Sep 17 00:00:00 2001 From: Mercy Ma Date: Tue, 7 Jan 2025 21:56:42 +0800 Subject: [PATCH 01/25] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 55faae5f..6c0a5633 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ io.github.microsphere-projects microsphere-build - 0.1.0 + 0.1.1 4.0.0 @@ -52,7 +52,7 @@ - 0.1.0-SNAPSHOT + 0.1.1-SNAPSHOT From 9d8493aac222c9fcfc40aeac990c3b7b46ebb3c7 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 14:27:06 +0800 Subject: [PATCH 02/25] Polish #78 --- .../webmvc/advice/StoringResponseBodyReturnValueAdvice.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/advice/StoringResponseBodyReturnValueAdvice.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/advice/StoringResponseBodyReturnValueAdvice.java index 8caabd04..da8c36d7 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/advice/StoringResponseBodyReturnValueAdvice.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/advice/StoringResponseBodyReturnValueAdvice.java @@ -7,6 +7,7 @@ import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.HandlerMethod; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; @@ -15,7 +16,7 @@ import static io.microsphere.spring.webmvc.util.WebMvcUtils.supportedConverterTypes; /** - * Store {@ link HandlerMethod} return value {@ link ResponseBodyAdviceAdapter} + * Store {@link HandlerMethod} return value {@link ResponseBodyAdviceAdapter} * * @author Mercy * @since 1.0.0 From 0d5cc67c598b24ab3043e2926a6a6fabacc6960b Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 14:48:59 +0800 Subject: [PATCH 03/25] Polish #77 --- .../WebMvcExtensionConfiguration.java | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionConfiguration.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionConfiguration.java index fd07a295..5fef59c6 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionConfiguration.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionConfiguration.java @@ -16,13 +16,16 @@ */ package io.microsphere.spring.webmvc.annotation; +import io.microsphere.logging.Logger; import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import static io.microsphere.logging.LoggerFactory.getLogger; +import static io.microsphere.util.ArrayUtils.length; + /** * The configuration class for {@link EnableWebMvcExtension} * @@ -33,13 +36,29 @@ */ public class WebMvcExtensionConfiguration extends WebMvcConfigurerAdapter { - @Autowired - private ObjectProvider lazyCompositeHandlerInterceptorProvider; + private static final Logger logger = getLogger(WebMvcExtensionConfiguration.class); + + private final ObjectProvider lazyCompositeHandlerInterceptorProvider; + + public WebMvcExtensionConfiguration(ObjectProvider lazyCompositeHandlerInterceptorProvider) { + this.lazyCompositeHandlerInterceptorProvider = lazyCompositeHandlerInterceptorProvider; + } @Override public void addInterceptors(InterceptorRegistry registry) { LazyCompositeHandlerInterceptor[] lazyCompositeHandlerInterceptors = lazyCompositeHandlerInterceptorProvider.getIfAvailable(); - for (LazyCompositeHandlerInterceptor lazyCompositeHandlerInterceptor : lazyCompositeHandlerInterceptors) { + int length = length(lazyCompositeHandlerInterceptors); + if (length == 0) { + if (logger.isTraceEnabled()) { + logger.trace("No LazyCompositeHandlerInterceptor Bean was registered."); + } + return; + } + if (logger.isTraceEnabled()) { + logger.trace("{} LazyCompositeHandlerInterceptor Beans will be added into InterceptorRegistry.", length); + } + for (int i = 0; i < length; i++) { + LazyCompositeHandlerInterceptor lazyCompositeHandlerInterceptor = lazyCompositeHandlerInterceptors[i]; registry.addInterceptor(lazyCompositeHandlerInterceptor); } } From 57b1a4ab7937441fa08e1f6b6eeb847d63cff0d7 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 14:53:14 +0800 Subject: [PATCH 04/25] Update pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6c0a5633..a02a3058 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ io.github.microsphere-projects microsphere-build - 0.1.1 + 0.1.0 4.0.0 From 687db990c3e300bacd5c1e30682cf54764389842 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 17:17:27 +0800 Subject: [PATCH 05/25] Polish #79 --- .../webmvc/annotation/EnableWebMvcExtension.java | 16 +++++++++++++--- .../WebMvcExtensionBeanDefinitionRegistrar.java | 13 ++++++++++--- .../LazyCompositeHandlerInterceptor.java | 3 ++- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtension.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtension.java index 0efdbd97..b288cd56 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtension.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtension.java @@ -103,14 +103,24 @@ boolean publishEvents() default true; /** - * Indicate whether the {@link InterceptorRegistry} registers the beans of {@link HandlerInterceptor} - * by the specified types + * Indicate whether the {@link InterceptorRegistry} registers the beans of {@link HandlerInterceptor}. + * If it specifies true, {@link #handlerInterceptors()} method will not work anymore. * * @return false as default * @see WebMvcConfigurer#addInterceptors(InterceptorRegistry) * @see InterceptorRegistry */ - Class[] registerHandlerInterceptors() default {}; + boolean registerHandlerInterceptors() default false; + + /** + * Specify {@link HandlerInterceptor} types or its inherited types to register into {@link InterceptorRegistry}. + * If {@link #registerHandlerInterceptors()} is true, specified types will be ignored. + * + * @return null as default + * @see WebMvcConfigurer#addInterceptors(InterceptorRegistry) + * @see InterceptorRegistry + */ + Class[] handlerInterceptors() default {}; /** * Indicate that Stores the {@link MethodParameter argument} of {@link HandlerMethod} that annotated {@link RequestBody} diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java index 27e7b539..21ce7d1a 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java @@ -23,17 +23,19 @@ import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; +import io.microsphere.util.ArrayUtils; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; -import org.springframework.util.ObjectUtils; import org.springframework.web.servlet.HandlerInterceptor; import static io.microsphere.spring.beans.factory.support.BeanRegistrar.registerBeanDefinition; import static io.microsphere.spring.core.annotation.AnnotationUtils.getAnnotationAttributes; import static io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor.BEAN_NAME; +import static io.microsphere.util.ArrayUtils.isNotEmpty; +import static io.microsphere.util.ArrayUtils.of; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; /** @@ -88,13 +90,18 @@ private AnnotationAttributes getAttributes(AnnotationMetadata metadata) { } private void registerHandlerInterceptors(AnnotationAttributes attributes, BeanDefinitionRegistry registry) { - Class[] interceptorClasses = (Class[]) attributes.getClassArray("registerHandlerInterceptors"); - if (!ObjectUtils.isEmpty(interceptorClasses)) { + Class[] interceptorClasses = resolveHandlerInterceptorClasses(attributes); + if (isNotEmpty(interceptorClasses)) { registerLazyCompositeHandlerInterceptor(registry, interceptorClasses); registerInterceptors(registry, interceptorClasses); } } + private Class[] resolveHandlerInterceptorClasses(AnnotationAttributes attributes) { + boolean registerHandlerInterceptors = attributes.getBoolean("registerHandlerInterceptors"); + return registerHandlerInterceptors ? of(HandlerInterceptor.class) : (Class[]) attributes.getClassArray("handlerInterceptors"); + } + private void registerLazyCompositeHandlerInterceptor(BeanDefinitionRegistry registry, Class... interceptorClasses) { AbstractBeanDefinition beanDefinition = rootBeanDefinition(LazyCompositeHandlerInterceptor.class) .addConstructorArgValue(interceptorClasses) diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java index 01d39522..e0b8d4f4 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java @@ -33,6 +33,7 @@ import java.util.Set; import static io.microsphere.collection.CollectionUtils.size; +import static io.microsphere.collection.SetUtils.of; import static org.springframework.core.annotation.AnnotationAwareOrderComparator.sort; /** @@ -54,7 +55,7 @@ public class LazyCompositeHandlerInterceptor extends OnceApplicationContextEvent private List interceptors; public LazyCompositeHandlerInterceptor(Class... interceptorClasses) { - this.interceptorClasses = SetUtils.of(interceptorClasses); + this.interceptorClasses = of(interceptorClasses); } @Override From e9207b5167055b33fd508c22084d07b584834ea7 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 17:48:23 +0800 Subject: [PATCH 06/25] Polish #79 --- ...ebMvcExtensionBeanDefinitionRegistrar.java | 34 ++++++++++++- .../LazyCompositeHandlerInterceptor.java | 7 ++- .../annotation/EnableWebMvcExtensionTest.java | 48 +++++++++++++++++++ 3 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java index 21ce7d1a..8180db5c 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/annotation/WebMvcExtensionBeanDefinitionRegistrar.java @@ -16,6 +16,7 @@ */ package io.microsphere.spring.webmvc.annotation; +import io.microsphere.logging.Logger; import io.microsphere.spring.web.annotation.EnableWebExtension; import io.microsphere.spring.web.annotation.WebExtensionBeanDefinitionRegistrar; import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; @@ -23,7 +24,6 @@ import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; -import io.microsphere.util.ArrayUtils; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; @@ -31,6 +31,9 @@ import org.springframework.core.type.AnnotationMetadata; import org.springframework.web.servlet.HandlerInterceptor; +import java.util.Arrays; + +import static io.microsphere.logging.LoggerFactory.getLogger; import static io.microsphere.spring.beans.factory.support.BeanRegistrar.registerBeanDefinition; import static io.microsphere.spring.core.annotation.AnnotationUtils.getAnnotationAttributes; import static io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor.BEAN_NAME; @@ -49,10 +52,14 @@ */ public class WebMvcExtensionBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { + private static final Logger logger = getLogger(WebMvcExtensionBeanDefinitionRegistrar.class); + public static final Class ANNOTATION_CLASS = EnableWebMvcExtension.class; public static final String ANNOTATION_CLASS_NAME = ANNOTATION_CLASS.getName(); + private static final Class[] ALL_HANDLER_INTERCEPTOR_CLASSES = of(HandlerInterceptor.class); + @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { @@ -75,6 +82,9 @@ private void registerWebEndpointMappingRegistrar(AnnotationAttributes attributes if (registerWebEndpointMappings) { registerBeanDefinition(registry, WebEndpointMappingRegistrar.class); } + if (logger.isTraceEnabled()) { + logger.trace("@EnableWebMvcExtension.registerWebEndpointMappings = {}", registerWebEndpointMappings); + } } private void registerInterceptingHandlerMethodProcessor(AnnotationAttributes attributes, BeanDefinitionRegistry registry) { @@ -83,6 +93,9 @@ private void registerInterceptingHandlerMethodProcessor(AnnotationAttributes att String beanName = InterceptingHandlerMethodProcessor.BEAN_NAME; registerBeanDefinition(registry, beanName, InterceptingHandlerMethodProcessor.class); } + if (logger.isTraceEnabled()) { + logger.trace("@EnableWebMvcExtension.interceptHandlerMethods() = {}", interceptHandlerMethods); + } } private AnnotationAttributes getAttributes(AnnotationMetadata metadata) { @@ -99,7 +112,15 @@ private void registerHandlerInterceptors(AnnotationAttributes attributes, BeanDe private Class[] resolveHandlerInterceptorClasses(AnnotationAttributes attributes) { boolean registerHandlerInterceptors = attributes.getBoolean("registerHandlerInterceptors"); - return registerHandlerInterceptors ? of(HandlerInterceptor.class) : (Class[]) attributes.getClassArray("handlerInterceptors"); + Class[] handlerInterceptors = + (Class[]) attributes.getClassArray("handlerInterceptors"); + Class[] handlerInterceptorClasses = registerHandlerInterceptors ? + ALL_HANDLER_INTERCEPTOR_CLASSES : handlerInterceptors; + if (logger.isTraceEnabled()) { + logger.trace("@EnableWebMvcExtension.registerHandlerInterceptors() = {} , handlerInterceptors() = {} , handlerInterceptorClasses = {}", + registerHandlerInterceptors, handlerInterceptors, handlerInterceptorClasses); + } + return handlerInterceptorClasses; } private void registerLazyCompositeHandlerInterceptor(BeanDefinitionRegistry registry, Class... interceptorClasses) { @@ -110,6 +131,9 @@ private void registerLazyCompositeHandlerInterceptor(BeanDefinitionRegistry regi } private void registerInterceptors(BeanDefinitionRegistry registry, Class[] interceptorClasses) { + if (Arrays.equals(ALL_HANDLER_INTERCEPTOR_CLASSES, interceptorClasses)) { + return; + } for (Class interceptorClass : interceptorClasses) { registerInterceptor(registry, interceptorClass); } @@ -124,6 +148,9 @@ private void registerStoringRequestBodyArgumentAdvice(AnnotationAttributes attri if (storeRequestBodyArgument) { registerBeanDefinition(registry, StoringRequestBodyArgumentAdvice.class); } + if (logger.isTraceEnabled()) { + logger.trace("@EnableWebMvcExtension.storeRequestBodyArgument() = {}", storeRequestBodyArgument); + } } private void registerStoringResponseBodyReturnValueAdvice(AnnotationAttributes attributes, BeanDefinitionRegistry registry) { @@ -131,5 +158,8 @@ private void registerStoringResponseBodyReturnValueAdvice(AnnotationAttributes a if (storeResponseBodyReturnValue) { registerBeanDefinition(registry, StoringResponseBodyReturnValueAdvice.class); } + if (logger.isTraceEnabled()) { + logger.trace("@EnableWebMvcExtension.storeResponseBodyReturnValue() = {}", storeResponseBodyReturnValue); + } } } diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java index e0b8d4f4..a65e95ee 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java @@ -85,7 +85,12 @@ protected void onApplicationContextEvent(ContextRefreshedEvent event) { List allInterceptors = new LinkedList<>(); for (Class interceptorClass : interceptorClasses) { Collection interceptors = context.getBeansOfType(interceptorClass).values(); - allInterceptors.addAll(interceptors); + for (HandlerInterceptor interceptor : interceptors) { + if (interceptor == this) { + continue; + } + allInterceptors.add(interceptor); + } } sort(allInterceptors); this.interceptors = allInterceptors; diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java new file mode 100644 index 00000000..d339742a --- /dev/null +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java @@ -0,0 +1,48 @@ +/* + * 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 io.microsphere.spring.webmvc.annotation; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +/** + * {@link EnableWebMvcExtension} Test + * + * @author Mercy + * @see EnableWebMvcExtension + * @since 1.0.0 + */ +@RunWith(SpringRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { + EnableWebMvcExtensionTest.class +}) +@EnableWebMvcExtension( + registerHandlerInterceptors = true, + storeRequestBodyArgument = true, + storeResponseBodyReturnValue = true +) +public class EnableWebMvcExtensionTest { + + @Test + public void test() { + + } +} From 5ac6fb6d23e665ecb0352a7dcfc06f6201d7f7c2 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 17:48:36 +0800 Subject: [PATCH 07/25] Update LazyCompositeHandlerInterceptor.java --- .../webmvc/interceptor/LazyCompositeHandlerInterceptor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java index a65e95ee..e3ddd3f2 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/LazyCompositeHandlerInterceptor.java @@ -16,7 +16,6 @@ */ package io.microsphere.spring.webmvc.interceptor; -import io.microsphere.collection.SetUtils; import io.microsphere.lang.function.ThrowableConsumer; import io.microsphere.lang.function.ThrowableFunction; import io.microsphere.spring.context.event.OnceApplicationContextEventListener; From 9852e36630106a128b846d084a8a4cb925e7cb19 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 18:01:58 +0800 Subject: [PATCH 08/25] Polish #57 --- .../EnableWebMvcExtensionDefaultTest.java | 61 +++++++++++++++++++ .../annotation/EnableWebMvcExtensionTest.java | 17 ++++++ 2 files changed, 78 insertions(+) create mode 100644 microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java new file mode 100644 index 00000000..003c2a74 --- /dev/null +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.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 io.microsphere.spring.webmvc.annotation; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +/** + * {@link EnableWebMvcExtension} Test with defaults + * + * @author Mercy + * @see EnableWebMvcExtension + * @since 1.0.0 + */ +@RunWith(SpringRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { + EnableWebMvcExtensionDefaultTest.class +}) +@EnableWebMvc +@EnableWebMvcExtension +public class EnableWebMvcExtensionDefaultTest { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void test() { + + } +} diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java index d339742a..993eabfe 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java @@ -16,11 +16,17 @@ */ package io.microsphere.spring.webmvc.annotation; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; /** * {@link EnableWebMvcExtension} Test @@ -34,6 +40,7 @@ @ContextConfiguration(classes = { EnableWebMvcExtensionTest.class }) +@EnableWebMvc @EnableWebMvcExtension( registerHandlerInterceptors = true, storeRequestBodyArgument = true, @@ -41,6 +48,16 @@ ) public class EnableWebMvcExtensionTest { + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + @Test public void test() { From 57f836767337553fa84e66b0b62177ff1a8cf5af Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:11:19 +0800 Subject: [PATCH 09/25] Polish #57 --- microsphere-spring-parent/pom.xml | 9 + microsphere-spring-webmvc/pom.xml | 6 + .../AbstractEnableWebMvcExtensionTest.java | 160 ++++++++++++++++++ .../EnableWebMvcExtensionDefaultsTest.java | 66 ++++++++ ... => EnableWebMvcExtensionDisableTest.java} | 47 +++-- .../annotation/EnableWebMvcExtensionTest.java | 36 ++-- 6 files changed, 279 insertions(+), 45 deletions(-) create mode 100644 microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java create mode 100644 microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java rename microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/{EnableWebMvcExtensionDefaultTest.java => EnableWebMvcExtensionDisableTest.java} (51%) diff --git a/microsphere-spring-parent/pom.xml b/microsphere-spring-parent/pom.xml index 1ad6afcb..1aecebe5 100644 --- a/microsphere-spring-parent/pom.xml +++ b/microsphere-spring-parent/pom.xml @@ -29,6 +29,7 @@ 1.2.12 4.13.2 4.11.0 + 1.5.3 @@ -99,6 +100,14 @@ import + + + org.skyscreamer + jsonassert + ${jsonassert.version} + + + ch.qos.logback logback-classic diff --git a/microsphere-spring-webmvc/pom.xml b/microsphere-spring-webmvc/pom.xml index ae7b62be..4411f1db 100644 --- a/microsphere-spring-webmvc/pom.xml +++ b/microsphere-spring-webmvc/pom.xml @@ -75,6 +75,12 @@ test + + org.skyscreamer + jsonassert + test + + ch.qos.logback logback-classic diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java new file mode 100644 index 00000000..57e19b10 --- /dev/null +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -0,0 +1,160 @@ +/* + * 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 io.microsphere.spring.webmvc.annotation; + +import io.microsphere.spring.web.event.HandlerMethodArgumentsResolvedEvent; +import io.microsphere.spring.web.event.WebEndpointMappingsReadyEvent; +import io.microsphere.spring.web.metadata.WebEndpointMapping; +import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; +import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; +import io.microsphere.spring.webmvc.controller.TestController; +import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; +import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; +import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.context.event.EventListener; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.ConfigurableWebApplicationContext; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import java.lang.reflect.Method; +import java.util.Collection; + +import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +/** + * Abstract {@link EnableWebMvcExtension} Test + * + * @author Mercy + * @see EnableWebMvcExtension + * @since 1.0.0 + */ +@RunWith(SpringRunner.class) +@WebAppConfiguration +@EnableWebMvc +@Ignore +@Import(TestController.class) +abstract class AbstractEnableWebMvcExtensionTest { + + @Autowired + protected ConfigurableWebApplicationContext wac; + + protected MockMvc mockMvc; + + protected boolean registerWebEndpointMappings; + + protected boolean interceptHandlerMethods; + + protected boolean publishEvents; + + protected boolean registerHandlerInterceptors; + + protected boolean storeRequestBodyArgument; + + protected boolean storeResponseBodyReturnValue; + + @Before + public void setup() { + this.mockMvc = webAppContextSetup(this.wac).build(); + EnableWebMvcExtension enableWebMvcExtension = this.getClass().getAnnotation(EnableWebMvcExtension.class); + this.registerWebEndpointMappings = enableWebMvcExtension.registerWebEndpointMappings(); + this.interceptHandlerMethods = enableWebMvcExtension.interceptHandlerMethods(); + this.publishEvents = enableWebMvcExtension.publishEvents(); + this.registerHandlerInterceptors = enableWebMvcExtension.registerHandlerInterceptors(); + this.storeRequestBodyArgument = enableWebMvcExtension.storeRequestBodyArgument(); + this.storeResponseBodyReturnValue = enableWebMvcExtension.storeResponseBodyReturnValue(); + } + + @Test + public void testRegisteredBeans() { + assertTrue(isBeanPresent(this.wac, WebMvcExtensionConfiguration.class)); + assertEquals(this.registerWebEndpointMappings, isBeanPresent(this.wac, WebEndpointMappingRegistrar.class)); + assertEquals(this.interceptHandlerMethods, this.wac.containsBean(InterceptingHandlerMethodProcessor.BEAN_NAME)); + assertEquals(this.interceptHandlerMethods, isBeanPresent(this.wac, InterceptingHandlerMethodProcessor.class)); + assertEquals(this.registerHandlerInterceptors, isBeanPresent(this.wac, LazyCompositeHandlerInterceptor.class)); + assertEquals(this.storeRequestBodyArgument, isBeanPresent(this.wac, StoringRequestBodyArgumentAdvice.class)); + assertEquals(this.storeResponseBodyReturnValue, isBeanPresent(this.wac, StoringResponseBodyReturnValueAdvice.class)); + } + + @Test + public void test() throws Exception { + this.mockMvc.perform(get("/echo/hello")) + .andExpect(status().isOk()) + .andExpect(content().json("[ECHO] : hello")); + } + + /** + * Test only one mapping : {@link TestController#echo(String)} + * + * @param event {@link WebEndpointMappingsReadyEvent} + */ + @EventListener(WebEndpointMappingsReadyEvent.class) + public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) { + // Only TestController + Collection mappings = event.getMappings(); + assertEquals(1, mappings.size()); + WebEndpointMapping webEndpointMapping = mappings.iterator().next(); + String[] patterns = webEndpointMapping.getPatterns(); + assertEquals(1, patterns.length); + assertEquals("/echo/{message}", patterns[0]); + } + + /** + * Test only one method : {@link TestController#echo(String)} + * + * @param event {@link HandlerMethodArgumentsResolvedEvent} + */ + @EventListener(HandlerMethodArgumentsResolvedEvent.class) + public void onHandlerMethodArgumentsResolvedEvent(HandlerMethodArgumentsResolvedEvent event) { + Method method = event.getMethod(); + assertEquals("echo", method.getName()); + assertEquals(String.class, method.getReturnType()); + + Class[] parameterTypes = method.getParameterTypes(); + assertEquals(1, parameterTypes.length); + assertEquals(String.class, parameterTypes[0]); + + HandlerMethod handlerMethod = event.getHandlerMethod(); + assertNotNull(handlerMethod); + + Object bean = handlerMethod.getBean(); + assertNotNull(bean); + assertEquals(TestController.class, bean.getClass()); + assertEquals(method, handlerMethod.getMethod()); + + Object[] arguments = event.getArguments(); + assertEquals(1, arguments.length); + assertEquals("hello", arguments[0]); + } +} diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java new file mode 100644 index 00000000..ecd774b1 --- /dev/null +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.microsphere.spring.webmvc.annotation; + +import io.microsphere.spring.web.event.HandlerMethodArgumentsResolvedEvent; +import io.microsphere.spring.web.event.WebEndpointMappingsReadyEvent; +import io.microsphere.spring.web.metadata.WebEndpointMapping; +import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; +import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; +import io.microsphere.spring.webmvc.controller.TestController; +import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; +import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; +import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.ConfigurableWebApplicationContext; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import java.lang.reflect.Method; +import java.util.Collection; + +import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +/** + * {@link EnableWebMvcExtension} Test with defaults + * + * @author Mercy + * @see EnableWebMvcExtension + * @since 1.0.0 + */ +@ContextConfiguration(classes = { + EnableWebMvcExtensionDefaultsTest.class +}) +@EnableWebMvcExtension +public class EnableWebMvcExtensionDefaultsTest extends AbstractEnableWebMvcExtensionTest { +} diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java similarity index 51% rename from microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java rename to microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java index 003c2a74..2f94d9ad 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java @@ -16,6 +16,12 @@ */ package io.microsphere.spring.webmvc.annotation; +import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; +import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; +import io.microsphere.spring.webmvc.controller.TestController; +import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; +import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; +import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,38 +30,31 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + /** - * {@link EnableWebMvcExtension} Test with defaults + * {@link EnableWebMvcExtension} Test with disable features * * @author Mercy * @see EnableWebMvcExtension * @since 1.0.0 */ -@RunWith(SpringRunner.class) -@WebAppConfiguration @ContextConfiguration(classes = { - EnableWebMvcExtensionDefaultTest.class + EnableWebMvcExtensionDisableTest.class }) -@EnableWebMvc -@EnableWebMvcExtension -public class EnableWebMvcExtensionDefaultTest { - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void test() { - - } +@EnableWebMvcExtension( + registerWebEndpointMappings = false, + interceptHandlerMethods = false, + publishEvents = false +) +public class EnableWebMvcExtensionDisableTest extends AbstractEnableWebMvcExtensionTest { } diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java index 993eabfe..83fddbbd 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java @@ -16,6 +16,12 @@ */ package io.microsphere.spring.webmvc.annotation; +import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; +import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; +import io.microsphere.spring.webmvc.controller.TestController; +import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; +import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; +import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,10 +30,16 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + /** * {@link EnableWebMvcExtension} Test * @@ -35,31 +47,13 @@ * @see EnableWebMvcExtension * @since 1.0.0 */ -@RunWith(SpringRunner.class) -@WebAppConfiguration @ContextConfiguration(classes = { EnableWebMvcExtensionTest.class }) -@EnableWebMvc @EnableWebMvcExtension( registerHandlerInterceptors = true, storeRequestBodyArgument = true, storeResponseBodyReturnValue = true ) -public class EnableWebMvcExtensionTest { - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void test() { - - } +public class EnableWebMvcExtensionTest extends AbstractEnableWebMvcExtensionTest { } From 73814f31d81edcc647e81290c016a59d0e5e74ca Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:12:58 +0800 Subject: [PATCH 10/25] Polish #57 --- .../webmvc/annotation/AbstractEnableWebMvcExtensionTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index 57e19b10..5bfbfe99 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -121,6 +121,8 @@ public void test() throws Exception { */ @EventListener(WebEndpointMappingsReadyEvent.class) public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) { + assertTrue(publishEvents); + // Only TestController Collection mappings = event.getMappings(); assertEquals(1, mappings.size()); @@ -137,6 +139,8 @@ public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) */ @EventListener(HandlerMethodArgumentsResolvedEvent.class) public void onHandlerMethodArgumentsResolvedEvent(HandlerMethodArgumentsResolvedEvent event) { + assertTrue(publishEvents); + Method method = event.getMethod(); assertEquals("echo", method.getName()); assertEquals(String.class, method.getReturnType()); @@ -156,5 +160,6 @@ public void onHandlerMethodArgumentsResolvedEvent(HandlerMethodArgumentsResolved Object[] arguments = event.getArguments(); assertEquals(1, arguments.length); assertEquals("hello", arguments[0]); + } } From 37ef3b74d7f2b511887d3d70c9a695b0fe259378 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:14:03 +0800 Subject: [PATCH 11/25] Polish #57 --- .../AbstractEnableWebMvcExtensionTest.java | 2 -- .../EnableWebMvcExtensionDefaultsTest.java | 33 ------------------- .../EnableWebMvcExtensionDisableTest.java | 23 ------------- .../annotation/EnableWebMvcExtensionTest.java | 22 ------------- 4 files changed, 80 deletions(-) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index 5bfbfe99..9fbc74b0 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -32,7 +32,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.context.event.EventListener; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; @@ -45,7 +44,6 @@ import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java index ecd774b1..771953dc 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDefaultsTest.java @@ -16,40 +16,7 @@ */ package io.microsphere.spring.webmvc.annotation; -import io.microsphere.spring.web.event.HandlerMethodArgumentsResolvedEvent; -import io.microsphere.spring.web.event.WebEndpointMappingsReadyEvent; -import io.microsphere.spring.web.metadata.WebEndpointMapping; -import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; -import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; -import io.microsphere.spring.webmvc.controller.TestController; -import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; -import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; -import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.event.EventListener; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -import java.lang.reflect.Method; -import java.util.Collection; - -import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * {@link EnableWebMvcExtension} Test with defaults diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java index 2f94d9ad..7f413bad 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionDisableTest.java @@ -16,30 +16,7 @@ */ package io.microsphere.spring.webmvc.annotation; -import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; -import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; -import io.microsphere.spring.webmvc.controller.TestController; -import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; -import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; -import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * {@link EnableWebMvcExtension} Test with disable features diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java index 83fddbbd..84071f87 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionTest.java @@ -16,29 +16,7 @@ */ package io.microsphere.spring.webmvc.annotation; -import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; -import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; -import io.microsphere.spring.webmvc.controller.TestController; -import io.microsphere.spring.webmvc.interceptor.LazyCompositeHandlerInterceptor; -import io.microsphere.spring.webmvc.metadata.WebEndpointMappingRegistrar; -import io.microsphere.spring.webmvc.method.support.InterceptingHandlerMethodProcessor; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * {@link EnableWebMvcExtension} Test From e22d28aa3647b5ce298418bb0341956bfb1bc74e Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:27:06 +0800 Subject: [PATCH 12/25] Polish #57 --- .../webmvc/annotation/AbstractEnableWebMvcExtensionTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index 9fbc74b0..4bcabca2 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -119,8 +119,6 @@ public void test() throws Exception { */ @EventListener(WebEndpointMappingsReadyEvent.class) public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) { - assertTrue(publishEvents); - // Only TestController Collection mappings = event.getMappings(); assertEquals(1, mappings.size()); @@ -137,8 +135,6 @@ public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) */ @EventListener(HandlerMethodArgumentsResolvedEvent.class) public void onHandlerMethodArgumentsResolvedEvent(HandlerMethodArgumentsResolvedEvent event) { - assertTrue(publishEvents); - Method method = event.getMethod(); assertEquals("echo", method.getName()); assertEquals(String.class, method.getReturnType()); From 327d9740bbc14cab366f1bb2f47c07d42d6d8356 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:44:11 +0800 Subject: [PATCH 13/25] Polish #57 --- .../AbstractEnableWebMvcExtensionTest.java | 4 +- ...EnableWebMvcExtensionInterceptorsTest.java | 51 +++++++++++++++++++ ...tentAnnotatedMethodHandlerInterceptor.java | 32 +++++++----- 3 files changed, 72 insertions(+), 15 deletions(-) create mode 100644 microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionInterceptorsTest.java diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index 4bcabca2..1fc028e2 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -43,6 +43,7 @@ import java.util.Collection; import static io.microsphere.spring.beans.BeanUtils.isBeanPresent; +import static io.microsphere.util.ArrayUtils.isNotEmpty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -89,7 +90,8 @@ public void setup() { this.registerWebEndpointMappings = enableWebMvcExtension.registerWebEndpointMappings(); this.interceptHandlerMethods = enableWebMvcExtension.interceptHandlerMethods(); this.publishEvents = enableWebMvcExtension.publishEvents(); - this.registerHandlerInterceptors = enableWebMvcExtension.registerHandlerInterceptors(); + this.registerHandlerInterceptors = enableWebMvcExtension.registerHandlerInterceptors() ? true : + isNotEmpty(enableWebMvcExtension.handlerInterceptors()); this.storeRequestBodyArgument = enableWebMvcExtension.storeRequestBodyArgument(); this.storeResponseBodyReturnValue = enableWebMvcExtension.storeResponseBodyReturnValue(); } diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionInterceptorsTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionInterceptorsTest.java new file mode 100644 index 00000000..c109f6cc --- /dev/null +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/EnableWebMvcExtensionInterceptorsTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.microsphere.spring.webmvc.annotation; + +import io.microsphere.spring.webmvc.interceptor.IdempotentAnnotatedMethodHandlerInterceptor; +import org.junit.Test; +import org.springframework.test.context.ContextConfiguration; + +import static io.microsphere.spring.webmvc.interceptor.IdempotentAnnotatedMethodHandlerInterceptor.MOCK_TOKEN_VALUE; +import static io.microsphere.spring.webmvc.interceptor.IdempotentAnnotatedMethodHandlerInterceptor.TOKEN_HEADER_NAME; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * {@link EnableWebMvcExtension} Test with interceptors + * + * @author Mercy + * @see EnableWebMvcExtension + * @since 1.0.0 + */ +@ContextConfiguration(classes = { + EnableWebMvcExtensionInterceptorsTest.class +}) +@EnableWebMvcExtension(handlerInterceptors = { + IdempotentAnnotatedMethodHandlerInterceptor.class +}) +public class EnableWebMvcExtensionInterceptorsTest extends AbstractEnableWebMvcExtensionTest { + + @Test + @Override + public void test() throws Exception { + this.mockMvc.perform(get("/echo/hello").header(TOKEN_HEADER_NAME, MOCK_TOKEN_VALUE)) + .andExpect(status().isOk()) + .andExpect(content().json("[ECHO] : hello")); + } +} diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java index 61d3325e..9761fa9e 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java @@ -16,6 +16,7 @@ */ package io.microsphere.spring.webmvc.interceptor; +import io.microsphere.logging.Logger; import io.microsphere.spring.web.event.HandlerMethodArgumentsResolvedEvent; import io.microsphere.spring.webmvc.IdempotentException; import io.microsphere.spring.webmvc.annotation.Idempotent; @@ -29,6 +30,11 @@ import javax.servlet.http.HttpSession; import java.lang.reflect.Method; import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +import static io.microsphere.logging.LoggerFactory.getLogger; +import static java.util.Arrays.asList; /** * {@link AnnotatedMethodHandlerInterceptor} for {@link Idempotent} annotation @@ -36,15 +42,18 @@ * @author Mercy * @since 1.0.0 */ -public class IdempotentAnnotatedMethodHandlerInterceptor extends AnnotatedMethodHandlerInterceptor implements ApplicationListener { +public class IdempotentAnnotatedMethodHandlerInterceptor extends AnnotatedMethodHandlerInterceptor + implements ApplicationListener { + + private static final Logger logger = getLogger(IdempotentAnnotatedMethodHandlerInterceptor.class); + + public static final String TOKEN_HEADER_NAME = "_token_"; + + public static final String MOCK_TOKEN_VALUE = UUID.randomUUID().toString(); @Override protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod, Idempotent idempotent) throws Exception { - - System.out.println(handlerMethod); - System.out.println(idempotent); - return true; } @@ -54,19 +63,14 @@ protected boolean preHandle(HttpServletRequest request, HttpServletResponse resp public void onApplicationEvent(HandlerMethodArgumentsResolvedEvent event) { Method method = event.getMethod(); Object[] args = event.getArguments(); - System.out.println("method : " + method + " , args : " + Arrays.asList(args)); WebRequest webRequest = event.getWebRequest(); + logger.trace("The method : {} , args : {} , webRequest : {}", method, asList(args), webRequest); if (webRequest instanceof ServletWebRequest) { ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest; HttpServletRequest request = servletWebRequest.getNativeRequest(HttpServletRequest.class); - // HttpSession based on Spring Redis - // Spring Session - HttpSession httpSession = request.getSession(); - String token = request.getHeader("token"); - Object tokenValue = httpSession.getAttribute(token); - if (tokenValue != null) { - // - throw new IdempotentException(""); + String token = request.getHeader(TOKEN_HEADER_NAME); + if (!Objects.equals(MOCK_TOKEN_VALUE, token)) { + throw new IdempotentException("Illegal token"); } } } From 2b951ed62cc243dca80d42cf4c869d446ad9a3d1 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 19:54:34 +0800 Subject: [PATCH 14/25] Polish #57 : Add assertions --- .../annotation/AbstractEnableWebMvcExtensionTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index 1fc028e2..cbdc55f8 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -18,7 +18,10 @@ import io.microsphere.spring.web.event.HandlerMethodArgumentsResolvedEvent; import io.microsphere.spring.web.event.WebEndpointMappingsReadyEvent; +import io.microsphere.spring.web.event.WebEventPublisher; +import io.microsphere.spring.web.metadata.SimpleWebEndpointMappingRegistry; import io.microsphere.spring.web.metadata.WebEndpointMapping; +import io.microsphere.spring.web.method.support.DelegatingHandlerMethodAdvice; import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; import io.microsphere.spring.webmvc.controller.TestController; @@ -99,7 +102,14 @@ public void setup() { @Test public void testRegisteredBeans() { assertTrue(isBeanPresent(this.wac, WebMvcExtensionConfiguration.class)); + // From @EnableWebExtension + assertEquals(this.registerWebEndpointMappings, isBeanPresent(this.wac, SimpleWebEndpointMappingRegistry.class)); + assertEquals(this.interceptHandlerMethods, this.wac.containsBean(DelegatingHandlerMethodAdvice.BEAN_NAME)); + assertEquals(this.publishEvents, isBeanPresent(this.wac, WebEventPublisher.class)); + + // From @EnableWebMvcExtension assertEquals(this.registerWebEndpointMappings, isBeanPresent(this.wac, WebEndpointMappingRegistrar.class)); + assertEquals(this.interceptHandlerMethods, isBeanPresent(this.wac, DelegatingHandlerMethodAdvice.class)); assertEquals(this.interceptHandlerMethods, this.wac.containsBean(InterceptingHandlerMethodProcessor.BEAN_NAME)); assertEquals(this.interceptHandlerMethods, isBeanPresent(this.wac, InterceptingHandlerMethodProcessor.class)); assertEquals(this.registerHandlerInterceptors, isBeanPresent(this.wac, LazyCompositeHandlerInterceptor.class)); From b654649e99ed8a9c78eaea6721aae4703c3410a8 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:20:28 +0800 Subject: [PATCH 15/25] Polish #84 --- .../method/support/HandlerMethodAdvice.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodAdvice.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodAdvice.java index bc20c6f9..5eb5dd54 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodAdvice.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodAdvice.java @@ -41,8 +41,9 @@ public interface HandlerMethodAdvice { * @param webRequest the current request * @throws Exception in case of errors with the preparation of argument values */ - void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMethod, NativeWebRequest webRequest) - throws Exception; + default void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMethod, NativeWebRequest webRequest) + throws Exception { + } /** * callback after the {@link MethodParameter} being resolved @@ -54,8 +55,9 @@ void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMetho * @return the resolved argument value, or {@code null} if not resolvable * @throws Exception in case of errors with the preparation of argument values */ - void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, HandlerMethod handlerMethod, - NativeWebRequest webRequest) throws Exception; + default void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, HandlerMethod handlerMethod, + NativeWebRequest webRequest) throws Exception { + } /** * Interception point before the execution of a {@link HandlerMethod}. Called after @@ -67,7 +69,8 @@ void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, Ha * @param request {@link WebRequest} * @throws Exception if any error caused */ - void beforeExecuteMethod(HandlerMethod handlerMethod, Object[] args, NativeWebRequest request) throws Exception; + default void beforeExecuteMethod(HandlerMethod handlerMethod, Object[] args, NativeWebRequest request) throws Exception { + } /** * Interception point after successful execution of a {@link HandlerMethod}. @@ -80,7 +83,8 @@ void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, Ha * @param request {@link WebRequest} * @throws Exception if any error caused */ - void afterExecuteMethod(HandlerMethod handlerMethod, Object[] args, @Nullable Object returnValue, @Nullable Throwable error, - NativeWebRequest request) throws Exception; + default void afterExecuteMethod(HandlerMethod handlerMethod, Object[] args, @Nullable Object returnValue, @Nullable Throwable error, + NativeWebRequest request) throws Exception { + } } From ebe49486c8e2c80f00834d11f0514fbb32cafb18 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:22:11 +0800 Subject: [PATCH 16/25] Polish #85 --- .../support/HandlerMethodArgumentInterceptor.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodArgumentInterceptor.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodArgumentInterceptor.java index 130c6de8..5799a90a 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodArgumentInterceptor.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodArgumentInterceptor.java @@ -20,7 +20,6 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.HandlerMethod; - /** * The interceptor interface for the resolvable {@link HandlerMethod HandlerMethods'} {@link MethodParameter} * @@ -39,8 +38,9 @@ public interface HandlerMethodArgumentInterceptor { * @param webRequest the current request * @throws Exception in case of errors with the preparation of argument values */ - void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMethod, NativeWebRequest webRequest) - throws Exception; + default void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMethod, NativeWebRequest webRequest) + throws Exception { + } /** * callback after the {@link MethodParameter} being resolved @@ -52,8 +52,8 @@ void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMetho * @return the resolved argument value, or {@code null} if not resolvable * @throws Exception in case of errors with the preparation of argument values */ - void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, HandlerMethod handlerMethod, - NativeWebRequest webRequest) throws Exception; - + default void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, HandlerMethod handlerMethod, + NativeWebRequest webRequest) throws Exception { + } -} +} \ No newline at end of file From 5c4fa0a4713a0b43c30b2543f144725a129443bd Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:23:43 +0800 Subject: [PATCH 17/25] Polish #86 --- .../web/method/support/HandlerMethodInterceptor.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodInterceptor.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodInterceptor.java index 98749a32..16d8d011 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodInterceptor.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/method/support/HandlerMethodInterceptor.java @@ -37,7 +37,8 @@ public interface HandlerMethodInterceptor { * @param request {@link WebRequest} * @throws Exception if any error caused */ - void beforeExecute(HandlerMethod handlerMethod, Object[] args, NativeWebRequest request) throws Exception; + default void beforeExecute(HandlerMethod handlerMethod, Object[] args, NativeWebRequest request) throws Exception { + } /** * Interception point after successful execution of a {@link HandlerMethod}. @@ -50,7 +51,8 @@ public interface HandlerMethodInterceptor { * @param request {@link WebRequest} * @throws Exception if any error caused */ - void afterExecute(HandlerMethod handlerMethod, Object[] args, @Nullable Object returnValue, @Nullable Throwable error, - NativeWebRequest request) throws Exception; + default void afterExecute(HandlerMethod handlerMethod, Object[] args, @Nullable Object returnValue, @Nullable Throwable error, + NativeWebRequest request) throws Exception { + } } From 1b3a9629971923a605ab7a16c34da2515d3240f1 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:31:03 +0800 Subject: [PATCH 18/25] Polish #86 : Reuse default method --- .../io/microsphere/spring/web/event/WebEventPublisher.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/event/WebEventPublisher.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/event/WebEventPublisher.java index ef841ea6..39f5a19c 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/event/WebEventPublisher.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/event/WebEventPublisher.java @@ -54,11 +54,6 @@ public void beforeExecute(HandlerMethod handlerMethod, Object[] args, NativeWebR context.publishEvent(new HandlerMethodArgumentsResolvedEvent(request, handlerMethod, args)); } - @Override - public void afterExecute(HandlerMethod handlerMethod, Object[] args, Object returnValue, Throwable error, NativeWebRequest request) throws Exception { - // DO NOTHING - } - @Override protected void doStart() { WebEndpointMappingRegistry webEndpointMappingRegistry = context.getBean(WebEndpointMappingRegistry.class); From 1bed56794ea419335080053e8dddadfd6f752147 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:41:44 +0800 Subject: [PATCH 19/25] Polish #57 : HandlerMethodArgumentInterceptor Testing --- .../AbstractEnableWebMvcExtensionTest.java | 68 +++++++++++++++++-- 1 file changed, 63 insertions(+), 5 deletions(-) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java index cbdc55f8..3c9b6530 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/annotation/AbstractEnableWebMvcExtensionTest.java @@ -22,6 +22,7 @@ import io.microsphere.spring.web.metadata.SimpleWebEndpointMappingRegistry; import io.microsphere.spring.web.metadata.WebEndpointMapping; import io.microsphere.spring.web.method.support.DelegatingHandlerMethodAdvice; +import io.microsphere.spring.web.method.support.HandlerMethodArgumentInterceptor; import io.microsphere.spring.webmvc.advice.StoringRequestBodyArgumentAdvice; import io.microsphere.spring.webmvc.advice.StoringResponseBodyReturnValueAdvice; import io.microsphere.spring.webmvc.controller.TestController; @@ -35,10 +36,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.context.event.EventListener; +import org.springframework.core.MethodParameter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.context.ConfigurableWebApplicationContext; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @@ -67,7 +70,7 @@ @EnableWebMvc @Ignore @Import(TestController.class) -abstract class AbstractEnableWebMvcExtensionTest { +abstract class AbstractEnableWebMvcExtensionTest implements HandlerMethodArgumentInterceptor { @Autowired protected ConfigurableWebApplicationContext wac; @@ -148,24 +151,79 @@ public void onWebEndpointMappingsReadyEvent(WebEndpointMappingsReadyEvent event) @EventListener(HandlerMethodArgumentsResolvedEvent.class) public void onHandlerMethodArgumentsResolvedEvent(HandlerMethodArgumentsResolvedEvent event) { Method method = event.getMethod(); + assertMethod(method); + + HandlerMethod handlerMethod = event.getHandlerMethod(); + assertEquals(method, handlerMethod.getMethod()); + + assertHandlerMethod(handlerMethod); + + Object[] arguments = event.getArguments(); + assertArguments(arguments); + } + + /** + * callback before the {@link MethodParameter} being resolved + * + * @param parameter the method parameter to resolve. + * @param handlerMethod the method to handle + * @param webRequest the current request + * @throws Exception in case of errors with the preparation of argument values + */ + @Override + public void beforeResolveArgument(MethodParameter parameter, HandlerMethod handlerMethod, NativeWebRequest webRequest) throws Exception { + assertMethodParameter(parameter); + assertHandlerMethod(handlerMethod); + assertNativeWebRequest(webRequest); + } + + /** + * callback after the {@link MethodParameter} being resolved + * + * @param parameter the method parameter to resolve. + * @param resolvedArgument the resolved argument + * @param handlerMethod the method to handle + * @param webRequest the current request + * @return the resolved argument value, or {@code null} if not resolvable + * @throws Exception in case of errors with the preparation of argument values + */ + @Override + public void afterResolveArgument(MethodParameter parameter, Object resolvedArgument, HandlerMethod handlerMethod, NativeWebRequest webRequest) throws Exception { + // Reuse + beforeResolveArgument(parameter, handlerMethod, webRequest); + assertEquals("hello", resolvedArgument); + } + + private void assertMethod(Method method) { assertEquals("echo", method.getName()); assertEquals(String.class, method.getReturnType()); Class[] parameterTypes = method.getParameterTypes(); assertEquals(1, parameterTypes.length); assertEquals(String.class, parameterTypes[0]); + } - HandlerMethod handlerMethod = event.getHandlerMethod(); + private void assertHandlerMethod(HandlerMethod handlerMethod) { assertNotNull(handlerMethod); - Object bean = handlerMethod.getBean(); assertNotNull(bean); assertEquals(TestController.class, bean.getClass()); - assertEquals(method, handlerMethod.getMethod()); + assertMethod(handlerMethod.getMethod()); + } - Object[] arguments = event.getArguments(); + private void assertArguments(Object[] arguments) { assertEquals(1, arguments.length); assertEquals("hello", arguments[0]); + } + private void assertMethodParameter(MethodParameter parameter) { + assertNotNull(parameter); + assertEquals(0, parameter.getParameterIndex()); + assertEquals(String.class, parameter.getParameterType()); } + + private void assertNativeWebRequest(NativeWebRequest webRequest) { + } + + } From bce39374b47f271cdf72b0c9da6570199658c9cb Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 21:42:09 +0800 Subject: [PATCH 20/25] Update IdempotentAnnotatedMethodHandlerInterceptor.java --- .../IdempotentAnnotatedMethodHandlerInterceptor.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java index 9761fa9e..90f41f58 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/interceptor/IdempotentAnnotatedMethodHandlerInterceptor.java @@ -27,9 +27,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; import java.lang.reflect.Method; -import java.util.Arrays; import java.util.Objects; import java.util.UUID; From 316431ba869a076f8e811049b54813706d1393f0 Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 22:14:01 +0800 Subject: [PATCH 21/25] Polish #88 --- .../microsphere/spring/beans/BeanUtils.java | 2 +- .../beans/factory/BeanFactoryUtils.java | 2 +- .../DefaultBeanDependencyResolver.java | 3 +- .../spring/beans/factory/Dependency.java | 9 +-- .../beans/factory/DependencyTreeWalker.java | 6 +- .../AnnotatedInjectionBeanPostProcessor.java | 79 +++++++++---------- ...onBeanDefinitionRegistryPostProcessor.java | 6 +- .../AnnotationInjectedBeanPostProcessor.java | 68 ++++++++-------- .../ConfigurationBeanBindingRegistrar.java | 7 +- .../beans/factory/support/BeanRegistrar.java | 4 +- .../cache/intereptor/TTLCacheResolver.java | 3 +- ...ctingConfigurationPropertyInitializer.java | 14 +++- .../spring/config/ConfigurationProperty.java | 11 +-- .../PropertySourceExtensionLoader.java | 8 +- .../DeferredApplicationEventPublisher.java | 4 +- ...DependencyAnalysisBeanFactoryListener.java | 1 + .../EventPublishingBeanAfterProcessor.java | 6 +- .../OnceApplicationContextEventListener.java | 4 +- .../core/annotation/AnnotationUtils.java | 13 ++- .../ListenableConfigurableEnvironment.java | 5 +- 20 files changed, 128 insertions(+), 127 deletions(-) diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java index 9db2762f..0c4a4c3d 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java @@ -44,6 +44,7 @@ import static io.microsphere.spring.beans.factory.BeanFactoryUtils.asConfigurableBeanFactory; import static io.microsphere.spring.context.ApplicationContextUtils.asConfigurableApplicationContext; import static io.microsphere.spring.context.ApplicationContextUtils.getApplicationContextAwareProcessor; +import static io.microsphere.util.ArrayUtils.isEmpty; import static io.microsphere.util.ClassLoaderUtils.resolveClass; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; @@ -53,7 +54,6 @@ import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName; import static org.springframework.util.ClassUtils.getUserClass; -import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.StringUtils.hasText; /** diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/BeanFactoryUtils.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/BeanFactoryUtils.java index c5220373..8cea585a 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/BeanFactoryUtils.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/BeanFactoryUtils.java @@ -65,7 +65,6 @@ public abstract class BeanFactoryUtils extends BaseUtils { * @return A bean if present , or null */ public static T getOptionalBean(ListableBeanFactory beanFactory, String beanName, Class beanType) { - if (!hasText(beanName)) { return null; } @@ -77,6 +76,7 @@ public static T getOptionalBean(ListableBeanFactory beanFactory, String bean return isEmpty(beans) ? null : beans.get(0); } + /** * Gets name-matched Beans from {@link ListableBeanFactory BeanFactory} * diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java index 2701c386..cf8fc216 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java @@ -53,6 +53,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import static io.microsphere.collection.CollectionUtils.isNotEmpty; import static io.microsphere.collection.ListUtils.newLinkedList; import static io.microsphere.collection.MapUtils.newHashMap; import static io.microsphere.collection.MapUtils.ofEntry; @@ -252,7 +253,7 @@ private void flattenDependentBeanNamesMap(Map> dependentBean Set dependentBeanNames = entry.getValue(); for (String dependentBeanName : dependentBeanNames) { Set nestedDependentBeanNames = dependentBeanNamesMap.get(dependentBeanName); - if (CollectionUtils.isNotEmpty(nestedDependentBeanNames) && !dependentBeanNames.containsAll(nestedDependentBeanNames)) { + if (isNotEmpty(nestedDependentBeanNames) && !dependentBeanNames.containsAll(nestedDependentBeanNames)) { nonRootBeanNames.add(beanName); break; } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/Dependency.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/Dependency.java index 264b1878..32b341df 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/Dependency.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/Dependency.java @@ -16,9 +16,6 @@ */ package io.microsphere.spring.beans.factory; -import io.microsphere.collection.CollectionUtils; -import io.microsphere.util.ArrayUtils; - import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; @@ -26,8 +23,10 @@ import java.util.List; import java.util.Objects; +import static io.microsphere.collection.CollectionUtils.size; import static io.microsphere.collection.ListUtils.newArrayList; import static io.microsphere.collection.ListUtils.newLinkedList; +import static io.microsphere.util.ArrayUtils.length; import static java.util.Collections.emptyList; import static org.springframework.util.Assert.hasText; @@ -149,7 +148,7 @@ public static Dependency create(String beanName, Dependency parent, String... de } private static List createList(Iterable beanNames) { - int length = CollectionUtils.size(beanNames); + int length = size(beanNames); if (length < 1) { return emptyList(); } @@ -163,7 +162,7 @@ private static List createList(Iterable beanNames) { } private static List createList(String[] beanNames) { - int length = ArrayUtils.length(beanNames); + int length = length(beanNames); if (length < 1) { return emptyList(); } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DependencyTreeWalker.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DependencyTreeWalker.java index a1f2e1b2..e112e0b7 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DependencyTreeWalker.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DependencyTreeWalker.java @@ -16,11 +16,11 @@ */ package io.microsphere.spring.beans.factory; -import io.microsphere.collection.CollectionUtils; - import java.util.Iterator; import java.util.List; +import static io.microsphere.collection.CollectionUtils.isEmpty; + /** * {@link Dependency} Tree Walker * @@ -54,7 +54,7 @@ private void removeIfDuplicated(Dependency dependency) { } private void walk(Dependency child, List siblings) { - if (CollectionUtils.isEmpty(siblings)) { + if (isEmpty(siblings)) { return; } if (siblings.contains(child)) { diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessor.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessor.java index 3b4e8b61..29bebb50 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessor.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessor.java @@ -45,7 +45,6 @@ import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotationMetadata; -import org.springframework.util.ReflectionUtils; import javax.annotation.Nullable; import java.beans.PropertyDescriptor; @@ -75,11 +74,15 @@ import static java.lang.Integer.getInteger; import static java.util.Collections.singleton; import static java.util.Collections.unmodifiableCollection; +import static org.springframework.beans.factory.annotation.InjectionMetadata.needsRefresh; import static org.springframework.core.BridgeMethodResolver.findBridgedMethod; import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair; import static org.springframework.util.Assert.notEmpty; import static org.springframework.util.ClassUtils.getMostSpecificMethod; import static org.springframework.util.ClassUtils.getUserClass; +import static org.springframework.util.ReflectionUtils.doWithFields; +import static org.springframework.util.ReflectionUtils.doWithMethods; +import static org.springframework.util.ReflectionUtils.makeAccessible; import static org.springframework.util.StringUtils.hasLength; /** @@ -305,27 +308,24 @@ private List findFieldAnnotationMetadata(final Class b final List elements = new LinkedList(); - ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + doWithFields(beanClass, field -> { - for (Class annotationType : getAnnotationTypes()) { + for (Class annotationType : getAnnotationTypes()) { - AnnotationAttributes attributes = doGetAnnotationAttributes(field, annotationType); + AnnotationAttributes attributes = doGetAnnotationAttributes(field, annotationType); - if (attributes != null) { + if (attributes != null) { - if (Modifier.isStatic(field.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@" + annotationType.getName() + " is not supported on static fields: " + field); - } - return; + if (Modifier.isStatic(field.getModifiers())) { + if (logger.isWarnEnabled()) { + logger.warn("@" + annotationType.getName() + " is not supported on static fields: " + field); } + return; + } - boolean required = determineRequiredStatus(attributes); + boolean required = determineRequiredStatus(attributes); - elements.add(new AnnotatedFieldElement(field, attributes, required)); - } + elements.add(new AnnotatedFieldElement(field, attributes, required)); } } }); @@ -354,36 +354,33 @@ private List findAnnotatedMethodMetadata(final Class final List elements = new LinkedList(); - ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + doWithMethods(beanClass, method -> { - Method bridgedMethod = findBridgedMethod(method); + Method bridgedMethod = findBridgedMethod(method); - if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { - return; - } + if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { + return; + } - for (Class annotationType : getAnnotationTypes()) { + for (Class annotationType : getAnnotationTypes()) { - AnnotationAttributes attributes = doGetAnnotationAttributes(bridgedMethod, annotationType); + AnnotationAttributes attributes = doGetAnnotationAttributes(bridgedMethod, annotationType); - if (attributes != null && method.equals(getMostSpecificMethod(method, beanClass))) { - if (Modifier.isStatic(method.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@" + annotationType.getName() + " annotation is not supported on static methods: " + method); - } - return; + if (attributes != null && method.equals(getMostSpecificMethod(method, beanClass))) { + if (Modifier.isStatic(method.getModifiers())) { + if (logger.isWarnEnabled()) { + logger.warn("@" + annotationType.getName() + " annotation is not supported on static methods: " + method); } - if (method.getParameterTypes().length == 0) { - if (logger.isWarnEnabled()) { - logger.warn("@" + annotationType.getName() + " annotation should only be used on methods with parameters: " + method); - } + return; + } + if (method.getParameterTypes().length == 0) { + if (logger.isWarnEnabled()) { + logger.warn("@" + annotationType.getName() + " annotation should only be used on methods with parameters: " + method); } - PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); - boolean required = determineRequiredStatus(attributes); - elements.add(new AnnotatedMethodElement(method, pd, attributes, required)); } + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); + boolean required = determineRequiredStatus(attributes); + elements.add(new AnnotatedMethodElement(method, pd, attributes, required)); } } }); @@ -424,10 +421,10 @@ private InjectionMetadata findInjectionMetadata(String beanName, Class clazz, String cacheKey = (hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. AnnotatedInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); - if (InjectionMetadata.needsRefresh(metadata, clazz)) { + if (needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); - if (InjectionMetadata.needsRefresh(metadata, clazz)) { + if (needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } @@ -695,7 +692,7 @@ protected void inject(Object bean, @Nullable String beanName, @Nullable Property value = resolveFieldValue(field, bean, beanName, pvs); } if (value != null) { - ReflectionUtils.makeAccessible(field); + makeAccessible(field); field.set(bean, value); } } @@ -769,7 +766,7 @@ protected void inject(Object bean, @Nullable String beanName, @Nullable Property } if (arguments != null) { try { - ReflectionUtils.makeAccessible(method); + makeAccessible(method); method.invoke(bean, arguments); } catch (InvocationTargetException ex) { throw ex.getTargetException(); diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessor.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessor.java index 66841026..9a3d4eae 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessor.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessor.java @@ -35,7 +35,6 @@ import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.util.ObjectUtils; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; @@ -50,6 +49,7 @@ import static io.microsphere.spring.context.annotation.AnnotatedBeanDefinitionRegistryUtils.resolveAnnotatedBeanNameGenerator; import static io.microsphere.spring.core.annotation.AnnotationUtils.tryGetMergedAnnotation; import static io.microsphere.spring.core.env.EnvironmentUtils.asConfigurableEnvironment; +import static io.microsphere.util.ArrayUtils.isNotEmpty; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import static org.springframework.util.Assert.noNullElements; @@ -144,7 +144,7 @@ public final void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry regis String[] basePackages = resolveBasePackages(getPackagesToScan()); - if (!ObjectUtils.isEmpty(basePackages)) { + if (isNotEmpty(basePackages)) { registerBeanDefinitions(registry, basePackages); } else { if (logger.isWarnEnabled()) { @@ -218,7 +218,7 @@ private void putPrimaryBeanDefinitions(Map prim private void putPrimaryBeanDefinition(Map primaryBeanDefinitions, AnnotatedBeanDefinition annotatedBeanDefinition, String... keys) { - if (!ObjectUtils.isEmpty(keys)) { + if (isNotEmpty(keys)) { for (String key : keys) { primaryBeanDefinitions.put(key, annotatedBeanDefinition); } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessor.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessor.java index ef58ce91..68e05577 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessor.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessor.java @@ -35,7 +35,6 @@ import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import org.springframework.core.env.Environment; -import org.springframework.util.ReflectionUtils; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; @@ -60,6 +59,9 @@ import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import static org.springframework.core.annotation.AnnotationUtils.getAnnotation; import static org.springframework.util.ClassUtils.getMostSpecificMethod; +import static org.springframework.util.ReflectionUtils.doWithFields; +import static org.springframework.util.ReflectionUtils.doWithMethods; +import static org.springframework.util.ReflectionUtils.makeAccessible; import static org.springframework.util.StringUtils.hasLength; /** @@ -153,25 +155,22 @@ private List findFieldAnnotationMetadata(final Class b final List elements = new LinkedList(); - ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + doWithFields(beanClass, field -> { - A annotation = getAnnotation(field, getAnnotationType()); + A annotation = getAnnotation(field, getAnnotationType()); - if (annotation != null) { + if (annotation != null) { - if (Modifier.isStatic(field.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@" + getAnnotationType().getName() + " is not supported on static fields: " + field); - } - return; + if (Modifier.isStatic(field.getModifiers())) { + if (logger.isWarnEnabled()) { + logger.warn("@" + getAnnotationType().getName() + " is not supported on static fields: " + field); } - - elements.add(new AnnotatedFieldElement(field, annotation)); + return; } + elements.add(new AnnotatedFieldElement(field, annotation)); } + }); return elements; @@ -188,34 +187,31 @@ private List findAnnotatedMethodMetadata(final Class final List elements = new LinkedList(); - ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + doWithMethods(beanClass, method -> { - Method bridgedMethod = findBridgedMethod(method); + Method bridgedMethod = findBridgedMethod(method); - if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { - return; - } + if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { + return; + } - A annotation = findAnnotation(bridgedMethod, getAnnotationType()); + A annotation = findAnnotation(bridgedMethod, getAnnotationType()); - if (annotation != null && method.equals(getMostSpecificMethod(method, beanClass))) { - if (Modifier.isStatic(method.getModifiers())) { - if (logger.isWarnEnabled()) { - logger.warn("@" + getAnnotationType().getSimpleName() + " annotation is not supported on static methods: " + method); - } - return; + if (annotation != null && method.equals(getMostSpecificMethod(method, beanClass))) { + if (Modifier.isStatic(method.getModifiers())) { + if (logger.isWarnEnabled()) { + logger.warn("@" + getAnnotationType().getSimpleName() + " annotation is not supported on static methods: " + method); } - if (method.getParameterTypes().length == 0) { - if (logger.isWarnEnabled()) { - logger.warn("@" + getAnnotationType().getSimpleName() + " annotation should only be used on methods with parameters: " + - method); - } + return; + } + if (method.getParameterTypes().length == 0) { + if (logger.isWarnEnabled()) { + logger.warn("@" + getAnnotationType().getSimpleName() + " annotation should only be used on methods with parameters: " + + method); } - PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); - elements.add(new AnnotatedMethodElement(method, pd, annotation)); } + PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); + elements.add(new AnnotatedMethodElement(method, pd, annotation)); } }); @@ -494,7 +490,7 @@ protected void inject(Object bean, String beanName, PropertyValues pvs) throws T Object injectedObject = getInjectedObject(annotation, bean, beanName, injectedType, this); - ReflectionUtils.makeAccessible(method); + makeAccessible(method); method.invoke(bean, injectedObject); @@ -526,7 +522,7 @@ protected void inject(Object bean, String beanName, PropertyValues pvs) throws T Object injectedObject = getInjectedObject(annotation, bean, beanName, injectedType, this); - ReflectionUtils.makeAccessible(field); + makeAccessible(field); field.set(bean, injectedObject); diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/ConfigurationBeanBindingRegistrar.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/ConfigurationBeanBindingRegistrar.java index 20d59735..a83c95ce 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/ConfigurationBeanBindingRegistrar.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/annotation/ConfigurationBeanBindingRegistrar.java @@ -18,13 +18,11 @@ import io.microsphere.logging.Logger; import io.microsphere.spring.beans.factory.support.ConfigurationBeanAliasGenerator; -import io.microsphere.spring.core.env.PropertySourcesUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; @@ -54,6 +52,7 @@ import static java.lang.Boolean.valueOf; import static java.util.Collections.singleton; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; +import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName; import static org.springframework.util.StringUtils.hasText; /** @@ -105,7 +104,7 @@ private void registerConfigurationBeans(String prefix, Class configClass, boo boolean ignoreUnknownFields, boolean ignoreInvalidFields, BeanDefinitionRegistry registry) { - Map configurationProperties = PropertySourcesUtils.getSubProperties(environment.getPropertySources(), environment, prefix); + Map configurationProperties = getSubProperties(environment.getPropertySources(), environment, prefix); Set beanNames = multiple ? resolveMultipleBeanNames(configurationProperties) : singleton(resolveSingleBeanName(configurationProperties, configClass, registry)); @@ -207,7 +206,7 @@ private String resolveSingleBeanName(Map properties, Class co if (!hasText(beanName)) { BeanDefinitionBuilder builder = rootBeanDefinition(configClass); - beanName = BeanDefinitionReaderUtils.generateBeanName(builder.getRawBeanDefinition(), registry); + beanName = generateBeanName(builder.getRawBeanDefinition(), registry); } return beanName; diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/support/BeanRegistrar.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/support/BeanRegistrar.java index 610c76b5..802ca54d 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/support/BeanRegistrar.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/support/BeanRegistrar.java @@ -18,7 +18,6 @@ import io.microsphere.logging.Logger; import io.microsphere.spring.beans.factory.DelegatingFactoryBean; -import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; @@ -36,6 +35,7 @@ import static io.microsphere.spring.beans.factory.config.BeanDefinitionUtils.setInstanceSupplier; import static java.beans.Introspector.decapitalize; import static java.lang.String.format; +import static org.springframework.aop.support.AopUtils.getTargetClass; import static org.springframework.beans.factory.config.BeanDefinition.ROLE_INFRASTRUCTURE; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName; import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames; @@ -256,7 +256,7 @@ public static void registerBean(BeanDefinitionRegistry registry, String beanName } public static void registerBean(BeanDefinitionRegistry registry, String beanName, Object bean, boolean primary) { - Class beanClass = AopUtils.getTargetClass(bean); + Class beanClass = getTargetClass(bean); AbstractBeanDefinition beanDefinition = genericBeanDefinition(beanClass); if (setInstanceSupplier(beanDefinition, () -> bean)) { beanDefinition.setPrimary(primary); diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java index 31757d12..72535359 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java @@ -48,6 +48,7 @@ import static io.microsphere.logging.LoggerFactory.getLogger; import static io.microsphere.spring.core.annotation.AnnotationUtils.getAnnotationAttributes; +import static io.microsphere.util.ArrayUtils.isEmpty; import static java.time.Duration.ofMillis; import static java.util.Collections.emptyList; @@ -100,7 +101,7 @@ public Collection resolveCaches(CacheOperationInvocationContext Collection targetCacheManagers; String[] cacheManagerBeanNames = ttlAnnotationAttributes.getStringArray("cacheManagers"); - if (ArrayUtils.isEmpty(cacheManagerBeanNames)) { + if (isEmpty(cacheManagerBeanNames)) { targetCacheManagers = namedCacheManagersMap.values(); } else { targetCacheManagers = new LinkedList<>(); diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/CollectingConfigurationPropertyInitializer.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/CollectingConfigurationPropertyInitializer.java index 62d49bdb..a821ae19 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/CollectingConfigurationPropertyInitializer.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/CollectingConfigurationPropertyInitializer.java @@ -16,9 +16,16 @@ */ package io.microsphere.spring.config; +import io.microsphere.spring.core.env.PropertyResolverListener; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; +import static io.microsphere.spring.beans.factory.support.BeanRegistrar.registerBean; +import static io.microsphere.spring.beans.factory.support.BeanRegistrar.registerSpringFactoriesBeans; +import static io.microsphere.spring.config.ConfigurationPropertyRepository.BEAN_NAME; + /** * The Initializer for Collecting Configuration Property * @@ -32,6 +39,11 @@ public class CollectingConfigurationPropertyInitializer implements ApplicationCo @Override public void initialize(ConfigurableApplicationContext applicationContext) { - + ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); + // Load PropertyResolverListener SPI and then be registered as the bean + registerSpringFactoriesBeans(beanFactory, PropertyResolverListener.class); + // Register ConfigurationPropertyRepository + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + registerBean(registry, BEAN_NAME, ConfigurationPropertyRepository.class); } } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/ConfigurationProperty.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/ConfigurationProperty.java index ec3c9e36..7cdd1c38 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/ConfigurationProperty.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/ConfigurationProperty.java @@ -21,8 +21,9 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; +import java.util.LinkedHashSet; import java.util.Objects; +import java.util.Set; import static io.microsphere.util.Assert.assertNotNull; @@ -179,7 +180,7 @@ public static class Metadata { /** * The targets of the property */ - private List targets; + private Set targets = new LinkedHashSet<>(8); public String getDescription() { return description; @@ -189,14 +190,10 @@ public void setDescription(String description) { this.description = description; } - public List getTargets() { + public Set getTargets() { return targets; } - public void setTargets(List targets) { - this.targets = targets; - } - @Override public final boolean equals(Object o) { if (!(o instanceof Metadata)) return false; diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/context/annotation/PropertySourceExtensionLoader.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/context/annotation/PropertySourceExtensionLoader.java index ae98f7d3..ebcea4b9 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/config/context/annotation/PropertySourceExtensionLoader.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/config/context/annotation/PropertySourceExtensionLoader.java @@ -18,7 +18,6 @@ import io.microsphere.spring.config.env.event.PropertySourceChangedEvent; import io.microsphere.spring.config.env.event.PropertySourcesChangedEvent; -import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Configuration; @@ -37,7 +36,6 @@ import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.AntPathMatcher; -import org.springframework.util.ObjectUtils; import org.springframework.util.PathMatcher; import javax.annotation.Nonnull; @@ -56,10 +54,12 @@ import static io.microsphere.spring.config.env.event.PropertySourceChangedEvent.added; import static io.microsphere.spring.config.env.event.PropertySourceChangedEvent.replaced; import static io.microsphere.text.FormatUtils.format; +import static io.microsphere.util.ArrayUtils.isEmpty; import static io.microsphere.util.StringUtils.EMPTY_STRING_ARRAY; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static java.util.Collections.sort; +import static org.springframework.beans.BeanUtils.instantiateClass; import static org.springframework.util.Assert.notNull; import static org.springframework.util.StringUtils.hasText; @@ -378,7 +378,7 @@ private List resolvePropertySourceResources(EA extension boolean ignoreResourceNotFound = extensionAttributes.isIgnoreResourceNotFound(); - if (ObjectUtils.isEmpty(resourceValues)) { + if (isEmpty(resourceValues)) { if (ignoreResourceNotFound) { return emptyList(); } @@ -523,7 +523,7 @@ protected void configureResourcePropertySourcesRefresher(EA extensionAttributes, protected T createInstance(EA extensionAttributes, Function> classFunction) { Class type = classFunction.apply(extensionAttributes); - return BeanUtils.instantiateClass(type); + return instantiateClass(type); } @Override diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisher.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisher.java index 6ac3a590..b7842c68 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisher.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisher.java @@ -24,7 +24,6 @@ import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.util.ReflectionUtils; import java.lang.reflect.Method; import java.util.Iterator; @@ -33,6 +32,7 @@ import static org.springframework.util.Assert.notNull; import static org.springframework.util.ReflectionUtils.findField; import static org.springframework.util.ReflectionUtils.findMethod; +import static org.springframework.util.ReflectionUtils.invokeMethod; /** * Before Spring Framework 4.2, {@link AbstractApplicationContext} is an implementation of {@link ApplicationEventPublisher} @@ -132,7 +132,7 @@ private void deferEvent(ApplicationEvent event) { public void publishEvent(Object event) { if (supportsEarlyApplicationEvents() && supportsPublishEventMethod()) { // invoke by reflection to resolve the compilation issue - ReflectionUtils.invokeMethod(PUBLISH_EVENT_METHOD, delegate, event); + invokeMethod(PUBLISH_EVENT_METHOD, delegate, event); } else { // before Spring 4.2 // DO NOTHING, just resolve the compilation issue in Spring 4.2 and above } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java index f5ab00b6..954cfa04 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java @@ -57,6 +57,7 @@ import static io.microsphere.spring.beans.factory.config.BeanDefinitionUtils.getInstanceSupplier; import static io.microsphere.spring.core.MethodParameterUtils.forParameter; import static io.microsphere.util.ArrayUtils.EMPTY_PARAMETER_ARRAY; +import static io.microsphere.util.ClassLoaderUtils.resolveClass; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/EventPublishingBeanAfterProcessor.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/EventPublishingBeanAfterProcessor.java index b263c33d..6f4b2aad 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/EventPublishingBeanAfterProcessor.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/EventPublishingBeanAfterProcessor.java @@ -28,7 +28,6 @@ import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.ResolvableType; -import org.springframework.util.ReflectionUtils; import java.util.Map; import java.util.Objects; @@ -38,6 +37,7 @@ import static io.microsphere.spring.context.event.BeanListeners.getBean; import static io.microsphere.spring.context.event.BeanListeners.getReadyBeanNames; import static io.microsphere.util.ClassLoaderUtils.resolveClass; +import static org.springframework.util.ReflectionUtils.doWithFields; /** * Bean After-Event Publishing Processor @@ -111,7 +111,7 @@ private void onContextClosedEvent(ContextClosedEvent event) { private void decorateDisposableBeans() { ConfigurableListableBeanFactory beanFactory = this.context.getBeanFactory(); if (beanFactory instanceof DefaultSingletonBeanRegistry) { - ReflectionUtils.doWithFields(DefaultSingletonBeanRegistry.class, field -> { + doWithFields(DefaultSingletonBeanRegistry.class, field -> { field.setAccessible(true); Map disposableBeans = (Map) field.get(beanFactory); for (Map.Entry entry : disposableBeans.entrySet()) { @@ -185,7 +185,7 @@ private static class DecoratingDisposableBean implements DisposableBean { @Override public void destroy() throws Exception { this.delegate.destroy(); - ReflectionUtils.doWithFields(DISPOSABLE_BEAN_ADAPTER_CLASS, field -> { + doWithFields(DISPOSABLE_BEAN_ADAPTER_CLASS, field -> { field.setAccessible(true); Object bean = field.get(this.delegate); this.destroyedCallback.accept(this.beanName, bean); diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/OnceApplicationContextEventListener.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/OnceApplicationContextEventListener.java index f1ef2c1b..5a1148c5 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/OnceApplicationContextEventListener.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/OnceApplicationContextEventListener.java @@ -23,9 +23,9 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationContextEvent; -import org.springframework.util.ClassUtils; import static io.microsphere.logging.LoggerFactory.getLogger; +import static org.springframework.util.ClassUtils.getShortName; import static org.springframework.util.ObjectUtils.nullSafeEquals; /** @@ -89,7 +89,7 @@ public ApplicationContext getApplicationContext() { if (applicationContext == null) { throw new NullPointerException("applicationContext must be not null, it has to invoke " + "setApplicationContext(ApplicationContext) method first if " - + ClassUtils.getShortName(getClass()) + " instance is not a Spring Bean"); + + getShortName(getClass()) + " instance is not a Spring Bean"); } return applicationContext; } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java index 68b04dce..4638352f 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java @@ -14,7 +14,6 @@ import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -24,6 +23,8 @@ import static java.lang.String.valueOf; import static java.util.Arrays.asList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.unmodifiableMap; import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedAnnotationAttributes; import static org.springframework.core.annotation.AnnotationAttributes.fromMap; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; @@ -52,11 +53,8 @@ public abstract class AnnotationUtils { * @return If present , return true , or false */ public static boolean isPresent(Method method, Class annotationClass) { - Map> annotationsMap = findAnnotations(method, annotationClass); - return !annotationsMap.isEmpty(); - } /** @@ -78,10 +76,10 @@ public static Map> findAnnotations(M RetentionPolicy retentionPolicy = retention.value(); if (!RetentionPolicy.RUNTIME.equals(retentionPolicy)) { - return Collections.emptyMap(); + return emptyMap(); } - Map> annotationsMap = new LinkedHashMap>(); + Map> annotationsMap = new LinkedHashMap<>(); Target target = annotationClass.getAnnotation(Target.class); @@ -125,8 +123,7 @@ public static Map> findAnnotations(M annotationsMap.put(elementType, annotationsList); } } - - return Collections.unmodifiableMap(annotationsMap); + return unmodifiableMap(annotationsMap); } diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironment.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironment.java index c0ba3d8a..ef7f2a0d 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironment.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironment.java @@ -40,6 +40,7 @@ import static io.microsphere.logging.LoggerFactory.getLogger; import static io.microsphere.spring.constants.PropertyConstants.MICROSPHERE_SPRING_PROPERTY_NAME_PREFIX; import static io.microsphere.spring.core.io.support.SpringFactoriesLoaderUtils.loadFactories; +import static java.util.Arrays.asList; import static org.springframework.core.annotation.AnnotationAwareOrderComparator.sort; /** @@ -233,7 +234,7 @@ public boolean acceptsProfiles(Profiles profiles) { } catch (Throwable e) { if (logger.isWarnEnabled()) { logger.warn("Failed to invokeExact on {} with args : '{}'", ACCEPTS_PROFILES_METHOD_HANDLE, - Arrays.asList(delegate, profiles), e); + asList(delegate, profiles), e); } } } @@ -388,7 +389,7 @@ public Class getPropertyAsClass(String key, Class targetType) { } catch (Throwable e) { if (logger.isWarnEnabled()) { logger.warn("Failed to invokeExact on {} with args : '{}'", GET_PROPERTY_AS_CLASS_METHOD_HANDLE, - Arrays.asList(key, targetType), e); + asList(key, targetType), e); } } return value; From ff84c5b96794efc06aebc17de85229eaefa9266b Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 23:01:19 +0800 Subject: [PATCH 22/25] Polish #89 --- .../microsphere/spring/beans/BeanUtils.java | 3 +- .../DefaultBeanDependencyResolver.java | 1 - .../cache/intereptor/TTLCacheResolver.java | 1 - ...DependencyAnalysisBeanFactoryListener.java | 1 - .../beans/factory/BeanFactoryUtilsTest.java | 21 +++++----- ...notatedInjectionBeanPostProcessorTest.java | 38 +++++++++--------- ...anDefinitionRegistryPostProcessorTest.java | 4 +- ...notationInjectedBeanPostProcessorTest.java | 36 +++++++++-------- ...tionBeanBindingTestForMultipleBinding.java | 4 +- .../GenericBeanPostProcessorAdapterTest.java | 5 +-- ...DeferredApplicationEventPublisherTest.java | 4 +- .../core/annotation/AnnotationUtilsTest.java | 34 +++++++--------- .../GenericAnnotationAttributesTest.java | 2 +- ...ListenableConfigurableEnvironmentTest.java | 2 +- .../SpringProtocolURLStreamHandlerTest.java | 4 +- microsphere-spring-parent/pom.xml | 32 ++++++--------- .../Jackson2WebEndpointMappingFactory.java | 5 ++- .../web/rule/WebRequestPattensRule.java | 4 +- .../web/rule/WebRequestProducesRule.java | 4 +- ...entNegotiationManagerWebMvcConfigurer.java | 40 +++++++------------ ...ctPageRenderContextHandlerInterceptor.java | 13 ++---- .../spring/webmvc/util/WebMvcUtils.java | 32 +++++++-------- ...pingInfoWebEndpointMappingFactoryTest.java | 4 +- 23 files changed, 133 insertions(+), 161 deletions(-) diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java index 0c4a4c3d..3934c45d 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/BeanUtils.java @@ -54,6 +54,7 @@ import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.beans.factory.support.BeanDefinitionReaderUtils.generateBeanName; import static org.springframework.util.ClassUtils.getUserClass; +import static org.springframework.util.ClassUtils.resolveClassName; import static org.springframework.util.StringUtils.hasText; /** @@ -207,7 +208,7 @@ public static Class resolveBeanType(String beanClassName, ClassLoader classLo Class beanType = null; try { - beanType = resolveClass(beanClassName, classLoader); + beanType = resolveClassName(beanClassName, classLoader); beanType = getUserClass(beanType); } catch (Exception e) { if (logger.isErrorEnabled()) { diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java index cf8fc216..68081702 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/beans/factory/DefaultBeanDependencyResolver.java @@ -16,7 +16,6 @@ */ package io.microsphere.spring.beans.factory; -import io.microsphere.collection.CollectionUtils; import io.microsphere.collection.SetUtils; import io.microsphere.lang.function.ThrowableAction; import io.microsphere.logging.Logger; diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java index 72535359..892c44b3 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/cache/intereptor/TTLCacheResolver.java @@ -22,7 +22,6 @@ import io.microsphere.spring.cache.annotation.TTLCachePut; import io.microsphere.spring.cache.annotation.TTLCacheable; import io.microsphere.spring.context.event.OnceApplicationContextEventListener; -import io.microsphere.util.ArrayUtils; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.CacheOperation; diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java index 954cfa04..f5ab00b6 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/context/event/DependencyAnalysisBeanFactoryListener.java @@ -57,7 +57,6 @@ import static io.microsphere.spring.beans.factory.config.BeanDefinitionUtils.getInstanceSupplier; import static io.microsphere.spring.core.MethodParameterUtils.forParameter; import static io.microsphere.util.ArrayUtils.EMPTY_PARAMETER_ARRAY; -import static io.microsphere.util.ClassLoaderUtils.resolveClass; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/BeanFactoryUtilsTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/BeanFactoryUtilsTest.java index 7e7b2a28..886d99e5 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/BeanFactoryUtilsTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/BeanFactoryUtilsTest.java @@ -17,7 +17,6 @@ package io.microsphere.spring.beans.factory; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; @@ -49,6 +48,8 @@ import static io.microsphere.util.ArrayUtils.of; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -79,11 +80,11 @@ public void testGetOptionalBean() { applicationContext.register(BaseTestBean.class); - applicationContext.refresh(); + this.applicationContext.refresh(); BaseTestBean testBean = getOptionalBean(applicationContext, "baseTestBean", BaseTestBean.class); - Assert.assertNotNull(testBean); + assertNotNull(testBean); assertEquals("Hello,World", testBean.getName()); @@ -92,27 +93,27 @@ public void testGetOptionalBean() { @Test public void testGetOptionalBeanIfAbsent() { - applicationContext.refresh(); + this.applicationContext.refresh(); BaseTestBean testBean = getOptionalBean(applicationContext, "baseTestBean", BaseTestBean.class); - Assert.assertNull(testBean); + assertNull(testBean); testBean = getOptionalBean(applicationContext, "1", BaseTestBean.class); - Assert.assertNull(testBean); + assertNull(testBean); testBean = getOptionalBean(applicationContext, null, BaseTestBean.class); - Assert.assertNull(testBean); + assertNull(testBean); } @Test public void testGetBeans() { - applicationContext.register(BaseTestBean.class, BaseTestBean2.class); + this.applicationContext.register(BaseTestBean.class, BaseTestBean2.class); - applicationContext.refresh(); + this.applicationContext.refresh(); List testBeans = getBeans(applicationContext, new String[]{"baseTestBean"}, BaseTestBean.class); @@ -136,7 +137,7 @@ public void testGetBeans() { @Test public void testGetBeansIfAbsent() { - applicationContext.refresh(); + this.applicationContext.refresh(); List testBeans = getBeans(applicationContext, new String[]{"baseTestBean"}, BaseTestBean.class); diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessorTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessorTest.java index a315019f..44691e3d 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessorTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotatedInjectionBeanPostProcessorTest.java @@ -17,7 +17,6 @@ package io.microsphere.spring.beans.factory.annotation; import io.microsphere.spring.util.User; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -27,14 +26,17 @@ import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * {@link AnnotatedInjectionBeanPostProcessor} Test * * @since 1.0.0 */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration(classes = { AnnotationInjectedBeanPostProcessorTest.TestConfiguration.class, AnnotatedInjectionBeanPostProcessorTest.ReferencedInjectedBeanPostProcessor.class, @@ -69,26 +71,26 @@ public class AnnotatedInjectionBeanPostProcessorTest { @Test public void testCustomizedAnnotationBeanPostProcessor() { - Assert.assertEquals(environment, processor.getEnvironment()); - Assert.assertEquals(beanFactory.getBeanClassLoader(), processor.getClassLoader()); - Assert.assertEquals(beanFactory, processor.getBeanFactory()); + assertEquals(environment, processor.getEnvironment()); + assertEquals(beanFactory.getBeanClassLoader(), processor.getClassLoader()); + assertEquals(beanFactory, processor.getBeanFactory()); - Assert.assertEquals(1, processor.getAnnotationTypes().size()); - Assert.assertTrue(processor.getAnnotationTypes().contains(Referenced.class)); - Assert.assertEquals(Ordered.LOWEST_PRECEDENCE - 3, processor.getOrder()); + assertEquals(1, processor.getAnnotationTypes().size()); + assertTrue(processor.getAnnotationTypes().contains(Referenced.class)); + assertEquals(Ordered.LOWEST_PRECEDENCE - 3, processor.getOrder()); } @Test public void testReferencedUser() { - Assert.assertEquals("mercyblitz", parent.user.getName()); - Assert.assertEquals(32, parent.user.getAge()); - Assert.assertEquals(parent.user, parent.parentUser); - Assert.assertEquals(parent.user, child.childUser); - Assert.assertEquals(parent.user, userHolder.user); - Assert.assertEquals(parent.user, genericChild.s); - Assert.assertEquals(parent.user, genericChild.s1); - Assert.assertEquals(parent.user, genericChild.s2); - Assert.assertEquals(parent.user, child.user); + assertEquals("mercyblitz", parent.user.getName()); + assertEquals(32, parent.user.getAge()); + assertEquals(parent.user, parent.parentUser); + assertEquals(parent.user, child.childUser); + assertEquals(parent.user, userHolder.user); + assertEquals(parent.user, genericChild.s); + assertEquals(parent.user, genericChild.s1); + assertEquals(parent.user, genericChild.s2); + assertEquals(parent.user, child.user); } public static class ReferencedInjectedBeanPostProcessor extends AnnotatedInjectionBeanPostProcessor { diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessorTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessorTest.java index d9e0120c..33489f7d 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessorTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationBeanDefinitionRegistryPostProcessorTest.java @@ -24,7 +24,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; @@ -44,7 +44,7 @@ * @author Mercy * @since 1.0.0 */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration(classes = { AnnotationBeanDefinitionRegistryPostProcessorTest.ServiceAnnotationBeanDefinitionRegistryPostProcessor.class, AnnotationBeanDefinitionRegistryPostProcessorTest.class diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessorTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessorTest.java index 5f5e497e..e0a54ed6 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessorTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/AnnotationInjectedBeanPostProcessorTest.java @@ -17,7 +17,6 @@ package io.microsphere.spring.beans.factory.annotation; import io.microsphere.spring.util.User; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +27,10 @@ import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * {@link AnnotationInjectedBeanPostProcessor} Test @@ -36,7 +38,7 @@ * @author Mercy * @since 1.0.0 */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration(classes = { AnnotationInjectedBeanPostProcessorTest.TestConfiguration.class, AnnotationInjectedBeanPostProcessorTest.ReferencedAnnotationInjectedBeanPostProcessor.class @@ -67,25 +69,25 @@ public class AnnotationInjectedBeanPostProcessorTest { @Test public void testCustomizedAnnotationBeanPostProcessor() { - Assert.assertEquals(environment, processor.getEnvironment()); - Assert.assertEquals(beanFactory.getBeanClassLoader(), processor.getClassLoader()); - Assert.assertEquals(beanFactory, processor.getBeanFactory()); + assertEquals(environment, processor.getEnvironment()); + assertEquals(beanFactory.getBeanClassLoader(), processor.getClassLoader()); + assertEquals(beanFactory, processor.getBeanFactory()); - Assert.assertEquals(Referenced.class, processor.getAnnotationType()); - Assert.assertEquals(1, processor.getInjectedObjects().size()); - Assert.assertTrue(processor.getInjectedObjects().contains(parent.parentUser)); - Assert.assertEquals(2, processor.getInjectedFieldObjectsMap().size()); - Assert.assertEquals(1, processor.getInjectedMethodObjectsMap().size()); - Assert.assertEquals(Ordered.HIGHEST_PRECEDENCE, processor.getOrder()); + assertEquals(Referenced.class, processor.getAnnotationType()); + assertEquals(1, processor.getInjectedObjects().size()); + assertTrue(processor.getInjectedObjects().contains(parent.parentUser)); + assertEquals(2, processor.getInjectedFieldObjectsMap().size()); + assertEquals(1, processor.getInjectedMethodObjectsMap().size()); + assertEquals(Ordered.HIGHEST_PRECEDENCE, processor.getOrder()); } @Test public void testReferencedUser() { - Assert.assertEquals("mercyblitz", parent.user.getName()); - Assert.assertEquals(32, parent.user.getAge()); - Assert.assertEquals(parent.user, parent.parentUser); - Assert.assertEquals(parent.user, child.childUser); - Assert.assertEquals(parent.user, userHolder.user); + assertEquals("mercyblitz", parent.user.getName()); + assertEquals(32, parent.user.getAge()); + assertEquals(parent.user, parent.parentUser); + assertEquals(parent.user, child.childUser); + assertEquals(parent.user, userHolder.user); } static class TestConfiguration { diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java index d575122f..4e100dbd 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java @@ -23,7 +23,6 @@ * @since 1.0.0 */ -import io.microsphere.spring.beans.BeanUtils; import io.microsphere.spring.context.config.DefaultConfigurationBeanBinder; import io.microsphere.spring.util.User; import org.junit.Before; @@ -32,6 +31,7 @@ import java.util.Collection; +import static io.microsphere.spring.beans.BeanUtils.getSortedBeans; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -61,7 +61,7 @@ public ConfigurationBeanBindingPostProcessor configurationBeanBindingPostProcess public void init() { aUser = context.getBean("a", User.class); bUser = context.getBean("b", User.class); - users = BeanUtils.getSortedBeans(context, User.class); + users = getSortedBeans(context, User.class); configurationBeanBindingPostProcessor = context.getBean("configurationBeanBindingPostProcessor", ConfigurationBeanBindingPostProcessor.class); } diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/config/GenericBeanPostProcessorAdapterTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/config/GenericBeanPostProcessorAdapterTest.java index d4615e21..4cfe5a41 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/config/GenericBeanPostProcessorAdapterTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/config/GenericBeanPostProcessorAdapterTest.java @@ -2,7 +2,6 @@ import io.microsphere.spring.test.Bean; import io.microsphere.spring.test.TestBean; -import org.junit.Assert; import org.junit.Test; import org.springframework.beans.BeansException; @@ -92,8 +91,8 @@ public void testPostProcess() { String bean = "test"; - Assert.assertEquals("test", beanPostProcessor.postProcessBeforeInitialization(bean, "")); - Assert.assertEquals("test", beanPostProcessor.postProcessAfterInitialization(bean, "")); + assertEquals("test", beanPostProcessor.postProcessBeforeInitialization(bean, "")); + assertEquals("test", beanPostProcessor.postProcessAfterInitialization(bean, "")); } @Test diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisherTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisherTest.java index e10842b2..81949052 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisherTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/context/event/DeferredApplicationEventPublisherTest.java @@ -27,7 +27,7 @@ import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.ApplicationListener; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import static org.junit.Assert.assertEquals; @@ -38,7 +38,7 @@ * @author Mercy * @since 1.0.0 */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration( classes = TestConfig.class, loader = AnnotationConfigContextLoader.class diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/AnnotationUtilsTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/AnnotationUtilsTest.java index d352375e..e6135b9b 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/AnnotationUtilsTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/AnnotationUtilsTest.java @@ -1,6 +1,5 @@ package io.microsphere.spring.core.annotation; -import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.support.AbstractBeanDefinition; @@ -23,11 +22,14 @@ import static io.microsphere.spring.core.annotation.AnnotationUtils.getAnnotationAttributes; import static io.microsphere.spring.core.annotation.AnnotationUtils.getAttribute; import static io.microsphere.spring.core.annotation.AnnotationUtils.getAttributes; +import static io.microsphere.spring.core.annotation.AnnotationUtils.isPresent; import static io.microsphere.spring.util.SpringVersionUtils.SPRING_CONTEXT_VERSION; import static io.microsphere.util.ArrayUtils.of; import static junit.framework.TestCase.assertNull; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.springframework.util.ReflectionUtils.findMethod; /** @@ -60,27 +62,21 @@ public void testIsPresent() { Method method = findMethod(RuntimeAnnotationHandler.class, "handle", String.class, String.class); - AnnotationUtils.isPresent(method, RuntimeAnnotation.class); + assertTrue(isPresent(method, RuntimeAnnotation.class)); method = findMethod(RuntimeAnnotationHandler.class, "handle", String.class); - AnnotationUtils.isPresent(method, RuntimeAnnotation.class); + assertTrue(isPresent(method, RuntimeAnnotation.class)); method = findMethod(RuntimeAnnotationHandler.class, "handle"); - AnnotationUtils.isPresent(method, RuntimeAnnotation.class); - - method = findMethod(RuntimeAnnotationHandler.class, "handle"); - - AnnotationUtils.isPresent(method, RuntimeAnnotation.class); - + assertTrue(isPresent(method, RuntimeAnnotation.class)); method = findMethod(ClassAnnotationHandler.class, "echo", String.class); - AnnotationUtils.isPresent(method, ClassAnnotation.class); - + assertFalse(isPresent(method, ClassAnnotation.class)); } @Test @@ -125,7 +121,7 @@ public void testFindAnnotations() { annotationsList = annotationsMap.get(ElementType.PACKAGE); - Assert.assertNull(annotationsList); + assertNull(annotationsList); method = findMethod(ClassAnnotationHandler.class, "handle", @@ -133,12 +129,12 @@ public void testFindAnnotations() { annotationsMap = findAnnotations(method, RuntimeAnnotation.class); - Assert.assertTrue(annotationsMap.isEmpty()); + assertTrue(annotationsMap.isEmpty()); Map> classAnnotationsMap = findAnnotations(method, ClassAnnotation.class); - Assert.assertTrue(classAnnotationsMap.isEmpty()); + assertTrue(classAnnotationsMap.isEmpty()); } @Test @@ -147,10 +143,10 @@ public void testGetAttributes() { Bean annotation = getAnnotation("dummyBean", Bean.class); Map attributes = getAttributes(annotation, true); - Assert.assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name"))); + assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name"))); attributes = getAttributes(annotation, true); - Assert.assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name"))); + assertTrue(Arrays.equals(new String[]{"dummy-bean"}, (String[]) attributes.get("name"))); attributes = getAttributes(annotation, false); if (SPRING_CONTEXT_VERSION.getMajor() < 6) { @@ -171,16 +167,16 @@ public void testGetAttributes() { annotation = getAnnotation("dummyBean2", Bean.class); attributes = getAttributes(annotation, true); - Assert.assertTrue(attributes.isEmpty()); + assertTrue(attributes.isEmpty()); attributes = getAttributes(annotation, environment, true); - Assert.assertTrue(attributes.isEmpty()); + assertTrue(attributes.isEmpty()); environment.setProperty("beanName", "Your Bean Name"); annotation = getAnnotation("dummyBean3", Bean.class); attributes = getAttributes(annotation, environment, true); - Assert.assertTrue(Arrays.deepEquals(of(environment.getProperty("beanName")), (String[]) attributes.get("name"))); + assertTrue(Arrays.deepEquals(of(environment.getProperty("beanName")), (String[]) attributes.get("name"))); } diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/GenericAnnotationAttributesTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/GenericAnnotationAttributesTest.java index e02edd7b..b03983af 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/GenericAnnotationAttributesTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/annotation/GenericAnnotationAttributesTest.java @@ -48,7 +48,7 @@ public void test() { assertEquals(contextConfiguration.loader(), annotationAttributes.getClass("loader")); assertEquals(contextConfiguration.inheritInitializers(), annotationAttributes.getBoolean("inheritInitializers")); assertEquals(contextConfiguration.inheritLocations(), annotationAttributes.getBoolean("inheritLocations")); - assertEquals(contextConfiguration.value(), annotationAttributes.getStringArray("value")); + assertArrayEquals(contextConfiguration.value(), annotationAttributes.getStringArray("value")); } } diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironmentTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironmentTest.java index 8c70a045..a1e2f9f0 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironmentTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/core/env/ListenableConfigurableEnvironmentTest.java @@ -297,7 +297,7 @@ public void testValidateRequiredProperties() { @Test public void testGetDelegate() { - assertTrue(environment instanceof ListenableConfigurableEnvironment); + assertTrue(ListenableConfigurableEnvironment.class.isInstance(environment)); assertNotSame(environment, environment.getDelegate()); } } diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/net/SpringProtocolURLStreamHandlerTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/net/SpringProtocolURLStreamHandlerTest.java index 47a475e0..aa4275e9 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/net/SpringProtocolURLStreamHandlerTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/net/SpringProtocolURLStreamHandlerTest.java @@ -21,7 +21,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.StreamUtils; import java.io.IOException; import java.io.InputStream; @@ -32,6 +31,7 @@ import java.util.List; import static org.junit.Assert.assertNotNull; +import static org.springframework.util.StreamUtils.copyToString; /** * {@link SpringProtocolURLStreamHandler} Test @@ -64,7 +64,7 @@ public void testSpringDelegatingBeanURLConnectionFactory() throws Throwable { private void assertContent(URL url) throws Throwable { String content = null; try (InputStream inputStream = url.openStream()) { - content = StreamUtils.copyToString(inputStream, Charset.defaultCharset()); + content = copyToString(inputStream, Charset.defaultCharset()); } assertNotNull(content); } diff --git a/microsphere-spring-parent/pom.xml b/microsphere-spring-parent/pom.xml index 1aecebe5..540f57dc 100644 --- a/microsphere-spring-parent/pom.xml +++ b/microsphere-spring-parent/pom.xml @@ -20,11 +20,9 @@ 0.0.9 - 5.3.39 4.0.1 2.18.2 2.3 - 6.1.10.RELEASE 1.7.36 1.2.12 4.13.2 @@ -35,15 +33,6 @@ - - - io.github.microsphere-projects - microsphere-java-dependencies - ${microsphere-java.version} - pom - import - - org.springframework @@ -62,13 +51,6 @@ import - - - io.lettuce - lettuce-core - ${lettuce.version} - - org.yaml @@ -100,7 +82,7 @@ import - + org.skyscreamer jsonassert @@ -114,6 +96,15 @@ ${logback.version} + + + io.github.microsphere-projects + microsphere-java-dependencies + ${microsphere-java.version} + pom + import + + @@ -148,6 +139,9 @@ spring-framework-5.3 + + true + 5.3.39 diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/metadata/Jackson2WebEndpointMappingFactory.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/metadata/Jackson2WebEndpointMappingFactory.java index 7eb6c770..f0180ed0 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/metadata/Jackson2WebEndpointMappingFactory.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/metadata/Jackson2WebEndpointMappingFactory.java @@ -17,7 +17,8 @@ package io.microsphere.spring.web.metadata; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.util.ClassUtils; + +import static org.springframework.util.ClassUtils.isPresent; /** * The {@link WebEndpointMappingFactory} class based on Jackson2 for JSON @@ -31,7 +32,7 @@ public class Jackson2WebEndpointMappingFactory extends AbstractWebEndpointMappin private static final ClassLoader classLoader = Jackson2WebEndpointMappingFactory.class.getClassLoader(); - private static final boolean objectMapperPresent = ClassUtils.isPresent(OBJECT_MAPPER_CLASS_NAME, classLoader); + private static final boolean objectMapperPresent = isPresent(OBJECT_MAPPER_CLASS_NAME, classLoader); @Override public boolean supports(String endpoint) { diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestPattensRule.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestPattensRule.java index 35b6f60c..dd18830a 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestPattensRule.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestPattensRule.java @@ -17,7 +17,6 @@ package io.microsphere.spring.web.rule; import org.springframework.util.AntPathMatcher; -import org.springframework.util.ObjectUtils; import org.springframework.util.PathMatcher; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.util.UrlPathHelper; @@ -33,6 +32,7 @@ import static io.microsphere.spring.web.util.WebRequestUtils.getResolvedLookupPath; import static io.microsphere.spring.web.util.WebRequestUtils.isPreFlightRequest; +import static io.microsphere.util.ArrayUtils.isNotEmpty; import static org.springframework.util.StringUtils.hasLength; import static org.springframework.util.StringUtils.hasText; @@ -232,7 +232,7 @@ private static Set initPatterns(String[] patterns) { } private static boolean hasPattern(String[] patterns) { - if (!ObjectUtils.isEmpty(patterns)) { + if (isNotEmpty(patterns)) { for (String pattern : patterns) { if (hasText(pattern)) { return true; diff --git a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestProducesRule.java b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestProducesRule.java index 016523d8..a5022194 100644 --- a/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestProducesRule.java +++ b/microsphere-spring-web/src/main/java/io/microsphere/spring/web/rule/WebRequestProducesRule.java @@ -17,7 +17,6 @@ package io.microsphere.spring.web.rule; import org.springframework.http.MediaType; -import org.springframework.util.CollectionUtils; import org.springframework.web.HttpMediaTypeException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.accept.ContentNegotiationManager; @@ -30,6 +29,7 @@ import java.util.Collections; import java.util.List; +import static io.microsphere.collection.CollectionUtils.isNotEmpty; import static io.microsphere.spring.util.MimeTypeUtils.isPresentIn; import static io.microsphere.spring.web.rule.ProduceMediaTypeExpression.parseExpressions; import static io.microsphere.spring.web.util.WebRequestUtils.isPreFlightRequest; @@ -110,7 +110,7 @@ public boolean matches(NativeWebRequest request) { return false; } List result = getMatchingExpressions(acceptedMediaTypes); - if (!CollectionUtils.isEmpty(result)) { + if (isNotEmpty(result)) { return false; } else if (isPresentIn(MediaType.ALL, acceptedMediaTypes)) { return false; diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/config/ConfigurableContentNegotiationManagerWebMvcConfigurer.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/config/ConfigurableContentNegotiationManagerWebMvcConfigurer.java index 280f23de..7d47b8a9 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/config/ConfigurableContentNegotiationManagerWebMvcConfigurer.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/config/ConfigurableContentNegotiationManagerWebMvcConfigurer.java @@ -2,7 +2,6 @@ import org.springframework.beans.MutablePropertyValues; import org.springframework.http.MediaType; -import org.springframework.util.ReflectionUtils; import org.springframework.validation.DataBinder; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; @@ -11,7 +10,6 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.beans.PropertyEditorSupport; -import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.Map; @@ -44,37 +42,31 @@ public ConfigurableContentNegotiationManagerWebMvcConfigurer(Map public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - doWithFields(configurer.getClass(), new ReflectionUtils.FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + doWithFields(configurer.getClass(), field -> { - boolean accessible = field.isAccessible(); + boolean accessible = field.isAccessible(); - try { + try { - if (!accessible) { - field.setAccessible(true); - } - - ContentNegotiationManagerFactoryBean factoryBean = (ContentNegotiationManagerFactoryBean) field.get(configurer); + if (!accessible) { + field.setAccessible(true); + } - configureContentNegotiationManagerFactoryBean(factoryBean); + ContentNegotiationManagerFactoryBean factoryBean = (ContentNegotiationManagerFactoryBean) field.get(configurer); - } finally { + configureContentNegotiationManagerFactoryBean(factoryBean); - if (!accessible) { - field.setAccessible(accessible); - } + } finally { + if (!accessible) { + field.setAccessible(accessible); } } - }, new ReflectionUtils.FieldFilter() { - @Override - public boolean matches(Field field) { - Class fieldType = field.getType(); - return FACTORY_BEAN_FIELD_CLASS.isAssignableFrom(fieldType); - } + + }, field -> { + Class fieldType = field.getType(); + return FACTORY_BEAN_FIELD_CLASS.isAssignableFrom(fieldType); }); } @@ -135,9 +127,7 @@ private static Map extraProperties(Map map) { properties.put(key, value.toString()); } - } - } return properties; diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/AbstractPageRenderContextHandlerInterceptor.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/AbstractPageRenderContextHandlerInterceptor.java index 58a2f541..1510f5ef 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/AbstractPageRenderContextHandlerInterceptor.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/interceptor/AbstractPageRenderContextHandlerInterceptor.java @@ -1,6 +1,5 @@ package io.microsphere.spring.webmvc.interceptor; -import io.microsphere.spring.webmvc.util.WebMvcUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @@ -9,6 +8,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static io.microsphere.spring.webmvc.util.WebMvcUtils.isPageRenderRequest; + /** * Abstract Page Render Context {@link HandlerInterceptor} * @@ -22,17 +23,9 @@ public abstract class AbstractPageRenderContextHandlerInterceptor extends Handle public final void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { - - if (WebMvcUtils.isPageRenderRequest(modelAndView)) { - + if (isPageRenderRequest(modelAndView)) { postHandleOnPageRenderContext(request, response, handler, modelAndView); - - } else { - - super.postHandle(request, response, handler, modelAndView); - } - } /** diff --git a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/util/WebMvcUtils.java b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/util/WebMvcUtils.java index 15f750da..01177609 100644 --- a/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/util/WebMvcUtils.java +++ b/microsphere-spring-webmvc/src/main/java/io/microsphere/spring/webmvc/util/WebMvcUtils.java @@ -1,15 +1,11 @@ package io.microsphere.spring.webmvc.util; -import io.microsphere.spring.web.servlet.util.WebUtils; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.MethodParameter; -import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.context.ContextLoader; @@ -40,14 +36,20 @@ import java.util.List; import java.util.Set; +import static io.microsphere.spring.web.servlet.util.WebUtils.findServletRegistrations; +import static io.microsphere.util.ArrayUtils.isNotEmpty; import static io.microsphere.util.ClassLoaderUtils.isPresent; +import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import static org.springframework.util.Assert.notNull; import static org.springframework.util.ReflectionUtils.findMethod; import static org.springframework.util.ReflectionUtils.invokeMethod; +import static org.springframework.util.StringUtils.arrayToDelimitedString; import static org.springframework.util.StringUtils.hasLength; +import static org.springframework.util.StringUtils.hasText; import static org.springframework.web.context.ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM; import static org.springframework.web.context.ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM; import static org.springframework.web.context.support.WebApplicationContextUtils.getRequiredWebApplicationContext; +import static org.springframework.web.servlet.support.RequestContextUtils.findWebApplicationContext; /** * Spring Web MVC Utilities Class @@ -308,7 +310,7 @@ public static T getHandlerMethodReturnValue(Method method) { * @return If {@link ControllerAdvice} bean type is present , return true , or false. */ public static boolean isControllerAdviceBeanType(Class beanType) { - return AnnotationUtils.findAnnotation(beanType, ControllerAdvice.class) != null; + return findAnnotation(beanType, ControllerAdvice.class) != null; } /** @@ -340,7 +342,7 @@ public static WebApplicationContext getWebApplicationContext(HttpServletRequest if (webApplicationContext == null) { - webApplicationContext = RequestContextUtils.findWebApplicationContext(request, servletContext); + webApplicationContext = findWebApplicationContext(request, servletContext); } @@ -356,13 +358,13 @@ protected static String appendInitParameter(String existedParameterValue, String List parameterValuesList = new ArrayList(); - if (!ObjectUtils.isEmpty(existedParameterValues)) { + if (isNotEmpty(existedParameterValues)) { parameterValuesList.addAll(Arrays.asList(existedParameterValues)); } parameterValuesList.addAll(Arrays.asList(parameterValues)); - String newParameterValue = StringUtils.arrayToDelimitedString(parameterValuesList.toArray(), ","); + String newParameterValue = arrayToDelimitedString(parameterValuesList.toArray(), ","); return newParameterValue; } @@ -376,8 +378,8 @@ protected static String appendInitParameter(String existedParameterValue, String */ public static void appendInitParameters(ServletContext servletContext, String parameterName, String... parameterValues) { - notNull(servletContext); - notNull(parameterValues); + notNull(servletContext, "The argument 'servletContext' must not be null!"); + notNull(parameterValues, "The argument 'parameterValues' must not be null!"); String existedParameterValue = servletContext.getInitParameter(parameterName); @@ -435,7 +437,7 @@ public static void appendFrameworkServletContextInitializerClassInitParameter( Class contextInitializerClass) { Collection servletRegistrations = - WebUtils.findServletRegistrations(servletContext, FrameworkServlet.class).values(); + findServletRegistrations(servletContext, FrameworkServlet.class).values(); for (ServletRegistration servletRegistration : servletRegistrations) { String contextInitializerClassName = servletRegistration.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); @@ -452,17 +454,11 @@ public static void appendFrameworkServletContextInitializerClassInitParameter( * @return If current request is for page render , return true , or false. */ public static boolean isPageRenderRequest(ModelAndView modelAndView) { - if (modelAndView != null) { - String viewName = modelAndView.getViewName(); - - return StringUtils.hasText(viewName); - + return hasText(viewName); } - return false; - } private static String getHandlerMethodRequestBodyArgumentAttributeName(Method method) { diff --git a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/metadata/RequestMappingInfoWebEndpointMappingFactoryTest.java b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/metadata/RequestMappingInfoWebEndpointMappingFactoryTest.java index 755631c6..05716a49 100644 --- a/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/metadata/RequestMappingInfoWebEndpointMappingFactoryTest.java +++ b/microsphere-spring-webmvc/src/test/java/io/microsphere/spring/webmvc/metadata/RequestMappingInfoWebEndpointMappingFactoryTest.java @@ -24,7 +24,7 @@ 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 org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; @@ -44,7 +44,7 @@ * @author Mercy * @since 1.0.0 */ -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { TestController.class, From 6a19df7e7342ffab8e59104dcb042b787d509b1c Mon Sep 17 00:00:00 2001 From: Mercy Date: Fri, 10 Jan 2025 23:02:33 +0800 Subject: [PATCH 23/25] Polish #89 --- microsphere-spring-context/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/microsphere-spring-context/pom.xml b/microsphere-spring-context/pom.xml index b72e50c6..1a62de63 100644 --- a/microsphere-spring-context/pom.xml +++ b/microsphere-spring-context/pom.xml @@ -117,12 +117,6 @@ test - - io.lettuce - lettuce-core - test - - From 5d3dcb3c14aea57d561d1f4037907e7396e79bcd Mon Sep 17 00:00:00 2001 From: Mercy Date: Sat, 11 Jan 2025 19:41:15 +0800 Subject: [PATCH 24/25] Polish #80 --- microsphere-spring-webflux/pom.xml | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/microsphere-spring-webflux/pom.xml b/microsphere-spring-webflux/pom.xml index c5f8708a..8ded49d9 100644 --- a/microsphere-spring-webflux/pom.xml +++ b/microsphere-spring-webflux/pom.xml @@ -27,6 +27,13 @@ ${revision} + + + org.springframework + spring-context + true + + org.springframework @@ -34,19 +41,45 @@ true + + + com.fasterxml.jackson.core + jackson-annotations + true + + + + com.fasterxml.jackson.core + jackson-databind + true + + org.slf4j slf4j-api + true + + junit + junit + test + + org.springframework spring-test test + + ch.qos.logback + logback-classic + test + + From 39f8b8c61b9861f7ce6ae597491296ea703aa6b7 Mon Sep 17 00:00:00 2001 From: Mercy Date: Sat, 11 Jan 2025 20:16:25 +0800 Subject: [PATCH 25/25] Polish #88 --- .../microsphere/spring/core/annotation/AnnotationUtils.java | 3 +-- .../EnableConfigurationBeanBindingTestForMultipleBinding.java | 2 +- .../io/microsphere/spring/util/SpringVersionUtilsTest.java | 4 ++-- microsphere-spring-parent/pom.xml | 3 +-- microsphere-spring-web/pom.xml | 2 +- 5 files changed, 6 insertions(+), 8 deletions(-) diff --git a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java index 4638352f..d6d0f151 100644 --- a/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java +++ b/microsphere-spring-context/src/main/java/io/microsphere/spring/core/annotation/AnnotationUtils.java @@ -21,7 +21,6 @@ import java.util.Map; import java.util.Set; -import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; @@ -180,7 +179,7 @@ public static Map getAttributes(Map annotationAt } if (attributeValue instanceof String) { - attributeValue = resolvePlaceholders(valueOf(attributeValue), propertyResolver); + attributeValue = resolvePlaceholders((String) attributeValue, propertyResolver); } else if (attributeValue instanceof String[]) { String[] values = (String[]) attributeValue; for (int i = 0; i < values.length; i++) { diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java index 4e100dbd..4ce807ca 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/beans/factory/annotation/EnableConfigurationBeanBindingTestForMultipleBinding.java @@ -32,9 +32,9 @@ import java.util.Collection; import static io.microsphere.spring.beans.BeanUtils.getSortedBeans; -import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; @EnableConfigurationBeanBinding(prefix = "users", type = User.class, multiple = true, ignoreUnknownFields = false, ignoreInvalidFields = false) diff --git a/microsphere-spring-context/src/test/java/io/microsphere/spring/util/SpringVersionUtilsTest.java b/microsphere-spring-context/src/test/java/io/microsphere/spring/util/SpringVersionUtilsTest.java index a2d77810..45a6ea8c 100644 --- a/microsphere-spring-context/src/test/java/io/microsphere/spring/util/SpringVersionUtilsTest.java +++ b/microsphere-spring-context/src/test/java/io/microsphere/spring/util/SpringVersionUtilsTest.java @@ -50,8 +50,8 @@ public void testGetSpringVersionOnIAE() { @Test public void testGetSpringVersion() { Version version = getSpringVersion(StringUtils.class); - assertEquals(version,SPRING_AOP_VERSION); - assertEquals(SPRING_CORE_VERSION,SPRING_AOP_VERSION); + assertEquals(version, SPRING_AOP_VERSION); + assertEquals(SPRING_CORE_VERSION, SPRING_AOP_VERSION); assertEquals(SPRING_AOP_VERSION, SPRING_BEANS_VERSION); assertEquals(SPRING_BEANS_VERSION, SPRING_CONTEXT_VERSION); assertEquals(SPRING_CONTEXT_VERSION, SPRING_CONTEXT_SUPPORT_VERSION); diff --git a/microsphere-spring-parent/pom.xml b/microsphere-spring-parent/pom.xml index 540f57dc..54f440ba 100644 --- a/microsphere-spring-parent/pom.xml +++ b/microsphere-spring-parent/pom.xml @@ -63,7 +63,6 @@ javax.servlet javax.servlet-api ${servlet-api.version} - provided @@ -73,7 +72,7 @@ ${junit.version} - + org.mockito mockito-bom diff --git a/microsphere-spring-web/pom.xml b/microsphere-spring-web/pom.xml index a5d4b363..cbbace68 100644 --- a/microsphere-spring-web/pom.xml +++ b/microsphere-spring-web/pom.xml @@ -67,7 +67,7 @@ jackson-databind true - + org.slf4j