Browse Source

Use uppercase for classpath-related static final field names

Closes gh-35525
pull/35535/head
Sébastien Deleuze 4 months ago
parent
commit
7635ac38f6
  1. 4
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJAdvisorBeanRegistrationAotProcessor.java
  2. 4
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJBeanFactoryInitializationAotProcessor.java
  3. 4
      spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java
  4. 4
      spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java
  5. 4
      spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java
  6. 4
      spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java
  7. 12
      spring-context/src/main/java/org/springframework/cache/annotation/CachingConfigurationSelector.java
  8. 12
      spring-context/src/main/java/org/springframework/cache/config/AnnotationDrivenCacheBeanDefinitionParser.java
  9. 6
      spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
  10. 8
      spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java
  11. 28
      spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java
  12. 4
      spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java
  13. 6
      spring-context/src/main/java/org/springframework/format/support/DefaultFormattingConversionService.java
  14. 4
      spring-context/src/main/java/org/springframework/resilience/retry/AbstractRetryInterceptor.java
  15. 4
      spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java
  16. 10
      spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationReactiveSupport.java
  17. 4
      spring-context/src/main/java/org/springframework/validation/beanvalidation/BeanValidationBeanRegistrationAotProcessor.java
  18. 4
      spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java
  19. 2
      spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationReactiveSupportTests.java
  20. 4
      spring-context/src/test/kotlin/org/springframework/scheduling/annotation/KotlinScheduledAnnotationReactiveSupportTests.kt
  21. 4
      spring-core/src/main/java/org/springframework/aot/hint/BindingReflectionHintsRegistrar.java
  22. 32
      spring-core/src/main/java/org/springframework/core/KotlinDetector.java
  23. 34
      spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java
  24. 16
      spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java
  25. 6
      spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java
  26. 6
      spring-jms/src/main/java/org/springframework/jms/listener/AbstractMessageListenerContainer.java
  27. 4
      spring-messaging/src/main/java/org/springframework/messaging/converter/ProtobufMessageConverter.java
  28. 4
      spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java
  29. 30
      spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java
  30. 4
      spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceManagedTypesBeanRegistrationAotProcessor.java
  31. 4
      spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java
  32. 6
      spring-test/src/main/java/org/springframework/test/context/aot/MergedContextConfigurationRuntimeHints.java
  33. 10
      spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoResetTestExecutionListener.java
  34. 2
      spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanOverrideHandler.java
  35. 4
      spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/SpringMockResolver.java
  36. 4
      spring-test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java
  37. 4
      spring-test/src/main/java/org/springframework/test/context/web/WebDelegatingSmartContextLoader.java
  38. 4
      spring-test/src/main/java/org/springframework/test/context/web/socket/MockServerContainerContextCustomizerFactory.java
  39. 12
      spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java
  40. 24
      spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClientBuilder.java
  41. 10
      spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java
  42. 14
      spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java
  43. 10
      spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
  44. 4
      spring-tx/src/main/java/org/springframework/transaction/reactive/TransactionSynchronizationUtils.java
  45. 4
      spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationUtils.java
  46. 94
      spring-web/src/main/java/org/springframework/http/codec/support/BaseDefaultCodecs.java
  47. 6
      spring-web/src/main/java/org/springframework/http/codec/support/ClientDefaultCodecsImpl.java
  48. 6
      spring-web/src/main/java/org/springframework/http/codec/support/ServerDefaultCodecsImpl.java
  49. 4
      spring-web/src/main/java/org/springframework/http/codec/xml/XmlEventDecoder.java
  50. 102
      spring-web/src/main/java/org/springframework/http/converter/DefaultHttpMessageConverters.java
  51. 4
      spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java
  52. 5
      spring-web/src/main/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverter.java
  53. 24
      spring-web/src/main/java/org/springframework/web/client/DefaultRestClientBuilder.java
  54. 4
      spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java
  55. 4
      spring-web/src/main/java/org/springframework/web/context/support/StandardServletEnvironment.java
  56. 4
      spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java
  57. 4
      spring-webflux/src/main/java/org/springframework/web/reactive/config/ResourceChainRegistration.java
  58. 4
      spring-webflux/src/main/java/org/springframework/web/reactive/config/WebFluxConfigurationSupport.java
  59. 18
      spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientBuilder.java
  60. 18
      spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketService.java
  61. 100
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
  62. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java
  63. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java
  64. 24
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
  65. 2
      spring-webmvc/src/main/java/org/springframework/web/servlet/function/AsyncServerResponse.java
  66. 2
      spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java
  67. 2
      spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java
  68. 6
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java
  69. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java
  70. 6
      spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java
  71. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/view/InternalResourceViewResolver.java
  72. 30
      spring-websocket/src/main/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParser.java
  73. 4
      spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketNamespaceHandler.java
  74. 4
      spring-websocket/src/main/java/org/springframework/web/socket/server/support/DefaultHandshakeHandler.java
  75. 8
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java
  76. 8
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java

4
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJAdvisorBeanRegistrationAotProcessor.java

@ -39,13 +39,13 @@ class AspectJAdvisorBeanRegistrationAotProcessor implements BeanRegistrationAotP
private static final String AJC_MAGIC = "ajc$"; private static final String AJC_MAGIC = "ajc$";
private static final boolean aspectjPresent = ClassUtils.isPresent("org.aspectj.lang.annotation.Pointcut", private static final boolean ASPECTJ_PRESENT = ClassUtils.isPresent("org.aspectj.lang.annotation.Pointcut",
AspectJAdvisorBeanRegistrationAotProcessor.class.getClassLoader()); AspectJAdvisorBeanRegistrationAotProcessor.class.getClassLoader());
@Override @Override
public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
if (aspectjPresent) { if (ASPECTJ_PRESENT) {
Class<?> beanClass = registeredBean.getBeanClass(); Class<?> beanClass = registeredBean.getBeanClass();
if (compiledByAjc(beanClass)) { if (compiledByAjc(beanClass)) {
return new AspectJAdvisorContribution(beanClass); return new AspectJAdvisorContribution(beanClass);

4
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJBeanFactoryInitializationAotProcessor.java

@ -41,13 +41,13 @@ import org.springframework.util.ClassUtils;
*/ */
class AspectJBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor { class AspectJBeanFactoryInitializationAotProcessor implements BeanFactoryInitializationAotProcessor {
private static final boolean aspectJPresent = ClassUtils.isPresent("org.aspectj.lang.annotation.Pointcut", private static final boolean ASPECTJ_PRESENT = ClassUtils.isPresent("org.aspectj.lang.annotation.Pointcut",
AspectJBeanFactoryInitializationAotProcessor.class.getClassLoader()); AspectJBeanFactoryInitializationAotProcessor.class.getClassLoader());
@Override @Override
public @Nullable BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) { public @Nullable BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
if (aspectJPresent) { if (ASPECTJ_PRESENT) {
return AspectDelegate.processAheadOfTime(beanFactory); return AspectDelegate.processAheadOfTime(beanFactory);
} }
return null; return null;

4
spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java

@ -98,7 +98,7 @@ class CglibAopProxy implements AopProxy, Serializable {
private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow"; private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow";
private static final boolean coroutinesReactorPresent = ClassUtils.isPresent( private static final boolean COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent(
"kotlinx.coroutines.reactor.MonoKt", CglibAopProxy.class.getClassLoader()); "kotlinx.coroutines.reactor.MonoKt", CglibAopProxy.class.getClassLoader());
private static final GeneratorStrategy undeclaredThrowableStrategy = private static final GeneratorStrategy undeclaredThrowableStrategy =
@ -435,7 +435,7 @@ class CglibAopProxy implements AopProxy, Serializable {
throw new AopInvocationException( throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method); "Null return value from advice does not match primitive return type for: " + method);
} }
if (coroutinesReactorPresent && KotlinDetector.isSuspendingFunction(method)) { if (COROUTINES_REACTOR_PRESENT && KotlinDetector.isSuspendingFunction(method)) {
return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ? return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ?
CoroutinesUtils.asFlow(returnValue) : CoroutinesUtils.asFlow(returnValue) :
CoroutinesUtils.awaitSingleOrNull(returnValue, arguments[arguments.length - 1]); CoroutinesUtils.awaitSingleOrNull(returnValue, arguments[arguments.length - 1]);

4
spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java

@ -75,7 +75,7 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow"; private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow";
private static final boolean coroutinesReactorPresent = ClassUtils.isPresent( private static final boolean COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent(
"kotlinx.coroutines.reactor.MonoKt", JdkDynamicAopProxy.class.getClassLoader()); "kotlinx.coroutines.reactor.MonoKt", JdkDynamicAopProxy.class.getClassLoader());
/** We use a static Log to avoid serialization issues. */ /** We use a static Log to avoid serialization issues. */
@ -236,7 +236,7 @@ final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa
throw new AopInvocationException( throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method); "Null return value from advice does not match primitive return type for: " + method);
} }
if (coroutinesReactorPresent && KotlinDetector.isSuspendingFunction(method)) { if (COROUTINES_REACTOR_PRESENT && KotlinDetector.isSuspendingFunction(method)) {
return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ? return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ?
CoroutinesUtils.asFlow(retVal) : CoroutinesUtils.awaitSingleOrNull(retVal, args[args.length - 1]); CoroutinesUtils.asFlow(retVal) : CoroutinesUtils.awaitSingleOrNull(retVal, args[args.length - 1]);
} }

4
spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java

@ -66,7 +66,7 @@ import org.springframework.util.ReflectionUtils;
*/ */
public abstract class AopUtils { public abstract class AopUtils {
private static final boolean coroutinesReactorPresent = ClassUtils.isPresent( private static final boolean COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent(
"kotlinx.coroutines.reactor.MonoKt", AopUtils.class.getClassLoader()); "kotlinx.coroutines.reactor.MonoKt", AopUtils.class.getClassLoader());
@ -355,7 +355,7 @@ public abstract class AopUtils {
try { try {
Method originalMethod = BridgeMethodResolver.findBridgedMethod(method); Method originalMethod = BridgeMethodResolver.findBridgedMethod(method);
ReflectionUtils.makeAccessible(originalMethod); ReflectionUtils.makeAccessible(originalMethod);
return (coroutinesReactorPresent && KotlinDetector.isSuspendingFunction(originalMethod) ? return (COROUTINES_REACTOR_PRESENT && KotlinDetector.isSuspendingFunction(originalMethod) ?
KotlinDelegate.invokeSuspendingFunction(originalMethod, target, args) : originalMethod.invoke(target, args)); KotlinDelegate.invokeSuspendingFunction(originalMethod, target, args) : originalMethod.invoke(target, args));
} }
catch (InvocationTargetException ex) { catch (InvocationTargetException ex) {

4
spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java

@ -76,7 +76,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class); private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class);
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", DisposableBeanAdapter.class.getClassLoader()); "org.reactivestreams.Publisher", DisposableBeanAdapter.class.getClassLoader());
@ -320,7 +320,7 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
future.get(); future.get();
logDestroyMethodCompletion(destroyMethod, true); logDestroyMethodCompletion(destroyMethod, true);
} }
else if (!reactiveStreamsPresent || !new ReactiveDestroyMethodHandler().await(destroyMethod, returnValue)) { else if (!REACTIVE_STREAMS_PRESENT || !new ReactiveDestroyMethodHandler().await(destroyMethod, returnValue)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Unknown return value type from custom destroy method '" + destroyMethod.getName() + logger.debug("Unknown return value type from custom destroy method '" + destroyMethod.getName() +
"' on bean with name '" + this.beanName + "': " + returnValue.getClass()); "' on bean with name '" + this.beanName + "': " + returnValue.getClass());

12
spring-context/src/main/java/org/springframework/cache/annotation/CachingConfigurationSelector.java vendored

@ -50,14 +50,14 @@ public class CachingConfigurationSelector extends AdviceModeImportSelector<Enabl
"org.springframework.cache.aspectj.AspectJJCacheConfiguration"; "org.springframework.cache.aspectj.AspectJJCacheConfiguration";
private static final boolean jsr107Present; private static final boolean JSR_107_PRESENT;
private static final boolean jcacheImplPresent; private static final boolean JCACHE_IMPL_PRESENT;
static { static {
ClassLoader classLoader = CachingConfigurationSelector.class.getClassLoader(); ClassLoader classLoader = CachingConfigurationSelector.class.getClassLoader();
jsr107Present = ClassUtils.isPresent("javax.cache.Cache", classLoader); JSR_107_PRESENT = ClassUtils.isPresent("javax.cache.Cache", classLoader);
jcacheImplPresent = ClassUtils.isPresent(PROXY_JCACHE_CONFIGURATION_CLASS, classLoader); JCACHE_IMPL_PRESENT = ClassUtils.isPresent(PROXY_JCACHE_CONFIGURATION_CLASS, classLoader);
} }
@ -82,7 +82,7 @@ public class CachingConfigurationSelector extends AdviceModeImportSelector<Enabl
List<String> result = new ArrayList<>(3); List<String> result = new ArrayList<>(3);
result.add(AutoProxyRegistrar.class.getName()); result.add(AutoProxyRegistrar.class.getName());
result.add(ProxyCachingConfiguration.class.getName()); result.add(ProxyCachingConfiguration.class.getName());
if (jsr107Present && jcacheImplPresent) { if (JSR_107_PRESENT && JCACHE_IMPL_PRESENT) {
result.add(PROXY_JCACHE_CONFIGURATION_CLASS); result.add(PROXY_JCACHE_CONFIGURATION_CLASS);
} }
return StringUtils.toStringArray(result); return StringUtils.toStringArray(result);
@ -95,7 +95,7 @@ public class CachingConfigurationSelector extends AdviceModeImportSelector<Enabl
private String[] getAspectJImports() { private String[] getAspectJImports() {
List<String> result = new ArrayList<>(2); List<String> result = new ArrayList<>(2);
result.add(CACHE_ASPECT_CONFIGURATION_CLASS_NAME); result.add(CACHE_ASPECT_CONFIGURATION_CLASS_NAME);
if (jsr107Present && jcacheImplPresent) { if (JSR_107_PRESENT && JCACHE_IMPL_PRESENT) {
result.add(JCACHE_ASPECT_CONFIGURATION_CLASS_NAME); result.add(JCACHE_ASPECT_CONFIGURATION_CLASS_NAME);
} }
return StringUtils.toStringArray(result); return StringUtils.toStringArray(result);

12
spring-context/src/main/java/org/springframework/cache/config/AnnotationDrivenCacheBeanDefinitionParser.java vendored

@ -61,14 +61,14 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
private static final String JCACHE_ASPECT_CLASS_NAME = private static final String JCACHE_ASPECT_CLASS_NAME =
"org.springframework.cache.aspectj.JCacheCacheAspect"; "org.springframework.cache.aspectj.JCacheCacheAspect";
private static final boolean jsr107Present; private static final boolean JSR_107_PRESENT;
private static final boolean jcacheImplPresent; private static final boolean JCACHE_IMPL_PRESENT;
static { static {
ClassLoader classLoader = AnnotationDrivenCacheBeanDefinitionParser.class.getClassLoader(); ClassLoader classLoader = AnnotationDrivenCacheBeanDefinitionParser.class.getClassLoader();
jsr107Present = ClassUtils.isPresent("javax.cache.Cache", classLoader); JSR_107_PRESENT = ClassUtils.isPresent("javax.cache.Cache", classLoader);
jcacheImplPresent = ClassUtils.isPresent( JCACHE_IMPL_PRESENT = ClassUtils.isPresent(
"org.springframework.cache.jcache.interceptor.DefaultJCacheOperationSource", classLoader); "org.springframework.cache.jcache.interceptor.DefaultJCacheOperationSource", classLoader);
} }
@ -95,7 +95,7 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
private void registerCacheAspect(Element element, ParserContext parserContext) { private void registerCacheAspect(Element element, ParserContext parserContext) {
SpringCachingConfigurer.registerCacheAspect(element, parserContext); SpringCachingConfigurer.registerCacheAspect(element, parserContext);
if (jsr107Present && jcacheImplPresent) { if (JSR_107_PRESENT && JCACHE_IMPL_PRESENT) {
JCacheCachingConfigurer.registerCacheAspect(element, parserContext); JCacheCachingConfigurer.registerCacheAspect(element, parserContext);
} }
} }
@ -103,7 +103,7 @@ class AnnotationDrivenCacheBeanDefinitionParser implements BeanDefinitionParser
private void registerCacheAdvisor(Element element, ParserContext parserContext) { private void registerCacheAdvisor(Element element, ParserContext parserContext) {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element); AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
SpringCachingConfigurer.registerCacheAdvisor(element, parserContext); SpringCachingConfigurer.registerCacheAdvisor(element, parserContext);
if (jsr107Present && jcacheImplPresent) { if (JSR_107_PRESENT && JCACHE_IMPL_PRESENT) {
JCacheCachingConfigurer.registerCacheAdvisor(element, parserContext); JCacheCachingConfigurer.registerCacheAdvisor(element, parserContext);
} }
} }

6
spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java vendored

@ -114,10 +114,10 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
*/ */
public static final String IGNORE_REACTIVESTREAMS_PROPERTY_NAME = "spring.cache.reactivestreams.ignore"; public static final String IGNORE_REACTIVESTREAMS_PROPERTY_NAME = "spring.cache.reactivestreams.ignore";
private static final boolean shouldIgnoreReactiveStreams = private static final boolean SHOULD_IGNORE_REACTIVE_STREAMS =
SpringProperties.getFlag(IGNORE_REACTIVESTREAMS_PROPERTY_NAME); SpringProperties.getFlag(IGNORE_REACTIVESTREAMS_PROPERTY_NAME);
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", CacheAspectSupport.class.getClassLoader()); "org.reactivestreams.Publisher", CacheAspectSupport.class.getClassLoader());
@ -145,7 +145,7 @@ public abstract class CacheAspectSupport extends AbstractCacheInvoker
protected CacheAspectSupport() { protected CacheAspectSupport() {
this.reactiveCachingHandler = this.reactiveCachingHandler =
(reactiveStreamsPresent && !shouldIgnoreReactiveStreams ? new ReactiveCachingHandler() : null); (REACTIVE_STREAMS_PRESENT && !SHOULD_IGNORE_REACTIVE_STREAMS ? new ReactiveCachingHandler() : null);
} }

8
spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java

@ -116,10 +116,10 @@ public abstract class AnnotationConfigUtils {
private static final ClassLoader classLoader = AnnotationConfigUtils.class.getClassLoader(); private static final ClassLoader classLoader = AnnotationConfigUtils.class.getClassLoader();
private static final boolean jakartaAnnotationsPresent = private static final boolean JAKARTA_ANNOTATIONS_PRESENT =
ClassUtils.isPresent("jakarta.annotation.PostConstruct", classLoader); ClassUtils.isPresent("jakarta.annotation.PostConstruct", classLoader);
private static final boolean jpaPresent = private static final boolean JPA_PRESENT =
ClassUtils.isPresent("jakarta.persistence.EntityManagerFactory", classLoader) && ClassUtils.isPresent("jakarta.persistence.EntityManagerFactory", classLoader) &&
ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, classLoader); ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, classLoader);
@ -168,14 +168,14 @@ public abstract class AnnotationConfigUtils {
} }
// Check for Jakarta Annotations support, and if present add the CommonAnnotationBeanPostProcessor. // Check for Jakarta Annotations support, and if present add the CommonAnnotationBeanPostProcessor.
if (jakartaAnnotationsPresent && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { if (JAKARTA_ANNOTATIONS_PRESENT && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source); def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
} }
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { if (JPA_PRESENT && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(); RootBeanDefinition def = new RootBeanDefinition();
try { try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,

28
spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java

@ -142,24 +142,24 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable { implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
// Defensive reference to JNDI API for JDK 9+ (optional java.naming module) // Defensive reference to JNDI API for JDK 9+ (optional java.naming module)
private static final boolean jndiPresent = ClassUtils.isPresent( private static final boolean JNDI_PRESENT = ClassUtils.isPresent(
"javax.naming.InitialContext", CommonAnnotationBeanPostProcessor.class.getClassLoader()); "javax.naming.InitialContext", CommonAnnotationBeanPostProcessor.class.getClassLoader());
private static final Set<Class<? extends Annotation>> resourceAnnotationTypes = CollectionUtils.newLinkedHashSet(3); private static final Set<Class<? extends Annotation>> resourceAnnotationTypes = CollectionUtils.newLinkedHashSet(3);
private static final @Nullable Class<? extends Annotation> jakartaResourceType; private static final @Nullable Class<? extends Annotation> JAKARTA_RESOURCE_TYPE;
private static final @Nullable Class<? extends Annotation> ejbAnnotationType; private static final @Nullable Class<? extends Annotation> EJB_ANNOTATION_TYPE;
static { static {
jakartaResourceType = loadAnnotationType("jakarta.annotation.Resource"); JAKARTA_RESOURCE_TYPE = loadAnnotationType("jakarta.annotation.Resource");
if (jakartaResourceType != null) { if (JAKARTA_RESOURCE_TYPE != null) {
resourceAnnotationTypes.add(jakartaResourceType); resourceAnnotationTypes.add(JAKARTA_RESOURCE_TYPE);
} }
ejbAnnotationType = loadAnnotationType("jakarta.ejb.EJB"); EJB_ANNOTATION_TYPE = loadAnnotationType("jakarta.ejb.EJB");
if (ejbAnnotationType != null) { if (EJB_ANNOTATION_TYPE != null) {
resourceAnnotationTypes.add(ejbAnnotationType); resourceAnnotationTypes.add(EJB_ANNOTATION_TYPE);
} }
} }
@ -195,7 +195,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
addDestroyAnnotationType(loadAnnotationType("jakarta.annotation.PreDestroy")); addDestroyAnnotationType(loadAnnotationType("jakarta.annotation.PreDestroy"));
// java.naming module present on JDK 9+? // java.naming module present on JDK 9+?
if (jndiPresent) { if (JNDI_PRESENT) {
this.jndiFactory = new SimpleJndiBeanFactory(); this.jndiFactory = new SimpleJndiBeanFactory();
} }
} }
@ -405,13 +405,13 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>(); final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
ReflectionUtils.doWithLocalFields(targetClass, field -> { ReflectionUtils.doWithLocalFields(targetClass, field -> {
if (ejbAnnotationType != null && field.isAnnotationPresent(ejbAnnotationType)) { if (EJB_ANNOTATION_TYPE != null && field.isAnnotationPresent(EJB_ANNOTATION_TYPE)) {
if (Modifier.isStatic(field.getModifiers())) { if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static fields"); throw new IllegalStateException("@EJB annotation is not supported on static fields");
} }
currElements.add(new EjbRefElement(field, field, null)); currElements.add(new EjbRefElement(field, field, null));
} }
else if (jakartaResourceType != null && field.isAnnotationPresent(jakartaResourceType)) { else if (JAKARTA_RESOURCE_TYPE != null && field.isAnnotationPresent(JAKARTA_RESOURCE_TYPE)) {
if (Modifier.isStatic(field.getModifiers())) { if (Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static fields"); throw new IllegalStateException("@Resource annotation is not supported on static fields");
} }
@ -426,7 +426,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return; return;
} }
if (ejbAnnotationType != null && bridgedMethod.isAnnotationPresent(ejbAnnotationType)) { if (EJB_ANNOTATION_TYPE != null && bridgedMethod.isAnnotationPresent(EJB_ANNOTATION_TYPE)) {
if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) { if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@EJB annotation is not supported on static methods"); throw new IllegalStateException("@EJB annotation is not supported on static methods");
@ -438,7 +438,7 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean
currElements.add(new EjbRefElement(method, bridgedMethod, pd)); currElements.add(new EjbRefElement(method, bridgedMethod, pd));
} }
} }
else if (jakartaResourceType != null && bridgedMethod.isAnnotationPresent(jakartaResourceType)) { else if (JAKARTA_RESOURCE_TYPE != null && bridgedMethod.isAnnotationPresent(JAKARTA_RESOURCE_TYPE)) {
if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) { if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalStateException("@Resource annotation is not supported on static methods"); throw new IllegalStateException("@Resource annotation is not supported on static methods");

4
spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java

@ -74,7 +74,7 @@ import org.springframework.util.StringUtils;
*/ */
public class ApplicationListenerMethodAdapter implements GenericApplicationListener { public class ApplicationListenerMethodAdapter implements GenericApplicationListener {
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", ApplicationListenerMethodAdapter.class.getClassLoader()); "org.reactivestreams.Publisher", ApplicationListenerMethodAdapter.class.getClassLoader());
@ -309,7 +309,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
} }
protected void handleResult(Object result) { protected void handleResult(Object result) {
if (reactiveStreamsPresent && new ReactiveResultHandler().subscribeToPublisher(result)) { if (REACTIVE_STREAMS_PRESENT && new ReactiveResultHandler().subscribeToPublisher(result)) {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Adapted to reactive result: " + result); logger.trace("Adapted to reactive result: " + result);
} }

6
spring-context/src/main/java/org/springframework/format/support/DefaultFormattingConversionService.java

@ -47,11 +47,11 @@ import org.springframework.util.StringValueResolver;
*/ */
public class DefaultFormattingConversionService extends FormattingConversionService { public class DefaultFormattingConversionService extends FormattingConversionService {
private static final boolean jsr354Present; private static final boolean JSR_354_PRESENT;
static { static {
ClassLoader classLoader = DefaultFormattingConversionService.class.getClassLoader(); ClassLoader classLoader = DefaultFormattingConversionService.class.getClassLoader();
jsr354Present = ClassUtils.isPresent("javax.money.MonetaryAmount", classLoader); JSR_354_PRESENT = ClassUtils.isPresent("javax.money.MonetaryAmount", classLoader);
} }
/** /**
@ -107,7 +107,7 @@ public class DefaultFormattingConversionService extends FormattingConversionServ
formatterRegistry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); formatterRegistry.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());
// Default handling of monetary values // Default handling of monetary values
if (jsr354Present) { if (JSR_354_PRESENT) {
formatterRegistry.addFormatter(new CurrencyUnitFormatter()); formatterRegistry.addFormatter(new CurrencyUnitFormatter());
formatterRegistry.addFormatter(new MonetaryAmountFormatter()); formatterRegistry.addFormatter(new MonetaryAmountFormatter());
formatterRegistry.addFormatterForFieldAnnotation(new Jsr354NumberFormatAnnotationFormatterFactory()); formatterRegistry.addFormatterForFieldAnnotation(new Jsr354NumberFormatAnnotationFormatterFactory());

4
spring-context/src/main/java/org/springframework/resilience/retry/AbstractRetryInterceptor.java

@ -51,14 +51,14 @@ public abstract class AbstractRetryInterceptor implements MethodInterceptor {
/** /**
* Reactive Streams API present on the classpath? * Reactive Streams API present on the classpath?
*/ */
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", AbstractRetryInterceptor.class.getClassLoader()); "org.reactivestreams.Publisher", AbstractRetryInterceptor.class.getClassLoader());
private final @Nullable ReactiveAdapterRegistry reactiveAdapterRegistry; private final @Nullable ReactiveAdapterRegistry reactiveAdapterRegistry;
public AbstractRetryInterceptor() { public AbstractRetryInterceptor() {
if (reactiveStreamsPresent) { if (REACTIVE_STREAMS_PRESENT) {
this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
} }
else { else {

4
spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java

@ -127,7 +127,7 @@ public class ScheduledAnnotationBeanPostProcessor
/** /**
* Reactive Streams API present on the classpath? * Reactive Streams API present on the classpath?
*/ */
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", ScheduledAnnotationBeanPostProcessor.class.getClassLoader()); "org.reactivestreams.Publisher", ScheduledAnnotationBeanPostProcessor.class.getClassLoader());
protected final Log logger = LogFactory.getLog(getClass()); protected final Log logger = LogFactory.getLog(getClass());
@ -330,7 +330,7 @@ public class ScheduledAnnotationBeanPostProcessor
protected void processScheduled(Scheduled scheduled, Method method, Object bean) { protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
// Is the method a Kotlin suspending function? Throws if true and the reactor bridge isn't on the classpath. // Is the method a Kotlin suspending function? Throws if true and the reactor bridge isn't on the classpath.
// Does the method return a reactive type? Throws if true and it isn't a deferred Publisher type. // Does the method return a reactive type? Throws if true and it isn't a deferred Publisher type.
if (reactiveStreamsPresent && ScheduledAnnotationReactiveSupport.isReactive(method)) { if (REACTIVE_STREAMS_PRESENT && ScheduledAnnotationReactiveSupport.isReactive(method)) {
processScheduledAsync(scheduled, method, bean); processScheduledAsync(scheduled, method, bean);
return; return;
} }

10
spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationReactiveSupport.java

@ -60,10 +60,10 @@ import static org.springframework.scheduling.support.ScheduledTaskObservationDoc
*/ */
abstract class ScheduledAnnotationReactiveSupport { abstract class ScheduledAnnotationReactiveSupport {
static final boolean reactorPresent = ClassUtils.isPresent( static final boolean REACTOR_PRESENT = ClassUtils.isPresent(
"reactor.core.publisher.Flux", ScheduledAnnotationReactiveSupport.class.getClassLoader()); "reactor.core.publisher.Flux", ScheduledAnnotationReactiveSupport.class.getClassLoader());
static final boolean coroutinesReactorPresent = ClassUtils.isPresent( static final boolean COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent(
"kotlinx.coroutines.reactor.MonoKt", ScheduledAnnotationReactiveSupport.class.getClassLoader()); "kotlinx.coroutines.reactor.MonoKt", ScheduledAnnotationReactiveSupport.class.getClassLoader());
private static final Log logger = LogFactory.getLog(ScheduledAnnotationReactiveSupport.class); private static final Log logger = LogFactory.getLog(ScheduledAnnotationReactiveSupport.class);
@ -87,7 +87,7 @@ abstract class ScheduledAnnotationReactiveSupport {
// parameter in reflective inspection // parameter in reflective inspection
Assert.isTrue(method.getParameterCount() == 1, Assert.isTrue(method.getParameterCount() == 1,
"Kotlin suspending functions may only be annotated with @Scheduled if declared without arguments"); "Kotlin suspending functions may only be annotated with @Scheduled if declared without arguments");
Assert.isTrue(coroutinesReactorPresent, "Kotlin suspending functions may only be annotated with " + Assert.isTrue(COROUTINES_REACTOR_PRESENT, "Kotlin suspending functions may only be annotated with " +
"@Scheduled if the Coroutine-Reactor bridge (kotlinx.coroutines.reactor) is present at runtime"); "@Scheduled if the Coroutine-Reactor bridge (kotlinx.coroutines.reactor) is present at runtime");
return true; return true;
} }
@ -161,7 +161,7 @@ abstract class ScheduledAnnotationReactiveSupport {
Publisher<?> publisher = adapter.toPublisher(returnValue); Publisher<?> publisher = adapter.toPublisher(returnValue);
// If Reactor is on the classpath, we could benefit from having a checkpoint for debuggability // If Reactor is on the classpath, we could benefit from having a checkpoint for debuggability
if (reactorPresent) { if (REACTOR_PRESENT) {
return Flux.from(publisher).checkpoint( return Flux.from(publisher).checkpoint(
"@Scheduled '"+ method.getName() + "()' in '" + method.getDeclaringClass().getName() + "'"); "@Scheduled '"+ method.getName() + "()' in '" + method.getDeclaringClass().getName() + "'");
} }
@ -246,7 +246,7 @@ abstract class ScheduledAnnotationReactiveSupport {
private void subscribe(TrackingSubscriber subscriber, Observation observation) { private void subscribe(TrackingSubscriber subscriber, Observation observation) {
this.subscriptionTrackerRegistry.add(subscriber); this.subscriptionTrackerRegistry.add(subscriber);
if (reactorPresent) { if (REACTOR_PRESENT) {
observation.start(); observation.start();
Flux.from(this.publisher) Flux.from(this.publisher)
.contextWrite(context -> context.put(ObservationThreadLocalAccessor.KEY, observation)) .contextWrite(context -> context.put(ObservationThreadLocalAccessor.KEY, observation))

4
spring-context/src/main/java/org/springframework/validation/beanvalidation/BeanValidationBeanRegistrationAotProcessor.java

@ -61,7 +61,7 @@ import org.springframework.util.ReflectionUtils;
*/ */
class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor { class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor {
private static final boolean beanValidationPresent = ClassUtils.isPresent( private static final boolean BEAN_VALIDATION_PRESENT = ClassUtils.isPresent(
"jakarta.validation.Validation", BeanValidationBeanRegistrationAotProcessor.class.getClassLoader()); "jakarta.validation.Validation", BeanValidationBeanRegistrationAotProcessor.class.getClassLoader());
private static final Log logger = LogFactory.getLog(BeanValidationBeanRegistrationAotProcessor.class); private static final Log logger = LogFactory.getLog(BeanValidationBeanRegistrationAotProcessor.class);
@ -69,7 +69,7 @@ class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotP
@Override @Override
public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
if (beanValidationPresent) { if (BEAN_VALIDATION_PRESENT) {
return BeanValidationDelegate.processAheadOfTime(registeredBean); return BeanValidationDelegate.processAheadOfTime(registeredBean);
} }
return null; return null;

4
spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java

@ -79,7 +79,7 @@ import org.springframework.validation.method.ParameterValidationResult;
*/ */
public class MethodValidationInterceptor implements MethodInterceptor { public class MethodValidationInterceptor implements MethodInterceptor {
private static final boolean reactorPresent = ClassUtils.isPresent( private static final boolean REACTOR_PRESENT = ClassUtils.isPresent(
"reactor.core.publisher.Mono", MethodValidationInterceptor.class.getClassLoader()); "reactor.core.publisher.Mono", MethodValidationInterceptor.class.getClassLoader());
@ -152,7 +152,7 @@ public class MethodValidationInterceptor implements MethodInterceptor {
@Nullable Object[] arguments = invocation.getArguments(); @Nullable Object[] arguments = invocation.getArguments();
Class<?>[] groups = determineValidationGroups(invocation); Class<?>[] groups = determineValidationGroups(invocation);
if (reactorPresent) { if (REACTOR_PRESENT) {
arguments = ReactorValidationHelper.insertAsyncValidation( arguments = ReactorValidationHelper.insertAsyncValidation(
this.validationAdapter.getSpringValidatorAdapter(), this.adaptViolations, this.validationAdapter.getSpringValidatorAdapter(), this.adaptViolations,
target, method, arguments); target, method, arguments);

2
spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationReactiveSupportTests.java

@ -50,7 +50,7 @@ class ScheduledAnnotationReactiveSupportTests {
@Test @Test
void ensureReactor() { void ensureReactor() {
assertThat(ScheduledAnnotationReactiveSupport.reactorPresent).isTrue(); assertThat(ScheduledAnnotationReactiveSupport.REACTOR_PRESENT).isTrue();
} }
@ParameterizedTest @ParameterizedTest

4
spring-context/src/test/kotlin/org/springframework/scheduling/annotation/KotlinScheduledAnnotationReactiveSupportTests.kt

@ -43,12 +43,12 @@ class KotlinScheduledAnnotationReactiveSupportTests {
@Test @Test
fun ensureReactor() { fun ensureReactor() {
assertThat(ScheduledAnnotationReactiveSupport.reactorPresent).isTrue assertThat(ScheduledAnnotationReactiveSupport.REACTOR_PRESENT).isTrue
} }
@Test @Test
fun ensureKotlinCoroutineReactorBridge() { fun ensureKotlinCoroutineReactorBridge() {
assertThat(ScheduledAnnotationReactiveSupport.coroutinesReactorPresent).isTrue assertThat(ScheduledAnnotationReactiveSupport.COROUTINES_REACTOR_PRESENT).isTrue
} }
@ParameterizedTest @ParameterizedTest

4
spring-core/src/main/java/org/springframework/aot/hint/BindingReflectionHintsRegistrar.java

@ -55,7 +55,7 @@ public class BindingReflectionHintsRegistrar {
private static final String JACKSON_ANNOTATION = "com.fasterxml.jackson.annotation.JacksonAnnotation"; private static final String JACKSON_ANNOTATION = "com.fasterxml.jackson.annotation.JacksonAnnotation";
private static final boolean jacksonAnnotationPresent = private static final boolean JACKSON_ANNOTATION_PRESENT =
ClassUtils.isPresent(JACKSON_ANNOTATION, BindingReflectionHintsRegistrar.class.getClassLoader()); ClassUtils.isPresent(JACKSON_ANNOTATION, BindingReflectionHintsRegistrar.class.getClassLoader());
@ -113,7 +113,7 @@ public class BindingReflectionHintsRegistrar {
registerPropertyHints(hints, seen, method, -1); registerPropertyHints(hints, seen, method, -1);
} }
} }
if (jacksonAnnotationPresent) { if (JACKSON_ANNOTATION_PRESENT) {
registerJacksonHints(hints, clazz); registerJacksonHints(hints, clazz);
} }
} }

32
spring-core/src/main/java/org/springframework/core/KotlinDetector.java

@ -34,16 +34,16 @@ import org.springframework.util.ClassUtils;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public abstract class KotlinDetector { public abstract class KotlinDetector {
private static final @Nullable Class<? extends Annotation> kotlinMetadata; private static final @Nullable Class<? extends Annotation> KOTLIN_METADATA;
private static final @Nullable Class<? extends Annotation> kotlinJvmInline; private static final @Nullable Class<? extends Annotation> KOTLIN_JVM_INLINE;
private static final @Nullable Class<?> kotlinCoroutineContinuation; private static final @Nullable Class<?> KOTLIN_COROUTINE_CONTINUATION;
// For ConstantFieldFeature compliance, otherwise could be deduced from kotlinMetadata // For ConstantFieldFeature compliance, otherwise could be deduced from kotlinMetadata
private static final boolean kotlinPresent; private static final boolean KOTLIN_PRESENT;
private static final boolean kotlinReflectPresent; private static final boolean KOTLIN_REFLECT_PRESENT;
static { static {
ClassLoader classLoader = KotlinDetector.class.getClassLoader(); ClassLoader classLoader = KotlinDetector.class.getClassLoader();
@ -68,11 +68,11 @@ public abstract class KotlinDetector {
catch (ClassNotFoundException ex) { catch (ClassNotFoundException ex) {
// Kotlin API not available - no Kotlin support // Kotlin API not available - no Kotlin support
} }
kotlinMetadata = (Class<? extends Annotation>) metadata; KOTLIN_METADATA = (Class<? extends Annotation>) metadata;
kotlinPresent = (kotlinMetadata != null); KOTLIN_PRESENT = (KOTLIN_METADATA != null);
kotlinReflectPresent = ClassUtils.isPresent("kotlin.reflect.full.KClasses", classLoader); KOTLIN_REFLECT_PRESENT = ClassUtils.isPresent("kotlin.reflect.full.KClasses", classLoader);
kotlinJvmInline = (Class<? extends Annotation>) jvmInline; KOTLIN_JVM_INLINE = (Class<? extends Annotation>) jvmInline;
kotlinCoroutineContinuation = coroutineContinuation; KOTLIN_COROUTINE_CONTINUATION = coroutineContinuation;
} }
@ -80,7 +80,7 @@ public abstract class KotlinDetector {
* Determine whether Kotlin is present in general. * Determine whether Kotlin is present in general.
*/ */
public static boolean isKotlinPresent() { public static boolean isKotlinPresent() {
return kotlinPresent; return KOTLIN_PRESENT;
} }
/** /**
@ -88,7 +88,7 @@ public abstract class KotlinDetector {
* @since 5.1 * @since 5.1
*/ */
public static boolean isKotlinReflectPresent() { public static boolean isKotlinReflectPresent() {
return kotlinReflectPresent; return KOTLIN_REFLECT_PRESENT;
} }
/** /**
@ -100,7 +100,7 @@ public abstract class KotlinDetector {
* as invokedynamic has become the default method for lambda generation. * as invokedynamic has become the default method for lambda generation.
*/ */
public static boolean isKotlinType(Class<?> clazz) { public static boolean isKotlinType(Class<?> clazz) {
return (kotlinPresent && clazz.getDeclaredAnnotation(kotlinMetadata) != null); return (KOTLIN_PRESENT && clazz.getDeclaredAnnotation(KOTLIN_METADATA) != null);
} }
/** /**
@ -108,11 +108,11 @@ public abstract class KotlinDetector {
* @since 5.3 * @since 5.3
*/ */
public static boolean isSuspendingFunction(Method method) { public static boolean isSuspendingFunction(Method method) {
if (kotlinCoroutineContinuation == null) { if (KOTLIN_COROUTINE_CONTINUATION == null) {
return false; return false;
} }
int parameterCount = method.getParameterCount(); int parameterCount = method.getParameterCount();
return (parameterCount > 0 && method.getParameterTypes()[parameterCount - 1] == kotlinCoroutineContinuation); return (parameterCount > 0 && method.getParameterTypes()[parameterCount - 1] == KOTLIN_COROUTINE_CONTINUATION);
} }
/** /**
@ -122,7 +122,7 @@ public abstract class KotlinDetector {
* @see <a href="https://kotlinlang.org/docs/inline-classes.html">Kotlin inline value classes</a> * @see <a href="https://kotlinlang.org/docs/inline-classes.html">Kotlin inline value classes</a>
*/ */
public static boolean isInlineClass(Class<?> clazz) { public static boolean isInlineClass(Class<?> clazz) {
return (kotlinJvmInline != null && clazz.getDeclaredAnnotation(kotlinJvmInline) != null); return (KOTLIN_JVM_INLINE != null && clazz.getDeclaredAnnotation(KOTLIN_JVM_INLINE) != null);
} }
} }

34
spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java

@ -61,23 +61,23 @@ public class ReactiveAdapterRegistry {
private static volatile @Nullable ReactiveAdapterRegistry sharedInstance; private static volatile @Nullable ReactiveAdapterRegistry sharedInstance;
private static final boolean reactiveStreamsPresent; private static final boolean REACTIVE_STREAMS_PRESENT;
private static final boolean reactorPresent; private static final boolean REACTOR_PRESENT;
private static final boolean rxjava3Present; private static final boolean RXJAVA_3_PRESENT;
private static final boolean kotlinCoroutinesPresent; private static final boolean COROUTINES_REACTOR_PRESENT;
private static final boolean mutinyPresent; private static final boolean MUTINY_PRESENT;
static { static {
ClassLoader classLoader = ReactiveAdapterRegistry.class.getClassLoader(); ClassLoader classLoader = ReactiveAdapterRegistry.class.getClassLoader();
reactiveStreamsPresent = ClassUtils.isPresent("org.reactivestreams.Publisher", classLoader); REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent("org.reactivestreams.Publisher", classLoader);
reactorPresent = ClassUtils.isPresent("reactor.core.publisher.Flux", classLoader); REACTOR_PRESENT = ClassUtils.isPresent("reactor.core.publisher.Flux", classLoader);
rxjava3Present = ClassUtils.isPresent("io.reactivex.rxjava3.core.Flowable", classLoader); RXJAVA_3_PRESENT = ClassUtils.isPresent("io.reactivex.rxjava3.core.Flowable", classLoader);
kotlinCoroutinesPresent = ClassUtils.isPresent("kotlinx.coroutines.reactor.MonoKt", classLoader); COROUTINES_REACTOR_PRESENT = ClassUtils.isPresent("kotlinx.coroutines.reactor.MonoKt", classLoader);
mutinyPresent = ClassUtils.isPresent("io.smallrye.mutiny.Multi", classLoader); MUTINY_PRESENT = ClassUtils.isPresent("io.smallrye.mutiny.Multi", classLoader);
} }
private final List<ReactiveAdapter> adapters = new ArrayList<>(); private final List<ReactiveAdapter> adapters = new ArrayList<>();
@ -89,32 +89,32 @@ public class ReactiveAdapterRegistry {
*/ */
public ReactiveAdapterRegistry() { public ReactiveAdapterRegistry() {
// Defensive guard for the Reactive Streams API itself // Defensive guard for the Reactive Streams API itself
if (!reactiveStreamsPresent) { if (!REACTIVE_STREAMS_PRESENT) {
return; return;
} }
// Reactor // Reactor
if (reactorPresent) { if (REACTOR_PRESENT) {
new ReactorRegistrar().registerAdapters(this); new ReactorRegistrar().registerAdapters(this);
} }
// RxJava // RxJava
if (rxjava3Present) { if (RXJAVA_3_PRESENT) {
new RxJava3Registrar().registerAdapters(this); new RxJava3Registrar().registerAdapters(this);
} }
// Kotlin Coroutines // Kotlin Coroutines
if (reactorPresent && kotlinCoroutinesPresent) { if (REACTOR_PRESENT && COROUTINES_REACTOR_PRESENT) {
new CoroutinesRegistrar().registerAdapters(this); new CoroutinesRegistrar().registerAdapters(this);
} }
// SmallRye Mutiny // SmallRye Mutiny
if (mutinyPresent) { if (MUTINY_PRESENT) {
new MutinyRegistrar().registerAdapters(this); new MutinyRegistrar().registerAdapters(this);
} }
// Simple Flow.Publisher bridge if Reactor is not present // Simple Flow.Publisher bridge if Reactor is not present
if (!reactorPresent) { if (!REACTOR_PRESENT) {
new FlowAdaptersRegistrar().registerAdapters(this); new FlowAdaptersRegistrar().registerAdapters(this);
} }
} }
@ -161,7 +161,7 @@ public class ReactiveAdapterRegistry {
private ReactiveAdapter buildAdapter(ReactiveTypeDescriptor descriptor, private ReactiveAdapter buildAdapter(ReactiveTypeDescriptor descriptor,
Function<Object, Publisher<?>> toAdapter, Function<Publisher<?>, Object> fromAdapter) { Function<Object, Publisher<?>> toAdapter, Function<Publisher<?>, Object> fromAdapter) {
return (reactorPresent ? new ReactorAdapter(descriptor, toAdapter, fromAdapter) : return (REACTOR_PRESENT ? new ReactorAdapter(descriptor, toAdapter, fromAdapter) :
new ReactiveAdapter(descriptor, toAdapter, fromAdapter)); new ReactiveAdapter(descriptor, toAdapter, fromAdapter));
} }

16
spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java

@ -43,15 +43,15 @@ class MapTests extends AbstractExpressionTests {
// if the list is full of literals then it will be of the type unmodifiableMapClass // if the list is full of literals then it will be of the type unmodifiableMapClass
// rather than HashMap (or similar) // rather than HashMap (or similar)
private static final Class<?> unmodifiableMapClass = Collections.unmodifiableMap(Map.of()).getClass(); private static final Class<?> UNMODIFIABLE_MAP_CLASS = Collections.unmodifiableMap(Map.of()).getClass();
@Test @Test
void inlineMapCreationForLiterals() { void inlineMapCreationForLiterals() {
evaluate("{'a':1, 'b':2, 'c':3, 'd':4, 'e':5}", "{a=1, b=2, c=3, d=4, e=5}", unmodifiableMapClass); evaluate("{'a':1, 'b':2, 'c':3, 'd':4, 'e':5}", "{a=1, b=2, c=3, d=4, e=5}", UNMODIFIABLE_MAP_CLASS);
evaluate("{'a':1}", "{a=1}", unmodifiableMapClass); evaluate("{'a':1}", "{a=1}", UNMODIFIABLE_MAP_CLASS);
evaluate("{'abc':'def', 'uvw':'xyz'}", "{abc=def, uvw=xyz}", unmodifiableMapClass); evaluate("{'abc':'def', 'uvw':'xyz'}", "{abc=def, uvw=xyz}", UNMODIFIABLE_MAP_CLASS);
evaluate("{:}", "{}", unmodifiableMapClass); evaluate("{:}", "{}", UNMODIFIABLE_MAP_CLASS);
} }
@Test @Test
@ -65,9 +65,9 @@ class MapTests extends AbstractExpressionTests {
@Test @Test
void inlineMapAndNesting() { void inlineMapAndNesting() {
evaluate("{a:{a:1,b:2,c:3},b:{d:4,e:5,f:6}}", "{a={a=1, b=2, c=3}, b={d=4, e=5, f=6}}", unmodifiableMapClass); evaluate("{a:{a:1,b:2,c:3},b:{d:4,e:5,f:6}}", "{a={a=1, b=2, c=3}, b={d=4, e=5, f=6}}", UNMODIFIABLE_MAP_CLASS);
evaluate("{a:{x:1,y:'2',z:3},b:{u:4,v:{'a','b'},w:5,x:6}}", "{a={x=1, y=2, z=3}, b={u=4, v=[a, b], w=5, x=6}}", unmodifiableMapClass); evaluate("{a:{x:1,y:'2',z:3},b:{u:4,v:{'a','b'},w:5,x:6}}", "{a={x=1, y=2, z=3}, b={u=4, v=[a, b], w=5, x=6}}", UNMODIFIABLE_MAP_CLASS);
evaluate("{a:{1,2,3},b:{4,5,6}}", "{a=[1, 2, 3], b=[4, 5, 6]}", unmodifiableMapClass); evaluate("{a:{1,2,3},b:{4,5,6}}", "{a=[1, 2, 3], b=[4, 5, 6]}", UNMODIFIABLE_MAP_CLASS);
} }
@Test @Test

6
spring-jms/src/main/java/org/springframework/jms/core/JmsTemplate.java

@ -94,7 +94,7 @@ import org.springframework.util.ClassUtils;
*/ */
public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations { public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations {
private static final boolean micrometerJakartaPresent = ClassUtils.isPresent( private static final boolean MICROMETER_JAKARTA_PRESENT = ClassUtils.isPresent(
"io.micrometer.jakarta9.instrument.jms.JmsInstrumentation", JmsTemplate.class.getClassLoader()); "io.micrometer.jakarta9.instrument.jms.JmsInstrumentation", JmsTemplate.class.getClassLoader());
/** Internal ResourceFactory adapter for interacting with ConnectionFactoryUtils. */ /** Internal ResourceFactory adapter for interacting with ConnectionFactoryUtils. */
@ -530,7 +530,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Executing callback on JMS Session: " + sessionToUse); logger.debug("Executing callback on JMS Session: " + sessionToUse);
} }
if (micrometerJakartaPresent && this.observationRegistry != null) { if (MICROMETER_JAKARTA_PRESENT && this.observationRegistry != null) {
sessionToUse = MicrometerInstrumentation.instrumentSession(sessionToUse, this.observationRegistry); sessionToUse = MicrometerInstrumentation.instrumentSession(sessionToUse, this.observationRegistry);
} }
return action.doInJms(sessionToUse); return action.doInJms(sessionToUse);
@ -952,7 +952,7 @@ public class JmsTemplate extends JmsDestinationAccessor implements JmsOperations
try { try {
con = createConnection(); con = createConnection();
session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
if (micrometerJakartaPresent && this.observationRegistry != null) { if (MICROMETER_JAKARTA_PRESENT && this.observationRegistry != null) {
session = MicrometerInstrumentation.instrumentSession(session, this.observationRegistry); session = MicrometerInstrumentation.instrumentSession(session, this.observationRegistry);
} }
if (startConnection) { if (startConnection) {

6
spring-jms/src/main/java/org/springframework/jms/listener/AbstractMessageListenerContainer.java

@ -151,7 +151,7 @@ import org.springframework.util.ErrorHandler;
public abstract class AbstractMessageListenerContainer extends AbstractJmsListeningContainer public abstract class AbstractMessageListenerContainer extends AbstractJmsListeningContainer
implements MessageListenerContainer { implements MessageListenerContainer {
private static final boolean micrometerJakartaPresent = ClassUtils.isPresent( private static final boolean MICROMETER_JAKARTA_PRESENT = ClassUtils.isPresent(
"io.micrometer.jakarta9.instrument.jms.JmsInstrumentation", "io.micrometer.jakarta9.instrument.jms.JmsInstrumentation",
AbstractMessageListenerContainer.class.getClassLoader()); AbstractMessageListenerContainer.class.getClassLoader());
@ -700,7 +700,7 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
* @since 6.1 * @since 6.1
*/ */
protected Observation createObservation(Message message) { protected Observation createObservation(Message message) {
if (micrometerJakartaPresent && this.observationRegistry != null) { if (MICROMETER_JAKARTA_PRESENT && this.observationRegistry != null) {
return ObservationFactory.create(this.observationRegistry, message); return ObservationFactory.create(this.observationRegistry, message);
} }
else { else {
@ -785,7 +785,7 @@ public abstract class AbstractMessageListenerContainer extends AbstractJmsListen
Session sessionToClose = null; Session sessionToClose = null;
try { try {
Session sessionToUse = session; Session sessionToUse = session;
if (micrometerJakartaPresent && this.observationRegistry != null) { if (MICROMETER_JAKARTA_PRESENT && this.observationRegistry != null) {
sessionToUse = MicrometerInstrumentation.instrumentSession(sessionToUse, this.observationRegistry); sessionToUse = MicrometerInstrumentation.instrumentSession(sessionToUse, this.observationRegistry);
} }
if (!isExposeListenerSession()) { if (!isExposeListenerSession()) {

4
spring-messaging/src/main/java/org/springframework/messaging/converter/ProtobufMessageConverter.java

@ -67,7 +67,7 @@ public class ProtobufMessageConverter extends AbstractMessageConverter {
*/ */
public static final MimeType PROTOBUF = new MimeType("application", "x-protobuf", DEFAULT_CHARSET); public static final MimeType PROTOBUF = new MimeType("application", "x-protobuf", DEFAULT_CHARSET);
private static final boolean protobufJsonFormatPresent = private static final boolean PROTOBUF_JSON_FORMAT_PRESENT =
ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", ProtobufMessageConverter.class.getClassLoader()); ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", ProtobufMessageConverter.class.getClassLoader());
private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>(); private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>();
@ -100,7 +100,7 @@ public class ProtobufMessageConverter extends AbstractMessageConverter {
if (formatSupport != null) { if (formatSupport != null) {
this.protobufFormatSupport = formatSupport; this.protobufFormatSupport = formatSupport;
} }
else if (protobufJsonFormatPresent) { else if (PROTOBUF_JSON_FORMAT_PRESENT) {
this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null); this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null);
} }
else { else {

4
spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandler.java

@ -94,7 +94,7 @@ import org.springframework.validation.Validator;
public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHandler<SimpMessageMappingInfo> public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHandler<SimpMessageMappingInfo>
implements EmbeddedValueResolverAware, SmartLifecycle { implements EmbeddedValueResolverAware, SmartLifecycle {
private static final boolean reactorPresent = ClassUtils.isPresent( private static final boolean REACTOR_PRESENT = ClassUtils.isPresent(
"reactor.core.publisher.Flux", SimpAnnotationMethodMessageHandler.class.getClassLoader()); "reactor.core.publisher.Flux", SimpAnnotationMethodMessageHandler.class.getClassLoader());
@ -344,7 +344,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
// Single-purpose return value types // Single-purpose return value types
handlers.add(new CompletableFutureReturnValueHandler()); handlers.add(new CompletableFutureReturnValueHandler());
if (reactorPresent) { if (REACTOR_PRESENT) {
handlers.add(new ReactiveReturnValueHandler()); handlers.add(new ReactiveReturnValueHandler());
} }

30
spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java

@ -104,25 +104,25 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC
private static final String MVC_VALIDATOR_NAME = "mvcValidator"; private static final String MVC_VALIDATOR_NAME = "mvcValidator";
private static final boolean jacksonPresent; private static final boolean JACKSON_PRESENT;
private static final boolean jackson2Present; private static final boolean JACKSON_2_PRESENT;
private static final boolean gsonPresent; private static final boolean GSON_PRESENT;
private static final boolean jsonbPresent; private static final boolean JSONB_PRESENT;
private static final boolean kotlinSerializationJsonPresent; private static final boolean KOTLIN_SERIALIZATION_JSON_PRESENT;
static { static {
ClassLoader classLoader = AbstractMessageBrokerConfiguration.class.getClassLoader(); ClassLoader classLoader = AbstractMessageBrokerConfiguration.class.getClassLoader();
jacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); GSON_PRESENT = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader); JSONB_PRESENT = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader); KOTLIN_SERIALIZATION_JSON_PRESENT = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
} }
@ -502,19 +502,19 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC
if (registerDefaults) { if (registerDefaults) {
converters.add(new StringMessageConverter()); converters.add(new StringMessageConverter());
converters.add(new ByteArrayMessageConverter()); converters.add(new ByteArrayMessageConverter());
if (kotlinSerializationJsonPresent) { if (KOTLIN_SERIALIZATION_JSON_PRESENT) {
converters.add(new KotlinSerializationJsonMessageConverter()); converters.add(new KotlinSerializationJsonMessageConverter());
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
converters.add(createJacksonJsonConverter()); converters.add(createJacksonJsonConverter());
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
converters.add(createJacksonConverter()); converters.add(createJacksonConverter());
} }
else if (gsonPresent) { else if (GSON_PRESENT) {
converters.add(new GsonMessageConverter()); converters.add(new GsonMessageConverter());
} }
else if (jsonbPresent) { else if (JSONB_PRESENT) {
converters.add(new JsonbMessageConverter()); converters.add(new JsonbMessageConverter());
} }
} }

4
spring-orm/src/main/java/org/springframework/orm/jpa/persistenceunit/PersistenceManagedTypesBeanRegistrationAotProcessor.java

@ -68,12 +68,12 @@ import org.springframework.util.ReflectionUtils;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
class PersistenceManagedTypesBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor { class PersistenceManagedTypesBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor {
private static final boolean jpaPresent = ClassUtils.isPresent("jakarta.persistence.Entity", private static final boolean JPA_PRESENT = ClassUtils.isPresent("jakarta.persistence.Entity",
PersistenceManagedTypesBeanRegistrationAotProcessor.class.getClassLoader()); PersistenceManagedTypesBeanRegistrationAotProcessor.class.getClassLoader());
@Override @Override
public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { public @Nullable BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) {
if (jpaPresent) { if (JPA_PRESENT) {
if (PersistenceManagedTypes.class.isAssignableFrom(registeredBean.getBeanClass())) { if (PersistenceManagedTypes.class.isAssignableFrom(registeredBean.getBeanClass())) {
return BeanRegistrationAotContribution.withCustomCodeFragments(codeFragments -> return BeanRegistrationAotContribution.withCustomCodeFragments(codeFragments ->
new JpaManagedTypesBeanRegistrationCodeFragments(codeFragments, registeredBean)); new JpaManagedTypesBeanRegistrationCodeFragments(codeFragments, registeredBean));

4
spring-test/src/main/java/org/springframework/test/context/BootstrapUtils.java

@ -60,7 +60,7 @@ public abstract class BootstrapUtils {
private static final String WEB_APP_CONFIGURATION_ANNOTATION_CLASS_NAME = private static final String WEB_APP_CONFIGURATION_ANNOTATION_CLASS_NAME =
"org.springframework.test.context.web.WebAppConfiguration"; "org.springframework.test.context.web.WebAppConfiguration";
private static final Class<? extends Annotation> webAppConfigurationClass = loadWebAppConfigurationClass(); private static final Class<? extends Annotation> WEB_APP_CONFIGURATION_CLASS = loadWebAppConfigurationClass();
private static final Log logger = LogFactory.getLog(BootstrapUtils.class); private static final Log logger = LogFactory.getLog(BootstrapUtils.class);
@ -196,7 +196,7 @@ public abstract class BootstrapUtils {
} }
private static Class<?> resolveDefaultTestContextBootstrapper(Class<?> testClass) throws Exception { private static Class<?> resolveDefaultTestContextBootstrapper(Class<?> testClass) throws Exception {
boolean webApp = TestContextAnnotationUtils.hasAnnotation(testClass, webAppConfigurationClass); boolean webApp = TestContextAnnotationUtils.hasAnnotation(testClass, WEB_APP_CONFIGURATION_CLASS);
String bootstrapperClassName = (webApp ? DEFAULT_WEB_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME : String bootstrapperClassName = (webApp ? DEFAULT_WEB_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME :
DEFAULT_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME); DEFAULT_TEST_CONTEXT_BOOTSTRAPPER_CLASS_NAME);
return ClassUtils.forName(bootstrapperClassName, BootstrapUtils.class.getClassLoader()); return ClassUtils.forName(bootstrapperClassName, BootstrapUtils.class.getClassLoader());

6
spring-test/src/main/java/org/springframework/test/context/aot/MergedContextConfigurationRuntimeHints.java

@ -57,7 +57,7 @@ class MergedContextConfigurationRuntimeHints {
private static final String GET_RESOURCE_BASE_PATH_METHOD_NAME = "getResourceBasePath"; private static final String GET_RESOURCE_BASE_PATH_METHOD_NAME = "getResourceBasePath";
private static final Class<?> webMergedContextConfigurationClass = loadWebMergedContextConfigurationClass(); private static final Class<?> WEB_MERGED_CONTEXT_CONFIGURATION_CLASS = loadWebMergedContextConfigurationClass();
private static final Method getResourceBasePathMethod = loadGetResourceBasePathMethod(); private static final Method getResourceBasePathMethod = loadGetResourceBasePathMethod();
@ -90,7 +90,7 @@ class MergedContextConfigurationRuntimeHints {
} }
// @WebAppConfiguration(value = ...) // @WebAppConfiguration(value = ...)
if (webMergedContextConfigurationClass.isInstance(mergedConfig)) { if (WEB_MERGED_CONTEXT_CONFIGURATION_CLASS.isInstance(mergedConfig)) {
String resourceBasePath; String resourceBasePath;
try { try {
resourceBasePath = (String) getResourceBasePathMethod.invoke(mergedConfig); resourceBasePath = (String) getResourceBasePathMethod.invoke(mergedConfig);
@ -162,7 +162,7 @@ class MergedContextConfigurationRuntimeHints {
private static Method loadGetResourceBasePathMethod() { private static Method loadGetResourceBasePathMethod() {
try { try {
return webMergedContextConfigurationClass.getMethod(GET_RESOURCE_BASE_PATH_METHOD_NAME); return WEB_MERGED_CONTEXT_CONFIGURATION_CLASS.getMethod(GET_RESOURCE_BASE_PATH_METHOD_NAME);
} }
catch (Exception ex) { catch (Exception ex) {
throw new IllegalStateException( throw new IllegalStateException(

10
spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoResetTestExecutionListener.java

@ -63,17 +63,17 @@ public class MockitoResetTestExecutionListener extends AbstractTestExecutionList
* @see #mockitoInitialized * @see #mockitoInitialized
* @see #isEnabled() * @see #isEnabled()
*/ */
private static final boolean mockitoPresent = ClassUtils.isPresent("org.mockito.Mockito", private static final boolean MOCKITO_PRESENT = ClassUtils.isPresent("org.mockito.Mockito",
MockitoResetTestExecutionListener.class.getClassLoader()); MockitoResetTestExecutionListener.class.getClassLoader());
/** /**
* Boolean flag which tracks whether Mockito has been successfully initialized * Boolean flag which tracks whether Mockito has been successfully initialized
* in the current environment. * in the current environment.
* <p>Even if {@link #mockitoPresent} evaluates to {@code true}, this flag * <p>Even if {@link #MOCKITO_PRESENT} evaluates to {@code true}, this flag
* may eventually evaluate to {@code false} &mdash; for example, in a GraalVM * may eventually evaluate to {@code false} &mdash; for example, in a GraalVM
* native image if the necessary reachability metadata has not been registered * native image if the necessary reachability metadata has not been registered
* for the {@link org.mockito.plugins.MockMaker} in use. * for the {@link org.mockito.plugins.MockMaker} in use.
* @see #mockitoPresent * @see #MOCKITO_PRESENT
* @see #isEnabled() * @see #isEnabled()
*/ */
private static volatile @Nullable Boolean mockitoInitialized; private static volatile @Nullable Boolean mockitoInitialized;
@ -158,11 +158,11 @@ public class MockitoResetTestExecutionListener extends AbstractTestExecutionList
/** /**
* Determine if this listener is enabled in the current environment. * Determine if this listener is enabled in the current environment.
* @see #mockitoPresent * @see #MOCKITO_PRESENT
* @see #mockitoInitialized * @see #mockitoInitialized
*/ */
private static boolean isEnabled() { private static boolean isEnabled() {
if (!mockitoPresent) { if (!MOCKITO_PRESENT) {
return false; return false;
} }
Boolean enabled = mockitoInitialized; Boolean enabled = mockitoInitialized;

2
spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanOverrideHandler.java

@ -80,7 +80,7 @@ class MockitoSpyBeanOverrideHandler extends AbstractMockitoBeanOverrideHandler {
if (StringUtils.hasLength(name)) { if (StringUtils.hasLength(name)) {
settings.name(name); settings.name(name);
} }
if (SpringMockResolver.springAopPresent) { if (SpringMockResolver.SPRING_AOP_PRESENT) {
settings.verificationStartedListeners(verificationStartedListener); settings.verificationStartedListeners(verificationStartedListener);
} }

4
spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/SpringMockResolver.java

@ -37,13 +37,13 @@ import org.springframework.util.ClassUtils;
*/ */
public class SpringMockResolver implements MockResolver { public class SpringMockResolver implements MockResolver {
static final boolean springAopPresent = ClassUtils.isPresent( static final boolean SPRING_AOP_PRESENT = ClassUtils.isPresent(
"org.springframework.aop.framework.Advised", SpringMockResolver.class.getClassLoader()); "org.springframework.aop.framework.Advised", SpringMockResolver.class.getClassLoader());
@Override @Override
public Object resolve(Object instance) { public Object resolve(Object instance) {
if (springAopPresent) { if (SPRING_AOP_PRESENT) {
return getUltimateTargetObject(instance); return getUltimateTargetObject(instance);
} }
return instance; return instance;

4
spring-test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java

@ -39,7 +39,7 @@ public class DelegatingSmartContextLoader extends AbstractDelegatingSmartContext
private static final String GROOVY_XML_CONTEXT_LOADER_CLASS_NAME = private static final String GROOVY_XML_CONTEXT_LOADER_CLASS_NAME =
"org.springframework.test.context.support.GenericGroovyXmlContextLoader"; "org.springframework.test.context.support.GenericGroovyXmlContextLoader";
private static final boolean groovyPresent = ClassUtils.isPresent("groovy.lang.Closure", private static final boolean GROOVY_PRESENT = ClassUtils.isPresent("groovy.lang.Closure",
DelegatingSmartContextLoader.class.getClassLoader()) && DelegatingSmartContextLoader.class.getClassLoader()) &&
ClassUtils.isPresent(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, ClassUtils.isPresent(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME,
DelegatingSmartContextLoader.class.getClassLoader()); DelegatingSmartContextLoader.class.getClassLoader());
@ -50,7 +50,7 @@ public class DelegatingSmartContextLoader extends AbstractDelegatingSmartContext
public DelegatingSmartContextLoader() { public DelegatingSmartContextLoader() {
if (groovyPresent) { if (GROOVY_PRESENT) {
try { try {
Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME,
DelegatingSmartContextLoader.class.getClassLoader()); DelegatingSmartContextLoader.class.getClassLoader());

4
spring-test/src/main/java/org/springframework/test/context/web/WebDelegatingSmartContextLoader.java

@ -38,7 +38,7 @@ public class WebDelegatingSmartContextLoader extends AbstractDelegatingSmartCont
private static final String GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.web.GenericGroovyXmlWebContextLoader"; private static final String GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.web.GenericGroovyXmlWebContextLoader";
private static final boolean groovyPresent = ClassUtils.isPresent("groovy.lang.Closure", private static final boolean GROOVY_PRESENT = ClassUtils.isPresent("groovy.lang.Closure",
WebDelegatingSmartContextLoader.class.getClassLoader()) && WebDelegatingSmartContextLoader.class.getClassLoader()) &&
ClassUtils.isPresent(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME, ClassUtils.isPresent(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME,
WebDelegatingSmartContextLoader.class.getClassLoader()); WebDelegatingSmartContextLoader.class.getClassLoader());
@ -48,7 +48,7 @@ public class WebDelegatingSmartContextLoader extends AbstractDelegatingSmartCont
public WebDelegatingSmartContextLoader() { public WebDelegatingSmartContextLoader() {
if (groovyPresent) { if (GROOVY_PRESENT) {
try { try {
Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME, Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME,
WebDelegatingSmartContextLoader.class.getClassLoader()); WebDelegatingSmartContextLoader.class.getClassLoader());

4
spring-test/src/main/java/org/springframework/test/context/web/socket/MockServerContainerContextCustomizerFactory.java

@ -38,7 +38,7 @@ import org.springframework.util.ClassUtils;
*/ */
class MockServerContainerContextCustomizerFactory implements ContextCustomizerFactory { class MockServerContainerContextCustomizerFactory implements ContextCustomizerFactory {
private static final boolean webSocketPresent = ClassUtils.isPresent("jakarta.websocket.server.ServerContainer", private static final boolean WEB_SOCKET_PRESENT = ClassUtils.isPresent("jakarta.websocket.server.ServerContainer",
MockServerContainerContextCustomizerFactory.class.getClassLoader()); MockServerContainerContextCustomizerFactory.class.getClassLoader());
@ -46,7 +46,7 @@ class MockServerContainerContextCustomizerFactory implements ContextCustomizerFa
public @Nullable ContextCustomizer createContextCustomizer(Class<?> testClass, public @Nullable ContextCustomizer createContextCustomizer(Class<?> testClass,
List<ContextConfigurationAttributes> configAttributes) { List<ContextConfigurationAttributes> configAttributes) {
if (webSocketPresent && isAnnotatedWithWebAppConfiguration(testClass)) { if (WEB_SOCKET_PRESENT && isAnnotatedWithWebAppConfiguration(testClass)) {
return new MockServerContainerContextCustomizer(); return new MockServerContainerContextCustomizer();
} }
// Else, nothing to customize // Else, nothing to customize

12
spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java

@ -75,7 +75,7 @@ public abstract class ReflectionTestUtils {
private static final Log logger = LogFactory.getLog(ReflectionTestUtils.class); private static final Log logger = LogFactory.getLog(ReflectionTestUtils.class);
private static final boolean springAopPresent = ClassUtils.isPresent( private static final boolean SPRING_AOP_PRESENT = ClassUtils.isPresent(
"org.springframework.aop.framework.Advised", ReflectionTestUtils.class.getClassLoader()); "org.springframework.aop.framework.Advised", ReflectionTestUtils.class.getClassLoader());
@ -180,7 +180,7 @@ public abstract class ReflectionTestUtils {
Assert.isTrue(targetObject != null || targetClass != null, Assert.isTrue(targetObject != null || targetClass != null,
"Either targetObject or targetClass for the field must be specified"); "Either targetObject or targetClass for the field must be specified");
if (targetObject != null && springAopPresent) { if (targetObject != null && SPRING_AOP_PRESENT) {
targetObject = AopTestUtils.getUltimateTargetObject(targetObject); targetObject = AopTestUtils.getUltimateTargetObject(targetObject);
} }
if (targetClass == null) { if (targetClass == null) {
@ -263,7 +263,7 @@ public abstract class ReflectionTestUtils {
Assert.isTrue(targetObject != null || targetClass != null, Assert.isTrue(targetObject != null || targetClass != null,
"Either targetObject or targetClass for the field must be specified"); "Either targetObject or targetClass for the field must be specified");
if (targetObject != null && springAopPresent) { if (targetObject != null && SPRING_AOP_PRESENT) {
targetObject = AopTestUtils.getUltimateTargetObject(targetObject); targetObject = AopTestUtils.getUltimateTargetObject(targetObject);
} }
if (targetClass == null) { if (targetClass == null) {
@ -352,7 +352,7 @@ public abstract class ReflectionTestUtils {
safeToString(target), value)); safeToString(target), value));
} }
if (springAopPresent) { if (SPRING_AOP_PRESENT) {
// If the target is a CGLIB proxy which does not intercept the method, invoke the // If the target is a CGLIB proxy which does not intercept the method, invoke the
// method on the ultimate target. // method on the ultimate target.
if (isCglibProxyThatDoesNotInterceptMethod(target, method)) { if (isCglibProxyThatDoesNotInterceptMethod(target, method)) {
@ -406,7 +406,7 @@ public abstract class ReflectionTestUtils {
"Could not find getter method '%s' on %s", getterMethodName, safeToString(target))); "Could not find getter method '%s' on %s", getterMethodName, safeToString(target)));
} }
if (springAopPresent) { if (SPRING_AOP_PRESENT) {
// If the target is a CGLIB proxy which does not intercept the method, invoke the // If the target is a CGLIB proxy which does not intercept the method, invoke the
// method on the ultimate target. // method on the ultimate target.
if (isCglibProxyThatDoesNotInterceptMethod(target, method)) { if (isCglibProxyThatDoesNotInterceptMethod(target, method)) {
@ -500,7 +500,7 @@ public abstract class ReflectionTestUtils {
methodInvoker.setArguments(args); methodInvoker.setArguments(args);
methodInvoker.prepare(); methodInvoker.prepare();
if (targetObject != null && springAopPresent) { if (targetObject != null && SPRING_AOP_PRESENT) {
// If the target is a CGLIB proxy which does not intercept the method, invoke the // If the target is a CGLIB proxy which does not intercept the method, invoke the
// method on the ultimate target. // method on the ultimate target.
if (isCglibProxyThatDoesNotInterceptMethod(targetObject, methodInvoker.getPreparedMethod())) { if (isCglibProxyThatDoesNotInterceptMethod(targetObject, methodInvoker.getPreparedMethod())) {

24
spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClientBuilder.java

@ -56,22 +56,22 @@ import org.springframework.web.util.UriBuilderFactory;
*/ */
class DefaultWebTestClientBuilder implements WebTestClient.Builder { class DefaultWebTestClientBuilder implements WebTestClient.Builder {
private static final boolean reactorNettyClientPresent; private static final boolean REACTOR_NETTY_CLIENT_PRESENT;
private static final boolean jettyClientPresent; private static final boolean JETTY_CLIENT_PRESENT;
private static final boolean httpComponentsClientPresent; private static final boolean HTTP_COMPONENTS_CLIENT_PRESENT;
private static final boolean webFluxPresent; private static final boolean WEB_FLUX_PRESENT;
static { static {
ClassLoader loader = DefaultWebTestClientBuilder.class.getClassLoader(); ClassLoader loader = DefaultWebTestClientBuilder.class.getClassLoader();
reactorNettyClientPresent = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader); REACTOR_NETTY_CLIENT_PRESENT = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader);
jettyClientPresent = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader); JETTY_CLIENT_PRESENT = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader);
httpComponentsClientPresent = HTTP_COMPONENTS_CLIENT_PRESENT =
ClassUtils.isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) && ClassUtils.isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) &&
ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader); ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader);
webFluxPresent = ClassUtils.isPresent( WEB_FLUX_PRESENT = ClassUtils.isPresent(
"org.springframework.web.reactive.function.client.ExchangeFunction", loader); "org.springframework.web.reactive.function.client.ExchangeFunction", loader);
} }
@ -122,7 +122,7 @@ class DefaultWebTestClientBuilder implements WebTestClient.Builder {
"Expected WebHttpHandlerBuilder or ClientHttpConnector but not both."); "Expected WebHttpHandlerBuilder or ClientHttpConnector but not both.");
// Helpful message especially for MockMvcWebTestClient users // Helpful message especially for MockMvcWebTestClient users
Assert.state(webFluxPresent, Assert.state(WEB_FLUX_PRESENT,
"To use WebTestClient, please add spring-webflux to the test classpath."); "To use WebTestClient, please add spring-webflux to the test classpath.");
this.connector = connector; this.connector = connector;
@ -312,13 +312,13 @@ class DefaultWebTestClientBuilder implements WebTestClient.Builder {
} }
private static ClientHttpConnector initConnector() { private static ClientHttpConnector initConnector() {
if (reactorNettyClientPresent) { if (REACTOR_NETTY_CLIENT_PRESENT) {
return new ReactorClientHttpConnector(); return new ReactorClientHttpConnector();
} }
else if (jettyClientPresent) { else if (JETTY_CLIENT_PRESENT) {
return new JettyClientHttpConnector(); return new JettyClientHttpConnector();
} }
else if (httpComponentsClientPresent) { else if (HTTP_COMPONENTS_CLIENT_PRESENT) {
return new HttpComponentsClientHttpConnector(); return new HttpComponentsClientHttpConnector();
} }
else { else {

10
spring-test/src/test/java/org/springframework/test/context/TestExecutionListenersTests.java

@ -59,7 +59,7 @@ import static org.springframework.test.context.TestExecutionListeners.MergeMode.
*/ */
class TestExecutionListenersTests { class TestExecutionListenersTests {
private static final Class<?> micrometerListenerClass = private static final Class<?> MICROMETER_LISTENER_CLASS =
ClassUtils.resolveClassName("org.springframework.test.context.observation.MicrometerObservationRegistryTestExecutionListener", null); ClassUtils.resolveClassName("org.springframework.test.context.observation.MicrometerObservationRegistryTestExecutionListener", null);
@Test @Test
@ -70,7 +70,7 @@ class TestExecutionListenersTests {
ApplicationEventsTestExecutionListener.class,// ApplicationEventsTestExecutionListener.class,//
BeanOverrideTestExecutionListener.class,// BeanOverrideTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,// DependencyInjectionTestExecutionListener.class,//
micrometerListenerClass,// MICROMETER_LISTENER_CLASS,//
DirtiesContextTestExecutionListener.class,// DirtiesContextTestExecutionListener.class,//
CommonCachesTestExecutionListener.class, // CommonCachesTestExecutionListener.class, //
TransactionalTestExecutionListener.class,// TransactionalTestExecutionListener.class,//
@ -93,7 +93,7 @@ class TestExecutionListenersTests {
ApplicationEventsTestExecutionListener.class,// ApplicationEventsTestExecutionListener.class,//
BeanOverrideTestExecutionListener.class,// BeanOverrideTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,// DependencyInjectionTestExecutionListener.class,//
micrometerListenerClass,// MICROMETER_LISTENER_CLASS,//
DirtiesContextTestExecutionListener.class,// DirtiesContextTestExecutionListener.class,//
CommonCachesTestExecutionListener.class, // CommonCachesTestExecutionListener.class, //
TransactionalTestExecutionListener.class,// TransactionalTestExecutionListener.class,//
@ -115,7 +115,7 @@ class TestExecutionListenersTests {
ApplicationEventsTestExecutionListener.class,// ApplicationEventsTestExecutionListener.class,//
BeanOverrideTestExecutionListener.class,// BeanOverrideTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,// DependencyInjectionTestExecutionListener.class,//
micrometerListenerClass,// MICROMETER_LISTENER_CLASS,//
DirtiesContextTestExecutionListener.class,// DirtiesContextTestExecutionListener.class,//
CommonCachesTestExecutionListener.class, // CommonCachesTestExecutionListener.class, //
TransactionalTestExecutionListener.class, TransactionalTestExecutionListener.class,
@ -139,7 +139,7 @@ class TestExecutionListenersTests {
BeanOverrideTestExecutionListener.class,// BeanOverrideTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,// DependencyInjectionTestExecutionListener.class,//
BarTestExecutionListener.class,// BarTestExecutionListener.class,//
micrometerListenerClass,// MICROMETER_LISTENER_CLASS,//
DirtiesContextTestExecutionListener.class,// DirtiesContextTestExecutionListener.class,//
CommonCachesTestExecutionListener.class, // CommonCachesTestExecutionListener.class, //
TransactionalTestExecutionListener.class,// TransactionalTestExecutionListener.class,//

14
spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java

@ -60,14 +60,14 @@ import org.springframework.util.CollectionUtils;
public class AnnotationTransactionAttributeSource extends AbstractFallbackTransactionAttributeSource public class AnnotationTransactionAttributeSource extends AbstractFallbackTransactionAttributeSource
implements Serializable { implements Serializable {
private static final boolean jtaPresent; private static final boolean JTA_PRESENT;
private static final boolean ejb3Present; private static final boolean EJB_3_PRESENT;
static { static {
ClassLoader classLoader = AnnotationTransactionAttributeSource.class.getClassLoader(); ClassLoader classLoader = AnnotationTransactionAttributeSource.class.getClassLoader();
jtaPresent = ClassUtils.isPresent("jakarta.transaction.Transactional", classLoader); JTA_PRESENT = ClassUtils.isPresent("jakarta.transaction.Transactional", classLoader);
ejb3Present = ClassUtils.isPresent("jakarta.ejb.TransactionAttribute", classLoader); EJB_3_PRESENT = ClassUtils.isPresent("jakarta.ejb.TransactionAttribute", classLoader);
} }
private final Set<TransactionAnnotationParser> annotationParsers; private final Set<TransactionAnnotationParser> annotationParsers;
@ -83,13 +83,13 @@ public class AnnotationTransactionAttributeSource extends AbstractFallbackTransa
* or the EJB3 {@link jakarta.ejb.TransactionAttribute} annotation. * or the EJB3 {@link jakarta.ejb.TransactionAttribute} annotation.
*/ */
public AnnotationTransactionAttributeSource() { public AnnotationTransactionAttributeSource() {
if (jtaPresent || ejb3Present) { if (JTA_PRESENT || EJB_3_PRESENT) {
this.annotationParsers = CollectionUtils.newLinkedHashSet(3); this.annotationParsers = CollectionUtils.newLinkedHashSet(3);
this.annotationParsers.add(new SpringTransactionAnnotationParser()); this.annotationParsers.add(new SpringTransactionAnnotationParser());
if (jtaPresent) { if (JTA_PRESENT) {
this.annotationParsers.add(new JtaTransactionAnnotationParser()); this.annotationParsers.add(new JtaTransactionAnnotationParser());
} }
if (ejb3Present) { if (EJB_3_PRESENT) {
this.annotationParsers.add(new Ejb3TransactionAnnotationParser()); this.annotationParsers.add(new Ejb3TransactionAnnotationParser());
} }
} }

10
spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java

@ -104,13 +104,13 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
/** /**
* Reactive Streams API present on the classpath? * Reactive Streams API present on the classpath?
*/ */
private static final boolean reactiveStreamsPresent = ClassUtils.isPresent( private static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", TransactionAspectSupport.class.getClassLoader()); "org.reactivestreams.Publisher", TransactionAspectSupport.class.getClassLoader());
/** /**
* Vavr library present on the classpath? * Vavr library present on the classpath?
*/ */
private static final boolean vavrPresent = ClassUtils.isPresent( private static final boolean VAVR_PRESENT = ClassUtils.isPresent(
"io.vavr.control.Try", TransactionAspectSupport.class.getClassLoader()); "io.vavr.control.Try", TransactionAspectSupport.class.getClassLoader());
/** /**
@ -187,7 +187,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
protected TransactionAspectSupport() { protected TransactionAspectSupport() {
if (reactiveStreamsPresent) { if (REACTIVE_STREAMS_PRESENT) {
this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); this.reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
} }
else { else {
@ -395,7 +395,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
else if (vavrPresent && VavrDelegate.isVavrTry(retVal)) { else if (VAVR_PRESENT && VavrDelegate.isVavrTry(retVal)) {
// Set rollback-only in case of Vavr failure matching our rollback rules... // Set rollback-only in case of Vavr failure matching our rollback rules...
retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
} }
@ -416,7 +416,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status); TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
try { try {
Object retVal = invocation.proceedWithInvocation(); Object retVal = invocation.proceedWithInvocation();
if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) { if (retVal != null && VAVR_PRESENT && VavrDelegate.isVavrTry(retVal)) {
// Set rollback-only in case of Vavr failure matching our rollback rules... // Set rollback-only in case of Vavr failure matching our rollback rules...
retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
} }

4
spring-tx/src/main/java/org/springframework/transaction/reactive/TransactionSynchronizationUtils.java

@ -42,7 +42,7 @@ abstract class TransactionSynchronizationUtils {
private static final Log logger = LogFactory.getLog(TransactionSynchronizationUtils.class); private static final Log logger = LogFactory.getLog(TransactionSynchronizationUtils.class);
private static final boolean aopPresent = ClassUtils.isPresent( private static final boolean SPRING_AOP_PRESENT = ClassUtils.isPresent(
"org.springframework.aop.scope.ScopedObject", TransactionSynchronizationUtils.class.getClassLoader()); "org.springframework.aop.scope.ScopedObject", TransactionSynchronizationUtils.class.getClassLoader());
@ -58,7 +58,7 @@ abstract class TransactionSynchronizationUtils {
if (resourceRef instanceof InfrastructureProxy infrastructureProxy) { if (resourceRef instanceof InfrastructureProxy infrastructureProxy) {
resourceRef = infrastructureProxy.getWrappedObject(); resourceRef = infrastructureProxy.getWrappedObject();
} }
if (aopPresent) { if (SPRING_AOP_PRESENT) {
// now unwrap scoped proxy // now unwrap scoped proxy
resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef); resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef);
} }

4
spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationUtils.java

@ -40,7 +40,7 @@ public abstract class TransactionSynchronizationUtils {
private static final Log logger = LogFactory.getLog(TransactionSynchronizationUtils.class); private static final Log logger = LogFactory.getLog(TransactionSynchronizationUtils.class);
private static final boolean aopPresent = ClassUtils.isPresent( private static final boolean SPRING_AOP_PRESENT = ClassUtils.isPresent(
"org.springframework.aop.scope.ScopedObject", TransactionSynchronizationUtils.class.getClassLoader()); "org.springframework.aop.scope.ScopedObject", TransactionSynchronizationUtils.class.getClassLoader());
@ -67,7 +67,7 @@ public abstract class TransactionSynchronizationUtils {
if (resourceRef instanceof InfrastructureProxy infrastructureProxy) { if (resourceRef instanceof InfrastructureProxy infrastructureProxy) {
resourceRef = infrastructureProxy.getWrappedObject(); resourceRef = infrastructureProxy.getWrappedObject();
} }
if (aopPresent) { if (SPRING_AOP_PRESENT) {
// now unwrap scoped proxy // now unwrap scoped proxy
resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef); resourceRef = ScopedProxyUnwrapper.unwrapIfNecessary(resourceRef);
} }

94
spring-web/src/main/java/org/springframework/http/codec/support/BaseDefaultCodecs.java

@ -89,39 +89,39 @@ import org.springframework.util.ObjectUtils;
*/ */
class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigurer.DefaultCodecConfig { class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigurer.DefaultCodecConfig {
static final boolean jacksonPresent; static final boolean JACKSON_PRESENT;
static final boolean jackson2Present; static final boolean JACKSON_2_PRESENT;
private static final boolean jacksonSmilePresent; private static final boolean JACKSON_SMILE_PRESENT;
private static final boolean jackson2SmilePresent; private static final boolean JACKSON_2_SMILE_PRESENT;
private static final boolean jaxb2Present; private static final boolean JAXB_2_PRESENT;
private static final boolean protobufPresent; private static final boolean PROTOBUF_PRESENT;
static final boolean nettyByteBufPresent; static final boolean NETTY_BYTE_BUF_PRESENT;
static final boolean kotlinSerializationCborPresent; static final boolean KOTLIN_SERIALIZATION_CBOR_PRESENT;
static final boolean kotlinSerializationJsonPresent; static final boolean KOTLIN_SERIALIZATION_JSON_PRESENT;
static final boolean kotlinSerializationProtobufPresent; static final boolean KOTLIN_SERIALIZATION_PROTOBUF_PRESENT;
static { static {
ClassLoader classLoader = BaseCodecConfigurer.class.getClassLoader(); ClassLoader classLoader = BaseCodecConfigurer.class.getClassLoader();
jacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jacksonSmilePresent = jacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader); JACKSON_SMILE_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader);
jackson2SmilePresent = jackson2Present && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader); JACKSON_2_SMILE_PRESENT = JACKSON_2_PRESENT && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
jaxb2Present = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader); JAXB_2_PRESENT = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader);
protobufPresent = ClassUtils.isPresent("com.google.protobuf.Message", classLoader); PROTOBUF_PRESENT = ClassUtils.isPresent("com.google.protobuf.Message", classLoader);
nettyByteBufPresent = ClassUtils.isPresent("io.netty.buffer.ByteBuf", classLoader); NETTY_BYTE_BUF_PRESENT = ClassUtils.isPresent("io.netty.buffer.ByteBuf", classLoader);
kotlinSerializationCborPresent = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader); KOTLIN_SERIALIZATION_CBOR_PRESENT = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader);
kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader); KOTLIN_SERIALIZATION_JSON_PRESENT = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
kotlinSerializationProtobufPresent = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader); KOTLIN_SERIALIZATION_PROTOBUF_PRESENT = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader);
} }
@ -448,12 +448,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new ByteArrayDecoder())); addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new ByteArrayDecoder()));
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new ByteBufferDecoder())); addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new ByteBufferDecoder()));
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new DataBufferDecoder())); addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new DataBufferDecoder()));
if (nettyByteBufPresent) { if (NETTY_BYTE_BUF_PRESENT) {
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new NettyByteBufDecoder())); addCodec(this.typedReaders, new DecoderHttpMessageReader<>(new NettyByteBufDecoder()));
} }
addCodec(this.typedReaders, new ResourceHttpMessageReader(new ResourceDecoder())); addCodec(this.typedReaders, new ResourceHttpMessageReader(new ResourceDecoder()));
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly())); addCodec(this.typedReaders, new DecoderHttpMessageReader<>(StringDecoder.textPlainOnly()));
if (protobufPresent) { if (PROTOBUF_PRESENT) {
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(this.protobufDecoder != null ? addCodec(this.typedReaders, new DecoderHttpMessageReader<>(this.protobufDecoder != null ?
(ProtobufDecoder) this.protobufDecoder : new ProtobufDecoder())); (ProtobufDecoder) this.protobufDecoder : new ProtobufDecoder()));
} }
@ -506,37 +506,37 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
} }
// Pattern variables in the following if-blocks cannot be named the same as instance fields // Pattern variables in the following if-blocks cannot be named the same as instance fields
// due to lacking support in Checkstyle: https://github.com/checkstyle/checkstyle/issues/10969 // due to lacking support in Checkstyle: https://github.com/checkstyle/checkstyle/issues/10969
if (protobufPresent) { if (PROTOBUF_PRESENT) {
if (codec instanceof ProtobufDecoder protobufDec) { if (codec instanceof ProtobufDecoder protobufDec) {
protobufDec.setMaxMessageSize(size); protobufDec.setMaxMessageSize(size);
} }
} }
if (kotlinSerializationCborPresent) { if (KOTLIN_SERIALIZATION_CBOR_PRESENT) {
if (codec instanceof KotlinSerializationCborDecoder kotlinSerializationCborDec) { if (codec instanceof KotlinSerializationCborDecoder kotlinSerializationCborDec) {
kotlinSerializationCborDec.setMaxInMemorySize(size); kotlinSerializationCborDec.setMaxInMemorySize(size);
} }
} }
if (kotlinSerializationJsonPresent) { if (KOTLIN_SERIALIZATION_JSON_PRESENT) {
if (codec instanceof KotlinSerializationJsonDecoder kotlinSerializationJsonDec) { if (codec instanceof KotlinSerializationJsonDecoder kotlinSerializationJsonDec) {
kotlinSerializationJsonDec.setMaxInMemorySize(size); kotlinSerializationJsonDec.setMaxInMemorySize(size);
} }
} }
if (kotlinSerializationProtobufPresent) { if (KOTLIN_SERIALIZATION_PROTOBUF_PRESENT) {
if (codec instanceof KotlinSerializationProtobufDecoder kotlinSerializationProtobufDec) { if (codec instanceof KotlinSerializationProtobufDecoder kotlinSerializationProtobufDec) {
kotlinSerializationProtobufDec.setMaxInMemorySize(size); kotlinSerializationProtobufDec.setMaxInMemorySize(size);
} }
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
if (codec instanceof AbstractJacksonDecoder<?> abstractJacksonDecoder) { if (codec instanceof AbstractJacksonDecoder<?> abstractJacksonDecoder) {
abstractJacksonDecoder.setMaxInMemorySize(size); abstractJacksonDecoder.setMaxInMemorySize(size);
} }
} }
if (jackson2Present) { if (JACKSON_2_PRESENT) {
if (codec instanceof AbstractJackson2Decoder abstractJackson2Decoder) { if (codec instanceof AbstractJackson2Decoder abstractJackson2Decoder) {
abstractJackson2Decoder.setMaxInMemorySize(size); abstractJackson2Decoder.setMaxInMemorySize(size);
} }
} }
if (jaxb2Present) { if (JAXB_2_PRESENT) {
if (codec instanceof Jaxb2XmlDecoder jaxb2XmlDecoder) { if (codec instanceof Jaxb2XmlDecoder jaxb2XmlDecoder) {
jaxb2XmlDecoder.setMaxInMemorySize(size); jaxb2XmlDecoder.setMaxInMemorySize(size);
} }
@ -619,35 +619,35 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
if (!this.registerDefaults) { if (!this.registerDefaults) {
return; return;
} }
if (kotlinSerializationCborPresent) { if (KOTLIN_SERIALIZATION_CBOR_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.kotlinSerializationCborDecoder != null ? addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.kotlinSerializationCborDecoder != null ?
(KotlinSerializationCborDecoder) this.kotlinSerializationCborDecoder : (KotlinSerializationCborDecoder) this.kotlinSerializationCborDecoder :
new KotlinSerializationCborDecoder())); new KotlinSerializationCborDecoder()));
} }
if (kotlinSerializationProtobufPresent) { if (KOTLIN_SERIALIZATION_PROTOBUF_PRESENT) {
addCodec(this.objectReaders, addCodec(this.objectReaders,
new DecoderHttpMessageReader<>(this.kotlinSerializationProtobufDecoder != null ? new DecoderHttpMessageReader<>(this.kotlinSerializationProtobufDecoder != null ?
(KotlinSerializationProtobufDecoder) this.kotlinSerializationProtobufDecoder : (KotlinSerializationProtobufDecoder) this.kotlinSerializationProtobufDecoder :
new KotlinSerializationProtobufDecoder())); new KotlinSerializationProtobufDecoder()));
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getJacksonJsonDecoder())); addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getJacksonJsonDecoder()));
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getJackson2JsonDecoder())); addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getJackson2JsonDecoder()));
} }
else if (kotlinSerializationJsonPresent) { else if (KOTLIN_SERIALIZATION_JSON_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getKotlinSerializationJsonDecoder())); addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getKotlinSerializationJsonDecoder()));
} }
if (jacksonSmilePresent) { if (JACKSON_SMILE_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jacksonSmileDecoder != null ? addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jacksonSmileDecoder != null ?
(JacksonSmileDecoder) this.jacksonSmileDecoder : new JacksonSmileDecoder())); (JacksonSmileDecoder) this.jacksonSmileDecoder : new JacksonSmileDecoder()));
} }
else if (jackson2SmilePresent) { else if (JACKSON_2_SMILE_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jackson2SmileDecoder != null ? addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jackson2SmileDecoder != null ?
(Jackson2SmileDecoder) this.jackson2SmileDecoder : new Jackson2SmileDecoder())); (Jackson2SmileDecoder) this.jackson2SmileDecoder : new Jackson2SmileDecoder()));
} }
if (jaxb2Present) { if (JAXB_2_PRESENT) {
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jaxb2Decoder != null ? addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.jaxb2Decoder != null ?
(Jaxb2XmlDecoder) this.jaxb2Decoder : new Jaxb2XmlDecoder())); (Jaxb2XmlDecoder) this.jaxb2Decoder : new Jaxb2XmlDecoder()));
} }
@ -705,12 +705,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
addCodec(writers, new EncoderHttpMessageWriter<>(new ByteArrayEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(new ByteArrayEncoder()));
addCodec(writers, new EncoderHttpMessageWriter<>(new ByteBufferEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
addCodec(writers, new EncoderHttpMessageWriter<>(new DataBufferEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(new DataBufferEncoder()));
if (nettyByteBufPresent) { if (NETTY_BYTE_BUF_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(new NettyByteBufEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(new NettyByteBufEncoder()));
} }
addCodec(writers, new ResourceHttpMessageWriter()); addCodec(writers, new ResourceHttpMessageWriter());
addCodec(writers, new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly())); addCodec(writers, new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
if (protobufPresent) { if (PROTOBUF_PRESENT) {
addCodec(writers, new ProtobufHttpMessageWriter(this.protobufEncoder != null ? addCodec(writers, new ProtobufHttpMessageWriter(this.protobufEncoder != null ?
(ProtobufEncoder) this.protobufEncoder : new ProtobufEncoder())); (ProtobufEncoder) this.protobufEncoder : new ProtobufEncoder()));
} }
@ -765,34 +765,34 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
@SuppressWarnings("removal") @SuppressWarnings("removal")
final List<HttpMessageWriter<?>> getBaseObjectWriters() { final List<HttpMessageWriter<?>> getBaseObjectWriters() {
List<HttpMessageWriter<?>> writers = new ArrayList<>(); List<HttpMessageWriter<?>> writers = new ArrayList<>();
if (kotlinSerializationCborPresent) { if (KOTLIN_SERIALIZATION_CBOR_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationCborEncoder != null ? addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationCborEncoder != null ?
(KotlinSerializationCborEncoder) this.kotlinSerializationCborEncoder : (KotlinSerializationCborEncoder) this.kotlinSerializationCborEncoder :
new KotlinSerializationCborEncoder())); new KotlinSerializationCborEncoder()));
} }
if (kotlinSerializationProtobufPresent) { if (KOTLIN_SERIALIZATION_PROTOBUF_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationProtobufEncoder != null ? addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationProtobufEncoder != null ?
(KotlinSerializationProtobufEncoder) this.kotlinSerializationProtobufEncoder : (KotlinSerializationProtobufEncoder) this.kotlinSerializationProtobufEncoder :
new KotlinSerializationProtobufEncoder())); new KotlinSerializationProtobufEncoder()));
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(getJacksonJsonEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(getJacksonJsonEncoder()));
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(getJackson2JsonEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(getJackson2JsonEncoder()));
} }
else if (kotlinSerializationJsonPresent) { else if (KOTLIN_SERIALIZATION_JSON_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(getKotlinSerializationJsonEncoder())); addCodec(writers, new EncoderHttpMessageWriter<>(getKotlinSerializationJsonEncoder()));
} }
if (jacksonSmilePresent) { if (JACKSON_SMILE_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(this.jacksonSmileEncoder != null ? addCodec(writers, new EncoderHttpMessageWriter<>(this.jacksonSmileEncoder != null ?
(JacksonSmileEncoder) this.jacksonSmileEncoder : new JacksonSmileEncoder())); (JacksonSmileEncoder) this.jacksonSmileEncoder : new JacksonSmileEncoder()));
} }
else if (jackson2SmilePresent) { else if (JACKSON_2_SMILE_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(this.jackson2SmileEncoder != null ? addCodec(writers, new EncoderHttpMessageWriter<>(this.jackson2SmileEncoder != null ?
(Jackson2SmileEncoder) this.jackson2SmileEncoder : new Jackson2SmileEncoder())); (Jackson2SmileEncoder) this.jackson2SmileEncoder : new Jackson2SmileEncoder()));
} }
if (jaxb2Present) { if (JAXB_2_PRESENT) {
addCodec(writers, new EncoderHttpMessageWriter<>(this.jaxb2Encoder != null ? addCodec(writers, new EncoderHttpMessageWriter<>(this.jaxb2Encoder != null ?
(Jaxb2XmlEncoder) this.jaxb2Encoder : new Jaxb2XmlEncoder())); (Jaxb2XmlEncoder) this.jaxb2Encoder : new Jaxb2XmlEncoder()));
} }

6
spring-web/src/main/java/org/springframework/http/codec/support/ClientDefaultCodecsImpl.java

@ -53,9 +53,9 @@ class ClientDefaultCodecsImpl extends BaseDefaultCodecs implements ClientCodecCo
protected void extendObjectReaders(List<HttpMessageReader<?>> objectReaders) { protected void extendObjectReaders(List<HttpMessageReader<?>> objectReaders) {
Decoder<?> decoder = (this.sseDecoder != null ? this.sseDecoder : Decoder<?> decoder = (this.sseDecoder != null ? this.sseDecoder :
jacksonPresent ? getJacksonJsonDecoder() : JACKSON_PRESENT ? getJacksonJsonDecoder() :
jackson2Present ? getJackson2JsonDecoder() : JACKSON_2_PRESENT ? getJackson2JsonDecoder() :
kotlinSerializationJsonPresent ? getKotlinSerializationJsonDecoder() : KOTLIN_SERIALIZATION_JSON_PRESENT ? getKotlinSerializationJsonDecoder() :
null); null);
addCodec(objectReaders, new ServerSentEventHttpMessageReader(decoder)); addCodec(objectReaders, new ServerSentEventHttpMessageReader(decoder));

6
spring-web/src/main/java/org/springframework/http/codec/support/ServerDefaultCodecsImpl.java

@ -57,9 +57,9 @@ class ServerDefaultCodecsImpl extends BaseDefaultCodecs implements ServerCodecCo
private @Nullable Encoder<?> getSseEncoder() { private @Nullable Encoder<?> getSseEncoder() {
return this.sseEncoder != null ? this.sseEncoder : return this.sseEncoder != null ? this.sseEncoder :
jacksonPresent ? getJacksonJsonEncoder() : JACKSON_PRESENT ? getJacksonJsonEncoder() :
jackson2Present ? getJackson2JsonEncoder() : JACKSON_2_PRESENT ? getJackson2JsonEncoder() :
kotlinSerializationJsonPresent ? getKotlinSerializationJsonEncoder() : KOTLIN_SERIALIZATION_JSON_PRESENT ? getKotlinSerializationJsonEncoder() :
null; null;
} }

4
spring-web/src/main/java/org/springframework/http/codec/xml/XmlEventDecoder.java

@ -86,10 +86,10 @@ public class XmlEventDecoder extends AbstractDecoder<XMLEvent> {
private static final XMLInputFactory inputFactory = StaxUtils.createDefensiveInputFactory(); private static final XMLInputFactory inputFactory = StaxUtils.createDefensiveInputFactory();
private static final boolean aaltoPresent = ClassUtils.isPresent( private static final boolean AALTO_PRESENT = ClassUtils.isPresent(
"com.fasterxml.aalto.AsyncXMLStreamReader", XmlEventDecoder.class.getClassLoader()); "com.fasterxml.aalto.AsyncXMLStreamReader", XmlEventDecoder.class.getClassLoader());
boolean useAalto = aaltoPresent; boolean useAalto = AALTO_PRESENT;
private int maxInMemorySize = 256 * 1024; private int maxInMemorySize = 256 * 1024;

102
spring-web/src/main/java/org/springframework/http/converter/DefaultHttpMessageConverters.java

@ -68,39 +68,39 @@ class DefaultHttpMessageConverters implements HttpMessageConverters {
abstract static class DefaultBuilder { abstract static class DefaultBuilder {
private static final boolean isJacksonPresent; private static final boolean JACKSON_PRESENT;
private static final boolean isJackson2Present; private static final boolean JACKSON_2_PRESENT;
private static final boolean isGsonPresent; private static final boolean GSON_PRESENT;
private static final boolean isJsonbPresent; private static final boolean JSONB_PRESENT;
private static final boolean isKotlinSerializationJsonPresent; private static final boolean KOTLIN_SERIALIZATION_JSON_PRESENT;
private static final boolean isJacksonXmlPresent; private static final boolean JACKSON_XML_PRESENT;
private static final boolean isJackson2XmlPresent; private static final boolean JACKSON_2_XML_PRESENT;
private static final boolean isJaxb2Present; private static final boolean JAXB_2_PRESENT;
private static final boolean isJacksonSmilePresent; private static final boolean JACKSON_SMILE_PRESENT;
private static final boolean isJackson2SmilePresent; private static final boolean JACKSON_2_SMILE_PRESENT;
private static final boolean isJacksonCborPresent; private static final boolean JACKSON_CBOR_PRESENT;
private static final boolean isJackson2CborPresent; private static final boolean JACKSON_2_CBOR_PRESENT;
private static final boolean isKotlinSerializationCborPresent; private static final boolean KOTLIN_SERIALIZATION_CBOR_PRESENT;
private static final boolean isJacksonYamlPresent; private static final boolean JACKSON_YAML_PRESENT;
private static final boolean isJackson2YamlPresent; private static final boolean JACKSON_2_YAML_PRESENT;
private static final boolean isKotlinSerializationProtobufPresent; private static final boolean KOTLIN_SERIALIZATION_PROTOBUF_PRESENT;
private static final boolean isRomePresent; private static final boolean ROME_PRESENT;
boolean registerDefaults; boolean registerDefaults;
@ -135,24 +135,24 @@ class DefaultHttpMessageConverters implements HttpMessageConverters {
static { static {
ClassLoader classLoader = DefaultBuilder.class.getClassLoader(); ClassLoader classLoader = DefaultBuilder.class.getClassLoader();
isJacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
isJackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
isGsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); GSON_PRESENT = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
isJsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader); JSONB_PRESENT = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
isKotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader); KOTLIN_SERIALIZATION_JSON_PRESENT = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
isJacksonSmilePresent = isJacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader); JACKSON_SMILE_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader);
isJackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader); JACKSON_2_SMILE_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
isJaxb2Present = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader); JAXB_2_PRESENT = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader);
isJacksonXmlPresent = isJacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.xml.XmlMapper", classLoader); JACKSON_XML_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.xml.XmlMapper", classLoader);
isJackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader); JACKSON_2_XML_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
isJacksonCborPresent = isJacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.cbor.CBORMapper", classLoader); JACKSON_CBOR_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.cbor.CBORMapper", classLoader);
isJackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader); JACKSON_2_CBOR_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
isJacksonYamlPresent = isJacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.yaml.YAMLMapper", classLoader); JACKSON_YAML_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.yaml.YAMLMapper", classLoader);
isJackson2YamlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.yaml.YAMLFactory", classLoader); JACKSON_2_YAML_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.yaml.YAMLFactory", classLoader);
isKotlinSerializationCborPresent = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader); KOTLIN_SERIALIZATION_CBOR_PRESENT = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader);
isKotlinSerializationProtobufPresent = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader); KOTLIN_SERIALIZATION_PROTOBUF_PRESENT = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader);
isRomePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader); ROME_PRESENT = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader);
} }
@ -250,72 +250,72 @@ class DefaultHttpMessageConverters implements HttpMessageConverters {
this.stringMessageConverter = new StringHttpMessageConverter(); this.stringMessageConverter = new StringHttpMessageConverter();
if (this.jsonMessageConverter == null) { if (this.jsonMessageConverter == null) {
if (isJacksonPresent) { if (JACKSON_PRESENT) {
this.jsonMessageConverter = new JacksonJsonHttpMessageConverter(); this.jsonMessageConverter = new JacksonJsonHttpMessageConverter();
} }
else if (isJackson2Present) { else if (JACKSON_2_PRESENT) {
this.jsonMessageConverter = new MappingJackson2HttpMessageConverter(); this.jsonMessageConverter = new MappingJackson2HttpMessageConverter();
} }
else if (isGsonPresent) { else if (GSON_PRESENT) {
this.jsonMessageConverter = new GsonHttpMessageConverter(); this.jsonMessageConverter = new GsonHttpMessageConverter();
} }
else if (isJsonbPresent) { else if (JSONB_PRESENT) {
this.jsonMessageConverter = new JsonbHttpMessageConverter(); this.jsonMessageConverter = new JsonbHttpMessageConverter();
} }
else if (isKotlinSerializationJsonPresent) { else if (KOTLIN_SERIALIZATION_JSON_PRESENT) {
this.jsonMessageConverter = new KotlinSerializationJsonHttpMessageConverter(); this.jsonMessageConverter = new KotlinSerializationJsonHttpMessageConverter();
} }
} }
if (this.xmlMessageConverter == null) { if (this.xmlMessageConverter == null) {
if (isJacksonXmlPresent) { if (JACKSON_XML_PRESENT) {
this.xmlMessageConverter = new JacksonXmlHttpMessageConverter(); this.xmlMessageConverter = new JacksonXmlHttpMessageConverter();
} }
else if (isJackson2XmlPresent) { else if (JACKSON_2_XML_PRESENT) {
this.xmlMessageConverter = new MappingJackson2XmlHttpMessageConverter(); this.xmlMessageConverter = new MappingJackson2XmlHttpMessageConverter();
} }
else if (isJaxb2Present) { else if (JAXB_2_PRESENT) {
this.xmlMessageConverter = new Jaxb2RootElementHttpMessageConverter(); this.xmlMessageConverter = new Jaxb2RootElementHttpMessageConverter();
} }
} }
if (this.smileMessageConverter == null) { if (this.smileMessageConverter == null) {
if (isJacksonSmilePresent) { if (JACKSON_SMILE_PRESENT) {
this.smileMessageConverter = new JacksonSmileHttpMessageConverter(); this.smileMessageConverter = new JacksonSmileHttpMessageConverter();
} }
else if (isJackson2SmilePresent) { else if (JACKSON_2_SMILE_PRESENT) {
this.smileMessageConverter = new MappingJackson2SmileHttpMessageConverter(); this.smileMessageConverter = new MappingJackson2SmileHttpMessageConverter();
} }
} }
if (this.cborMessageConverter == null) { if (this.cborMessageConverter == null) {
if (isJacksonCborPresent) { if (JACKSON_CBOR_PRESENT) {
this.cborMessageConverter = new JacksonCborHttpMessageConverter(); this.cborMessageConverter = new JacksonCborHttpMessageConverter();
} }
else if (isJackson2CborPresent) { else if (JACKSON_2_CBOR_PRESENT) {
this.cborMessageConverter = new MappingJackson2CborHttpMessageConverter(); this.cborMessageConverter = new MappingJackson2CborHttpMessageConverter();
} }
else if (isKotlinSerializationCborPresent) { else if (KOTLIN_SERIALIZATION_CBOR_PRESENT) {
this.cborMessageConverter = new KotlinSerializationCborHttpMessageConverter(); this.cborMessageConverter = new KotlinSerializationCborHttpMessageConverter();
} }
} }
if (this.yamlMessageConverter == null) { if (this.yamlMessageConverter == null) {
if (isJacksonYamlPresent) { if (JACKSON_YAML_PRESENT) {
this.yamlMessageConverter = new JacksonYamlHttpMessageConverter(); this.yamlMessageConverter = new JacksonYamlHttpMessageConverter();
} }
else if (isJackson2YamlPresent) { else if (JACKSON_2_YAML_PRESENT) {
this.yamlMessageConverter = new MappingJackson2YamlHttpMessageConverter(); this.yamlMessageConverter = new MappingJackson2YamlHttpMessageConverter();
} }
} }
if (this.protobufMessageConverter == null) { if (this.protobufMessageConverter == null) {
if (isKotlinSerializationProtobufPresent) { if (KOTLIN_SERIALIZATION_PROTOBUF_PRESENT) {
this.protobufMessageConverter = new KotlinSerializationProtobufHttpMessageConverter(); this.protobufMessageConverter = new KotlinSerializationProtobufHttpMessageConverter();
} }
} }
if (isRomePresent) { if (ROME_PRESENT) {
if (this.atomMessageConverter == null) { if (this.atomMessageConverter == null) {
this.atomMessageConverter = new AtomFeedHttpMessageConverter(); this.atomMessageConverter = new AtomFeedHttpMessageConverter();
} }

4
spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java

@ -106,7 +106,7 @@ import org.springframework.util.xml.StaxUtils;
@SuppressWarnings("removal") @SuppressWarnings("removal")
public class Jackson2ObjectMapperBuilder { public class Jackson2ObjectMapperBuilder {
private static final boolean jackson2XmlPresent = ClassUtils.isPresent( private static final boolean JACKSON_2_XML_PRESENT = ClassUtils.isPresent(
"com.fasterxml.jackson.dataformat.xml.XmlMapper", Jackson2ObjectMapperBuilder.class.getClassLoader()); "com.fasterxml.jackson.dataformat.xml.XmlMapper", Jackson2ObjectMapperBuilder.class.getClassLoader());
@ -747,7 +747,7 @@ public class Jackson2ObjectMapperBuilder {
objectMapper.setFilterProvider(this.filters); objectMapper.setFilterProvider(this.filters);
} }
if (jackson2XmlPresent) { if (JACKSON_2_XML_PRESENT) {
objectMapper.addMixIn(ProblemDetail.class, ProblemDetailJacksonXmlMixin.class); objectMapper.addMixIn(ProblemDetail.class, ProblemDetailJacksonXmlMixin.class);
} }
else { else {

5
spring-web/src/main/java/org/springframework/http/converter/protobuf/ProtobufHttpMessageConverter.java

@ -97,7 +97,8 @@ public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<M
*/ */
public static final String X_PROTOBUF_MESSAGE_HEADER = "X-Protobuf-Message"; public static final String X_PROTOBUF_MESSAGE_HEADER = "X-Protobuf-Message";
private static final boolean protobufJsonFormatPresent = ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", ProtobufHttpMessageConverter.class.getClassLoader()); private static final boolean PROTOBUF_JSON_FORMAT_PRESENT =
ClassUtils.isPresent("com.google.protobuf.util.JsonFormat", ProtobufHttpMessageConverter.class.getClassLoader());
private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>(); private static final Map<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>();
@ -129,7 +130,7 @@ public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<M
if (formatSupport != null) { if (formatSupport != null) {
this.protobufFormatSupport = formatSupport; this.protobufFormatSupport = formatSupport;
} }
else if (protobufJsonFormatPresent) { else if (PROTOBUF_JSON_FORMAT_PRESENT) {
this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null); this.protobufFormatSupport = new ProtobufJavaUtilSupport(null, null);
} }
else { else {

24
spring-web/src/main/java/org/springframework/web/client/DefaultRestClientBuilder.java

@ -66,21 +66,21 @@ final class DefaultRestClientBuilder implements RestClient.Builder {
// request factories // request factories
private static final boolean httpComponentsClientPresent; private static final boolean HTTP_COMPONENTS_CLIENT_PRESENT;
private static final boolean jettyClientPresent; private static final boolean JETTY_CLIENT_PRESENT;
private static final boolean reactorNettyClientPresent; private static final boolean REACTOR_NETTY_CLIENT_PRESENT;
private static final boolean jdkClientPresent; private static final boolean JDK_CLIENT_PRESENT;
static { static {
ClassLoader loader = DefaultRestClientBuilder.class.getClassLoader(); ClassLoader loader = DefaultRestClientBuilder.class.getClassLoader();
httpComponentsClientPresent = ClassUtils.isPresent("org.apache.hc.client5.http.classic.HttpClient", loader); HTTP_COMPONENTS_CLIENT_PRESENT = ClassUtils.isPresent("org.apache.hc.client5.http.classic.HttpClient", loader);
jettyClientPresent = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader); JETTY_CLIENT_PRESENT = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader);
reactorNettyClientPresent = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader); REACTOR_NETTY_CLIENT_PRESENT = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader);
jdkClientPresent = ClassUtils.isPresent("java.net.http.HttpClient", loader); JDK_CLIENT_PRESENT = ClassUtils.isPresent("java.net.http.HttpClient", loader);
} }
private @Nullable String baseUrl; private @Nullable String baseUrl;
@ -449,16 +449,16 @@ final class DefaultRestClientBuilder implements RestClient.Builder {
if (this.requestFactory != null) { if (this.requestFactory != null) {
return this.requestFactory; return this.requestFactory;
} }
else if (httpComponentsClientPresent) { else if (HTTP_COMPONENTS_CLIENT_PRESENT) {
return new HttpComponentsClientHttpRequestFactory(); return new HttpComponentsClientHttpRequestFactory();
} }
else if (jettyClientPresent) { else if (JETTY_CLIENT_PRESENT) {
return new JettyClientHttpRequestFactory(); return new JettyClientHttpRequestFactory();
} }
else if (reactorNettyClientPresent) { else if (REACTOR_NETTY_CLIENT_PRESENT) {
return new ReactorClientHttpRequestFactory(); return new ReactorClientHttpRequestFactory();
} }
else if (jdkClientPresent) { else if (JDK_CLIENT_PRESENT) {
// java.net.http module might not be loaded, so we can't default to the JDK HttpClient // java.net.http module might not be loaded, so we can't default to the JDK HttpClient
return new JdkClientHttpRequestFactory(); return new JdkClientHttpRequestFactory();
} }

4
spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java

@ -44,7 +44,7 @@ import org.springframework.util.ClassUtils;
*/ */
public abstract class RequestContextHolder { public abstract class RequestContextHolder {
private static final boolean jsfPresent = private static final boolean JSF_PRESENT =
ClassUtils.isPresent("jakarta.faces.context.FacesContext", RequestContextHolder.class.getClassLoader()); ClassUtils.isPresent("jakarta.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
@ -123,7 +123,7 @@ public abstract class RequestContextHolder {
public static RequestAttributes currentRequestAttributes() throws IllegalStateException { public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
RequestAttributes attributes = getRequestAttributes(); RequestAttributes attributes = getRequestAttributes();
if (attributes == null) { if (attributes == null) {
if (jsfPresent) { if (JSF_PRESENT) {
attributes = FacesRequestAttributesFactory.getFacesRequestAttributes(); attributes = FacesRequestAttributesFactory.getFacesRequestAttributes();
} }
if (attributes == null) { if (attributes == null) {

4
spring-web/src/main/java/org/springframework/web/context/support/StandardServletEnvironment.java

@ -57,7 +57,7 @@ public class StandardServletEnvironment extends StandardEnvironment implements C
// Defensive reference to JNDI API for JDK 9+ (optional java.naming module) // Defensive reference to JNDI API for JDK 9+ (optional java.naming module)
private static final boolean jndiPresent = ClassUtils.isPresent( private static final boolean JNDI_PRESENT = ClassUtils.isPresent(
"javax.naming.InitialContext", StandardServletEnvironment.class.getClassLoader()); "javax.naming.InitialContext", StandardServletEnvironment.class.getClassLoader());
@ -109,7 +109,7 @@ public class StandardServletEnvironment extends StandardEnvironment implements C
protected void customizePropertySources(MutablePropertySources propertySources) { protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME)); propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME));
propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)); propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME));
if (jndiPresent && JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) { if (JNDI_PRESENT && JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) {
propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME)); propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME));
} }
super.customizePropertySources(propertySources); super.customizePropertySources(propertySources);

4
spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java

@ -65,7 +65,7 @@ import org.springframework.web.context.request.WebRequest;
*/ */
public abstract class WebApplicationContextUtils { public abstract class WebApplicationContextUtils {
private static final boolean jsfPresent = private static final boolean JSF_PRESENT =
ClassUtils.isPresent("jakarta.faces.context.FacesContext", RequestContextHolder.class.getClassLoader()); ClassUtils.isPresent("jakarta.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());
@ -193,7 +193,7 @@ public abstract class WebApplicationContextUtils {
beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory()); beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
if (jsfPresent) { if (JSF_PRESENT) {
FacesDependencyRegistrar.registerFacesDependencies(beanFactory); FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
} }
} }

4
spring-webflux/src/main/java/org/springframework/web/reactive/config/ResourceChainRegistration.java

@ -44,7 +44,7 @@ public class ResourceChainRegistration {
private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache"; private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache";
private static final boolean webJarsPresent = ClassUtils.isPresent( private static final boolean WEB_JARS_PRESENT = ClassUtils.isPresent(
"org.webjars.WebJarVersionLocator", ResourceChainRegistration.class.getClassLoader()); "org.webjars.WebJarVersionLocator", ResourceChainRegistration.class.getClassLoader());
@ -113,7 +113,7 @@ public class ResourceChainRegistration {
protected List<ResourceResolver> getResourceResolvers() { protected List<ResourceResolver> getResourceResolvers() {
if (!this.hasPathResolver) { if (!this.hasPathResolver) {
List<ResourceResolver> result = new ArrayList<>(this.resolvers); List<ResourceResolver> result = new ArrayList<>(this.resolvers);
if (webJarsPresent && !this.hasWebjarsResolver) { if (WEB_JARS_PRESENT && !this.hasWebjarsResolver) {
result.add(new LiteWebJarsResourceResolver()); result.add(new LiteWebJarsResourceResolver());
} }
result.add(new PathResourceResolver()); result.add(new PathResourceResolver());

4
spring-webflux/src/main/java/org/springframework/web/reactive/config/WebFluxConfigurationSupport.java

@ -88,7 +88,7 @@ import org.springframework.web.server.i18n.LocaleContextResolver;
*/ */
public class WebFluxConfigurationSupport implements ApplicationContextAware { public class WebFluxConfigurationSupport implements ApplicationContextAware {
private static final boolean jakartaValidatorPresent = private static final boolean BEAN_VALIDATION_PRESENT =
ClassUtils.isPresent("jakarta.validation.Validator", WebFluxConfigurationSupport.class.getClassLoader()); ClassUtils.isPresent("jakarta.validation.Validator", WebFluxConfigurationSupport.class.getClassLoader());
@ -429,7 +429,7 @@ public class WebFluxConfigurationSupport implements ApplicationContextAware {
public Validator webFluxValidator() { public Validator webFluxValidator() {
Validator validator = getValidator(); Validator validator = getValidator();
if (validator == null) { if (validator == null) {
if (jakartaValidatorPresent) { if (BEAN_VALIDATION_PRESENT) {
try { try {
validator = new OptionalValidatorFactoryBean(); validator = new OptionalValidatorFactoryBean();
} }

18
spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientBuilder.java

@ -55,17 +55,17 @@ import org.springframework.web.util.UriBuilderFactory;
*/ */
final class DefaultWebClientBuilder implements WebClient.Builder { final class DefaultWebClientBuilder implements WebClient.Builder {
private static final boolean reactorNettyClientPresent; private static final boolean REACTOR_NETTY_CLIENT_PRESENT;
private static final boolean jettyClientPresent; private static final boolean JETTY_CLIENT_PRESENT;
private static final boolean httpComponentsClientPresent; private static final boolean HTTP_COMPONENTS_CLIENT_PRESENT;
static { static {
ClassLoader loader = DefaultWebClientBuilder.class.getClassLoader(); ClassLoader loader = DefaultWebClientBuilder.class.getClassLoader();
reactorNettyClientPresent = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader); REACTOR_NETTY_CLIENT_PRESENT = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader);
jettyClientPresent = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader); JETTY_CLIENT_PRESENT = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader);
httpComponentsClientPresent = HTTP_COMPONENTS_CLIENT_PRESENT =
ClassUtils.isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) && ClassUtils.isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) &&
ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader); ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader);
} }
@ -325,13 +325,13 @@ final class DefaultWebClientBuilder implements WebClient.Builder {
} }
private ClientHttpConnector initConnector() { private ClientHttpConnector initConnector() {
if (reactorNettyClientPresent) { if (REACTOR_NETTY_CLIENT_PRESENT) {
return new ReactorClientHttpConnector(); return new ReactorClientHttpConnector();
} }
else if (jettyClientPresent) { else if (JETTY_CLIENT_PRESENT) {
return new JettyClientHttpConnector(); return new JettyClientHttpConnector();
} }
else if (httpComponentsClientPresent) { else if (HTTP_COMPONENTS_CLIENT_PRESENT) {
return new HttpComponentsClientHttpConnector(); return new HttpComponentsClientHttpConnector();
} }
else { else {

18
spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/support/HandshakeWebSocketService.java

@ -74,19 +74,19 @@ public class HandshakeWebSocketService implements WebSocketService, Lifecycle {
private static final Mono<Map<String, Object>> EMPTY_ATTRIBUTES = Mono.just(Collections.emptyMap()); private static final Mono<Map<String, Object>> EMPTY_ATTRIBUTES = Mono.just(Collections.emptyMap());
private static final boolean jettyWsPresent; private static final boolean JETTY_WS_PRESENT;
private static final boolean jettyCoreWsPresent; private static final boolean JETTY_CORE_WS_PRESENT;
private static final boolean reactorNettyPresent; private static final boolean REACTOR_NETTY_PRESENT;
static { static {
ClassLoader classLoader = HandshakeWebSocketService.class.getClassLoader(); ClassLoader classLoader = HandshakeWebSocketService.class.getClassLoader();
jettyWsPresent = ClassUtils.isPresent( JETTY_WS_PRESENT = ClassUtils.isPresent(
"org.eclipse.jetty.ee11.websocket.server.JettyWebSocketServerContainer", classLoader); "org.eclipse.jetty.ee11.websocket.server.JettyWebSocketServerContainer", classLoader);
jettyCoreWsPresent = ClassUtils.isPresent( JETTY_CORE_WS_PRESENT = ClassUtils.isPresent(
"org.eclipse.jetty.websocket.server.ServerWebSocketContainer", classLoader); "org.eclipse.jetty.websocket.server.ServerWebSocketContainer", classLoader);
reactorNettyPresent = ClassUtils.isPresent( REACTOR_NETTY_PRESENT = ClassUtils.isPresent(
"reactor.netty.http.server.HttpServerResponse", classLoader); "reactor.netty.http.server.HttpServerResponse", classLoader);
} }
@ -265,13 +265,13 @@ public class HandshakeWebSocketService implements WebSocketService, Lifecycle {
static RequestUpgradeStrategy initUpgradeStrategy() { static RequestUpgradeStrategy initUpgradeStrategy() {
if (jettyWsPresent) { if (JETTY_WS_PRESENT) {
return new JettyRequestUpgradeStrategy(); return new JettyRequestUpgradeStrategy();
} }
else if (jettyCoreWsPresent) { else if (JETTY_CORE_WS_PRESENT) {
return new JettyCoreRequestUpgradeStrategy(); return new JettyCoreRequestUpgradeStrategy();
} }
else if (reactorNettyPresent) { else if (REACTOR_NETTY_PRESENT) {
return new ReactorNettyRequestUpgradeStrategy(); return new ReactorNettyRequestUpgradeStrategy();
} }
else { else {

100
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java

@ -168,51 +168,51 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
public static final String CONTENT_NEGOTIATION_MANAGER_BEAN_NAME = "mvcContentNegotiationManager"; public static final String CONTENT_NEGOTIATION_MANAGER_BEAN_NAME = "mvcContentNegotiationManager";
private static final boolean javaxValidationPresent; private static final boolean BEAN_VALIDATION_PRESENT;
private static final boolean romePresent; private static final boolean ROME_PRESENT;
private static final boolean jaxb2Present; private static final boolean JAXB_2_PRESENT;
private static final boolean jacksonPresent; private static final boolean JACKSON_PRESENT;
private static final boolean jackson2Present; private static final boolean JACKSON_2_PRESENT;
private static final boolean jacksonXmlPresent; private static final boolean JACKSON_XML_PRESENT;
private static final boolean jackson2XmlPresent; private static final boolean JACKSON_2_XML_PRESENT;
private static final boolean jacksonSmilePresent; private static final boolean JACKSON_SMILE_PRESENT;
private static final boolean jackson2SmilePresent; private static final boolean JACKSON_2_SMILE_PRESENT;
private static final boolean jacksonCborPresent; private static final boolean JACKSON_CBOR_PRESENT;
private static final boolean jackson2CborPresent; private static final boolean JACKSON_2_CBOR_PRESENT;
private static final boolean jacksonYamlPresent; private static final boolean JACKSON_YAML_PRESENT;
private static final boolean jackson2YamlPresent; private static final boolean JACKSON_2_YAML_PRESENT;
private static final boolean gsonPresent; private static final boolean GSON_PRESENT;
static { static {
ClassLoader classLoader = AnnotationDrivenBeanDefinitionParser.class.getClassLoader(); ClassLoader classLoader = AnnotationDrivenBeanDefinitionParser.class.getClassLoader();
javaxValidationPresent = ClassUtils.isPresent("jakarta.validation.Validator", classLoader); BEAN_VALIDATION_PRESENT = ClassUtils.isPresent("jakarta.validation.Validator", classLoader);
romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader); ROME_PRESENT = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader);
jaxb2Present = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader); JAXB_2_PRESENT = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader);
jacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jacksonXmlPresent = jacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.xml.XmlMapper", classLoader); JACKSON_XML_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2XmlPresent = jackson2Present && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader); JACKSON_2_XML_PRESENT = JACKSON_2_PRESENT && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jacksonSmilePresent = jacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader); JACKSON_SMILE_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.smile.SmileMapper", classLoader);
jackson2SmilePresent = jackson2Present && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader); JACKSON_2_SMILE_PRESENT = JACKSON_2_PRESENT && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
jacksonCborPresent = jacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.cbor.CBORMapper", classLoader); JACKSON_CBOR_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.cbor.CBORMapper", classLoader);
jackson2CborPresent = jackson2Present && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader); JACKSON_2_CBOR_PRESENT = JACKSON_2_PRESENT && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
jacksonYamlPresent = jacksonPresent && ClassUtils.isPresent("tools.jackson.dataformat.yaml.YAMLMapper", classLoader); JACKSON_YAML_PRESENT = JACKSON_PRESENT && ClassUtils.isPresent("tools.jackson.dataformat.yaml.YAMLMapper", classLoader);
jackson2YamlPresent = jackson2Present && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.yaml.YAMLFactory", classLoader); JACKSON_2_YAML_PRESENT = JACKSON_2_PRESENT && ClassUtils.isPresent("com.fasterxml.jackson.dataformat.yaml.YAMLFactory", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); GSON_PRESENT = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
} }
@ -354,14 +354,14 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
} }
protected void addRequestBodyAdvice(RootBeanDefinition beanDef) { protected void addRequestBodyAdvice(RootBeanDefinition beanDef) {
if (jackson2Present) { if (JACKSON_2_PRESENT) {
beanDef.getPropertyValues().add("requestBodyAdvice", beanDef.getPropertyValues().add("requestBodyAdvice",
new RootBeanDefinition(JsonViewRequestBodyAdvice.class)); new RootBeanDefinition(JsonViewRequestBodyAdvice.class));
} }
} }
protected void addResponseBodyAdvice(RootBeanDefinition beanDef) { protected void addResponseBodyAdvice(RootBeanDefinition beanDef) {
if (jackson2Present) { if (JACKSON_2_PRESENT) {
beanDef.getPropertyValues().add("responseBodyAdvice", beanDef.getPropertyValues().add("responseBodyAdvice",
new RootBeanDefinition(JsonViewResponseBodyAdvice.class)); new RootBeanDefinition(JsonViewResponseBodyAdvice.class));
} }
@ -387,7 +387,7 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
if (element.hasAttribute("validator")) { if (element.hasAttribute("validator")) {
return new RuntimeBeanReference(element.getAttribute("validator")); return new RuntimeBeanReference(element.getAttribute("validator"));
} }
else if (javaxValidationPresent) { else if (BEAN_VALIDATION_PRESENT) {
RootBeanDefinition validatorDef = new RootBeanDefinition( RootBeanDefinition validatorDef = new RootBeanDefinition(
"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean"); "org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
validatorDef.setSource(source); validatorDef.setSource(source);
@ -463,23 +463,23 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
private Properties getDefaultMediaTypes() { private Properties getDefaultMediaTypes() {
Properties defaultMediaTypes = new Properties(); Properties defaultMediaTypes = new Properties();
if (romePresent) { if (ROME_PRESENT) {
defaultMediaTypes.put("atom", MediaType.APPLICATION_ATOM_XML_VALUE); defaultMediaTypes.put("atom", MediaType.APPLICATION_ATOM_XML_VALUE);
defaultMediaTypes.put("rss", MediaType.APPLICATION_RSS_XML_VALUE); defaultMediaTypes.put("rss", MediaType.APPLICATION_RSS_XML_VALUE);
} }
if (jaxb2Present || jacksonXmlPresent || jackson2XmlPresent) { if (JAXB_2_PRESENT || JACKSON_XML_PRESENT || JACKSON_2_XML_PRESENT) {
defaultMediaTypes.put("xml", MediaType.APPLICATION_XML_VALUE); defaultMediaTypes.put("xml", MediaType.APPLICATION_XML_VALUE);
} }
if (jacksonPresent || jackson2Present || gsonPresent) { if (JACKSON_PRESENT || JACKSON_2_PRESENT || GSON_PRESENT) {
defaultMediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE); defaultMediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
} }
if (jacksonSmilePresent || jackson2SmilePresent) { if (JACKSON_SMILE_PRESENT || JACKSON_2_SMILE_PRESENT) {
defaultMediaTypes.put("smile", "application/x-jackson-smile"); defaultMediaTypes.put("smile", "application/x-jackson-smile");
} }
if (jacksonCborPresent || jackson2CborPresent) { if (JACKSON_CBOR_PRESENT || JACKSON_2_CBOR_PRESENT) {
defaultMediaTypes.put("cbor", MediaType.APPLICATION_CBOR_VALUE); defaultMediaTypes.put("cbor", MediaType.APPLICATION_CBOR_VALUE);
} }
if (jacksonYamlPresent || jackson2YamlPresent) { if (JACKSON_YAML_PRESENT || JACKSON_2_YAML_PRESENT) {
defaultMediaTypes.put("yaml", MediaType.APPLICATION_YAML_VALUE); defaultMediaTypes.put("yaml", MediaType.APPLICATION_YAML_VALUE);
} }
return defaultMediaTypes; return defaultMediaTypes;
@ -585,15 +585,15 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
messageConverters.add(createConverterDefinition(ResourceRegionHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(ResourceRegionHttpMessageConverter.class, source));
messageConverters.add(createConverterDefinition(AllEncompassingFormHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(AllEncompassingFormHttpMessageConverter.class, source));
if (romePresent) { if (ROME_PRESENT) {
messageConverters.add(createConverterDefinition(AtomFeedHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(AtomFeedHttpMessageConverter.class, source));
messageConverters.add(createConverterDefinition(RssChannelHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(RssChannelHttpMessageConverter.class, source));
} }
if (jacksonXmlPresent) { if (JACKSON_XML_PRESENT) {
messageConverters.add(createConverterDefinition(JacksonXmlHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(JacksonXmlHttpMessageConverter.class, source));
} }
else if (jackson2XmlPresent) { else if (JACKSON_2_XML_PRESENT) {
Class<?> type = MappingJackson2XmlHttpMessageConverter.class; Class<?> type = MappingJackson2XmlHttpMessageConverter.class;
RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source); RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source);
GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source);
@ -601,28 +601,28 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef); jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef);
messageConverters.add(jacksonConverterDef); messageConverters.add(jacksonConverterDef);
} }
else if (jaxb2Present) { else if (JAXB_2_PRESENT) {
messageConverters.add(createConverterDefinition(Jaxb2RootElementHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(Jaxb2RootElementHttpMessageConverter.class, source));
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
messageConverters.add(createConverterDefinition(JacksonJsonHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(JacksonJsonHttpMessageConverter.class, source));
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
Class<?> type = MappingJackson2HttpMessageConverter.class; Class<?> type = MappingJackson2HttpMessageConverter.class;
RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source); RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source);
GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source);
jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef); jacksonConverterDef.getConstructorArgumentValues().addIndexedArgumentValue(0, jacksonFactoryDef);
messageConverters.add(jacksonConverterDef); messageConverters.add(jacksonConverterDef);
} }
else if (gsonPresent) { else if (GSON_PRESENT) {
messageConverters.add(createConverterDefinition(GsonHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(GsonHttpMessageConverter.class, source));
} }
if (jacksonSmilePresent) { if (JACKSON_SMILE_PRESENT) {
messageConverters.add(createConverterDefinition(JacksonSmileHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(JacksonSmileHttpMessageConverter.class, source));
} }
else if (jackson2SmilePresent) { else if (JACKSON_2_SMILE_PRESENT) {
Class<?> type = MappingJackson2SmileHttpMessageConverter.class; Class<?> type = MappingJackson2SmileHttpMessageConverter.class;
RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source); RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source);
GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source);
@ -631,10 +631,10 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
messageConverters.add(jacksonConverterDef); messageConverters.add(jacksonConverterDef);
} }
if (jacksonCborPresent) { if (JACKSON_CBOR_PRESENT) {
messageConverters.add(createConverterDefinition(JacksonCborHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(JacksonCborHttpMessageConverter.class, source));
} }
else if (jackson2CborPresent) { else if (JACKSON_2_CBOR_PRESENT) {
Class<?> type = MappingJackson2CborHttpMessageConverter.class; Class<?> type = MappingJackson2CborHttpMessageConverter.class;
RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source); RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source);
GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source);
@ -643,10 +643,10 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
messageConverters.add(jacksonConverterDef); messageConverters.add(jacksonConverterDef);
} }
if (jacksonYamlPresent) { if (JACKSON_YAML_PRESENT) {
messageConverters.add(createConverterDefinition(JacksonYamlHttpMessageConverter.class, source)); messageConverters.add(createConverterDefinition(JacksonYamlHttpMessageConverter.class, source));
} }
else if (jackson2YamlPresent) { else if (JACKSON_2_YAML_PRESENT) {
Class<?> type = MappingJackson2YamlHttpMessageConverter.class; Class<?> type = MappingJackson2YamlHttpMessageConverter.class;
RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source); RootBeanDefinition jacksonConverterDef = createConverterDefinition(type, source);
GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source); GenericBeanDefinition jacksonFactoryDef = createObjectMapperFactoryDefinition(source);

4
spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java

@ -81,7 +81,7 @@ class ResourcesBeanDefinitionParser implements BeanDefinitionParser {
private static final String RESOURCE_URL_PROVIDER = "mvcResourceUrlProvider"; private static final String RESOURCE_URL_PROVIDER = "mvcResourceUrlProvider";
private static final boolean webJarsPresent = ClassUtils.isPresent( private static final boolean WEB_JARS_PRESENT = ClassUtils.isPresent(
"org.webjars.WebJarVersionLocator", ResourcesBeanDefinitionParser.class.getClassLoader()); "org.webjars.WebJarVersionLocator", ResourcesBeanDefinitionParser.class.getClassLoader());
@ -325,7 +325,7 @@ class ResourcesBeanDefinitionParser implements BeanDefinitionParser {
} }
if (isAutoRegistration) { if (isAutoRegistration) {
if (webJarsPresent) { if (WEB_JARS_PRESENT) {
RootBeanDefinition webJarsResolverDef = new RootBeanDefinition(LiteWebJarsResourceResolver.class); RootBeanDefinition webJarsResolverDef = new RootBeanDefinition(LiteWebJarsResourceResolver.class);
webJarsResolverDef.setSource(source); webJarsResolverDef.setSource(source);
webJarsResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); webJarsResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

4
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java

@ -44,7 +44,7 @@ public class ResourceChainRegistration {
private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache"; private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache";
private static final boolean webJarsPresent = ClassUtils.isPresent( private static final boolean WEB_JARS_PRESENT = ClassUtils.isPresent(
"org.webjars.WebJarVersionLocator", ResourceChainRegistration.class.getClassLoader()); "org.webjars.WebJarVersionLocator", ResourceChainRegistration.class.getClassLoader());
@ -113,7 +113,7 @@ public class ResourceChainRegistration {
protected List<ResourceResolver> getResourceResolvers() { protected List<ResourceResolver> getResourceResolvers() {
if (!this.hasPathResolver) { if (!this.hasPathResolver) {
List<ResourceResolver> result = new ArrayList<>(this.resolvers); List<ResourceResolver> result = new ArrayList<>(this.resolvers);
if (webJarsPresent && !this.hasWebjarsResolver) { if (WEB_JARS_PRESENT && !this.hasWebjarsResolver) {
result.add(new LiteWebJarsResourceResolver()); result.add(new LiteWebJarsResourceResolver());
} }
result.add(new PathResourceResolver()); result.add(new PathResourceResolver());

24
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java

@ -180,19 +180,19 @@ import org.springframework.web.util.pattern.PathPatternParser;
*/ */
public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware { public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {
private static final boolean jacksonPresent; private static final boolean JACKSON_PRESENT;
private static final boolean jackson2Present; private static final boolean JACKSON_2_PRESENT;
private static final boolean kotlinSerializationPresent; private static final boolean KOTLIN_SERIALIZATION_PRESENT;
static { static {
ClassLoader classLoader = WebMvcConfigurationSupport.class.getClassLoader(); ClassLoader classLoader = WebMvcConfigurationSupport.class.getClassLoader();
jacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
kotlinSerializationPresent = ClassUtils.isPresent("kotlinx.serialization.Serializable", classLoader); KOTLIN_SERIALIZATION_PRESENT = ClassUtils.isPresent("kotlinx.serialization.Serializable", classLoader);
} }
@ -652,14 +652,14 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
adapter.setCustomReturnValueHandlers(getReturnValueHandlers()); adapter.setCustomReturnValueHandlers(getReturnValueHandlers());
adapter.setErrorResponseInterceptors(getErrorResponseInterceptors()); adapter.setErrorResponseInterceptors(getErrorResponseInterceptors());
if (jacksonPresent || jackson2Present || kotlinSerializationPresent) { if (JACKSON_PRESENT || JACKSON_2_PRESENT || KOTLIN_SERIALIZATION_PRESENT) {
List<RequestBodyAdvice> requestBodyAdvices = new ArrayList<>(2); List<RequestBodyAdvice> requestBodyAdvices = new ArrayList<>(2);
List<ResponseBodyAdvice<?>> responseBodyAdvices = new ArrayList<>(2); List<ResponseBodyAdvice<?>> responseBodyAdvices = new ArrayList<>(2);
if (jacksonPresent || jackson2Present) { if (JACKSON_PRESENT || JACKSON_2_PRESENT) {
requestBodyAdvices.add(new JsonViewRequestBodyAdvice()); requestBodyAdvices.add(new JsonViewRequestBodyAdvice());
responseBodyAdvices.add(new JsonViewResponseBodyAdvice()); responseBodyAdvices.add(new JsonViewResponseBodyAdvice());
} }
if (kotlinSerializationPresent) { if (KOTLIN_SERIALIZATION_PRESENT) {
requestBodyAdvices.add(new KotlinRequestBodyAdvice()); requestBodyAdvices.add(new KotlinRequestBodyAdvice());
responseBodyAdvices.add(new KotlinResponseBodyAdvice()); responseBodyAdvices.add(new KotlinResponseBodyAdvice());
} }
@ -1032,12 +1032,12 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
exceptionHandlerResolver.setCustomArgumentResolvers(getArgumentResolvers()); exceptionHandlerResolver.setCustomArgumentResolvers(getArgumentResolvers());
exceptionHandlerResolver.setCustomReturnValueHandlers(getReturnValueHandlers()); exceptionHandlerResolver.setCustomReturnValueHandlers(getReturnValueHandlers());
exceptionHandlerResolver.setErrorResponseInterceptors(getErrorResponseInterceptors()); exceptionHandlerResolver.setErrorResponseInterceptors(getErrorResponseInterceptors());
if (jacksonPresent || jackson2Present || kotlinSerializationPresent) { if (JACKSON_PRESENT || JACKSON_2_PRESENT || KOTLIN_SERIALIZATION_PRESENT) {
List<ResponseBodyAdvice<?>> responseBodyAdvices = new ArrayList<>(2); List<ResponseBodyAdvice<?>> responseBodyAdvices = new ArrayList<>(2);
if (jacksonPresent || jackson2Present) { if (JACKSON_PRESENT || JACKSON_2_PRESENT) {
responseBodyAdvices.add(new JsonViewResponseBodyAdvice()); responseBodyAdvices.add(new JsonViewResponseBodyAdvice());
} }
if (kotlinSerializationPresent) { if (KOTLIN_SERIALIZATION_PRESENT) {
responseBodyAdvices.add(new KotlinResponseBodyAdvice()); responseBodyAdvices.add(new KotlinResponseBodyAdvice());
} }
exceptionHandlerResolver.setResponseBodyAdvice(responseBodyAdvices); exceptionHandlerResolver.setResponseBodyAdvice(responseBodyAdvices);

2
spring-webmvc/src/main/java/org/springframework/web/servlet/function/AsyncServerResponse.java

@ -100,7 +100,7 @@ public interface AsyncServerResponse extends ServerResponse {
if (obj instanceof CompletableFuture<?> futureResponse) { if (obj instanceof CompletableFuture<?> futureResponse) {
return (CompletableFuture<ServerResponse>) futureResponse; return (CompletableFuture<ServerResponse>) futureResponse;
} }
else if (DefaultAsyncServerResponse.reactiveStreamsPresent) { else if (DefaultAsyncServerResponse.REACTIVE_STREAMS_PRESENT) {
ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance(); ReactiveAdapterRegistry registry = ReactiveAdapterRegistry.getSharedInstance();
ReactiveAdapter publisherAdapter = registry.getAdapter(obj.getClass()); ReactiveAdapter publisherAdapter = registry.getAdapter(obj.getClass());
if (publisherAdapter != null) { if (publisherAdapter != null) {

2
spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultAsyncServerResponse.java

@ -49,7 +49,7 @@ import org.springframework.web.servlet.ModelAndView;
*/ */
final class DefaultAsyncServerResponse extends ErrorHandlingServerResponse implements AsyncServerResponse { final class DefaultAsyncServerResponse extends ErrorHandlingServerResponse implements AsyncServerResponse {
static final boolean reactiveStreamsPresent = ClassUtils.isPresent( static final boolean REACTIVE_STREAMS_PRESENT = ClassUtils.isPresent(
"org.reactivestreams.Publisher", DefaultAsyncServerResponse.class.getClassLoader()); "org.reactivestreams.Publisher", DefaultAsyncServerResponse.class.getClassLoader());
private final CompletableFuture<ServerResponse> futureResponse; private final CompletableFuture<ServerResponse> futureResponse;

2
spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java

@ -211,7 +211,7 @@ final class DefaultEntityResponseBuilder<T> implements EntityResponse.Builder<T>
return new CompletionStageEntityResponse(this.status, this.headers, this.cookies, return new CompletionStageEntityResponse(this.status, this.headers, this.cookies,
completionStage, this.entityType); completionStage, this.entityType);
} }
else if (DefaultAsyncServerResponse.reactiveStreamsPresent) { else if (DefaultAsyncServerResponse.REACTIVE_STREAMS_PRESENT) {
ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(this.entity.getClass()); ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(this.entity.getClass());
if (adapter != null) { if (adapter != null) {
Publisher<T> publisher = adapter.toPublisher(this.entity); Publisher<T> publisher = adapter.toPublisher(this.entity);

6
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java

@ -83,7 +83,7 @@ class ReactiveTypeHandler {
private static final MediaType APPLICATION_GRPC = MediaType.valueOf("application/grpc"); private static final MediaType APPLICATION_GRPC = MediaType.valueOf("application/grpc");
private static final boolean isContextPropagationPresent = ClassUtils.isPresent( private static final boolean CONTEXT_PROPAGATION_PRESENT = ClassUtils.isPresent(
"io.micrometer.context.ContextSnapshot", ReactiveTypeHandler.class.getClassLoader()); "io.micrometer.context.ContextSnapshot", ReactiveTypeHandler.class.getClassLoader());
private static final Log logger = LogFactory.getLog(ReactiveTypeHandler.class); private static final Log logger = LogFactory.getLog(ReactiveTypeHandler.class);
@ -116,7 +116,7 @@ class ReactiveTypeHandler {
} }
private static @Nullable Object initContextSnapshotHelper(@Nullable Object snapshotFactory) { private static @Nullable Object initContextSnapshotHelper(@Nullable Object snapshotFactory) {
if (isContextPropagationPresent) { if (CONTEXT_PROPAGATION_PRESENT) {
return new ContextSnapshotHelper((ContextSnapshotFactory) snapshotFactory); return new ContextSnapshotHelper((ContextSnapshotFactory) snapshotFactory);
} }
return null; return null;
@ -147,7 +147,7 @@ class ReactiveTypeHandler {
Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz); Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz);
TaskDecorator taskDecorator = null; TaskDecorator taskDecorator = null;
if (isContextPropagationPresent) { if (CONTEXT_PROPAGATION_PRESENT) {
ContextSnapshotHelper helper = (ContextSnapshotHelper) this.contextSnapshotHelper; ContextSnapshotHelper helper = (ContextSnapshotHelper) this.contextSnapshotHelper;
Assert.notNull(helper, "No ContextSnapshotHelper"); Assert.notNull(helper, "No ContextSnapshotHelper");
returnValue = helper.writeReactorContext(returnValue); returnValue = helper.writeReactorContext(returnValue);

4
spring-webmvc/src/main/java/org/springframework/web/servlet/support/JspAwareRequestContext.java

@ -80,7 +80,7 @@ public class JspAwareRequestContext extends RequestContext {
*/ */
@Override @Override
protected Locale getFallbackLocale() { protected Locale getFallbackLocale() {
if (jstlPresent) { if (JSTL_PRESENT) {
Locale locale = JstlPageLocaleResolver.getJstlLocale(getPageContext()); Locale locale = JstlPageLocaleResolver.getJstlLocale(getPageContext());
if (locale != null) { if (locale != null) {
return locale; return locale;
@ -95,7 +95,7 @@ public class JspAwareRequestContext extends RequestContext {
*/ */
@Override @Override
protected @Nullable TimeZone getFallbackTimeZone() { protected @Nullable TimeZone getFallbackTimeZone() {
if (jstlPresent) { if (JSTL_PRESENT) {
TimeZone timeZone = JstlPageLocaleResolver.getJstlTimeZone(getPageContext()); TimeZone timeZone = JstlPageLocaleResolver.getJstlTimeZone(getPageContext());
if (timeZone != null) { if (timeZone != null) {
return timeZone; return timeZone;

6
spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java

@ -82,7 +82,7 @@ public class RequestContext {
public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = RequestContext.class.getName() + ".CONTEXT"; public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = RequestContext.class.getName() + ".CONTEXT";
protected static final boolean jstlPresent = ClassUtils.isPresent( protected static final boolean JSTL_PRESENT = ClassUtils.isPresent(
"jakarta.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader()); "jakarta.servlet.jsp.jstl.core.Config", RequestContext.class.getClassLoader());
private final HttpServletRequest request; private final HttpServletRequest request;
@ -305,7 +305,7 @@ public class RequestContext {
* @see jakarta.servlet.http.HttpServletRequest#getLocale() * @see jakarta.servlet.http.HttpServletRequest#getLocale()
*/ */
protected Locale getFallbackLocale() { protected Locale getFallbackLocale() {
if (jstlPresent) { if (JSTL_PRESENT) {
Locale locale = JstlLocaleResolver.getJstlLocale(getRequest(), getServletContext()); Locale locale = JstlLocaleResolver.getJstlLocale(getRequest(), getServletContext());
if (locale != null) { if (locale != null) {
return locale; return locale;
@ -321,7 +321,7 @@ public class RequestContext {
* @return the fallback time zone (or {@code null} if none derivable from the request) * @return the fallback time zone (or {@code null} if none derivable from the request)
*/ */
protected @Nullable TimeZone getFallbackTimeZone() { protected @Nullable TimeZone getFallbackTimeZone() {
if (jstlPresent) { if (JSTL_PRESENT) {
TimeZone timeZone = JstlLocaleResolver.getJstlTimeZone(getRequest(), getServletContext()); TimeZone timeZone = JstlLocaleResolver.getJstlTimeZone(getRequest(), getServletContext());
if (timeZone != null) { if (timeZone != null) {
return timeZone; return timeZone;

4
spring-webmvc/src/main/java/org/springframework/web/servlet/view/InternalResourceViewResolver.java

@ -49,7 +49,7 @@ import org.springframework.util.ClassUtils;
*/ */
public class InternalResourceViewResolver extends UrlBasedViewResolver { public class InternalResourceViewResolver extends UrlBasedViewResolver {
private static final boolean jstlPresent = ClassUtils.isPresent( private static final boolean JSTL_PRESENT = ClassUtils.isPresent(
"jakarta.servlet.jsp.jstl.core.Config", InternalResourceViewResolver.class.getClassLoader()); "jakarta.servlet.jsp.jstl.core.Config", InternalResourceViewResolver.class.getClassLoader());
private @Nullable Boolean alwaysInclude; private @Nullable Boolean alwaysInclude;
@ -62,7 +62,7 @@ public class InternalResourceViewResolver extends UrlBasedViewResolver {
*/ */
public InternalResourceViewResolver() { public InternalResourceViewResolver() {
Class<?> viewClass = requiredViewClass(); Class<?> viewClass = requiredViewClass();
if (InternalResourceView.class == viewClass && jstlPresent) { if (InternalResourceView.class == viewClass && JSTL_PRESENT) {
viewClass = JstlView.class; viewClass = JstlView.class;
} }
setViewClass(viewClass); setViewClass(viewClass);

30
spring-websocket/src/main/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParser.java

@ -116,24 +116,24 @@ class MessageBrokerBeanDefinitionParser implements BeanDefinitionParser {
private static final int DEFAULT_MAPPING_ORDER = 1; private static final int DEFAULT_MAPPING_ORDER = 1;
private static final boolean jacksonPresent; private static final boolean JACKSON_PRESENT;
private static final boolean jackson2Present; private static final boolean JACKSON_2_PRESENT;
private static final boolean gsonPresent; private static final boolean GSON_PRESENT;
private static final boolean jsonbPresent; private static final boolean JSONB_PRESENT;
private static final boolean javaxValidationPresent; private static final boolean BEAN_VALIDATION_PRESENT;
static { static {
ClassLoader classLoader = MessageBrokerBeanDefinitionParser.class.getClassLoader(); ClassLoader classLoader = MessageBrokerBeanDefinitionParser.class.getClassLoader();
jacksonPresent = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader); JACKSON_PRESENT = ClassUtils.isPresent("tools.jackson.databind.ObjectMapper", classLoader);
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && JACKSON_2_PRESENT = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); GSON_PRESENT = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader); JSONB_PRESENT = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
javaxValidationPresent = ClassUtils.isPresent("jakarta.validation.Validator", classLoader); BEAN_VALIDATION_PRESENT = ClassUtils.isPresent("jakarta.validation.Validator", classLoader);
} }
@ -510,14 +510,14 @@ class MessageBrokerBeanDefinitionParser implements BeanDefinitionParser {
converters.setSource(source); converters.setSource(source);
converters.add(new RootBeanDefinition(StringMessageConverter.class)); converters.add(new RootBeanDefinition(StringMessageConverter.class));
converters.add(new RootBeanDefinition(ByteArrayMessageConverter.class)); converters.add(new RootBeanDefinition(ByteArrayMessageConverter.class));
if (jacksonPresent) { if (JACKSON_PRESENT) {
RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(JacksonJsonMessageConverter.class); RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(JacksonJsonMessageConverter.class);
RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class); RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class);
resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON); resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON);
jacksonConverterDef.getPropertyValues().add("contentTypeResolver", resolverDef); jacksonConverterDef.getPropertyValues().add("contentTypeResolver", resolverDef);
converters.add(jacksonConverterDef); converters.add(jacksonConverterDef);
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(MappingJackson2MessageConverter.class); RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(MappingJackson2MessageConverter.class);
RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class); RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class);
resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON); resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON);
@ -530,10 +530,10 @@ class MessageBrokerBeanDefinitionParser implements BeanDefinitionParser {
jacksonConverterDef.getPropertyValues().add("objectMapper", jacksonFactoryDef); jacksonConverterDef.getPropertyValues().add("objectMapper", jacksonFactoryDef);
converters.add(jacksonConverterDef); converters.add(jacksonConverterDef);
} }
else if (gsonPresent) { else if (GSON_PRESENT) {
converters.add(new RootBeanDefinition(GsonMessageConverter.class)); converters.add(new RootBeanDefinition(GsonMessageConverter.class));
} }
else if (jsonbPresent) { else if (JSONB_PRESENT) {
converters.add(new RootBeanDefinition(JsonbMessageConverter.class)); converters.add(new RootBeanDefinition(JsonbMessageConverter.class));
} }
} }
@ -605,7 +605,7 @@ class MessageBrokerBeanDefinitionParser implements BeanDefinitionParser {
if (messageBrokerElement.hasAttribute("validator")) { if (messageBrokerElement.hasAttribute("validator")) {
return new RuntimeBeanReference(messageBrokerElement.getAttribute("validator")); return new RuntimeBeanReference(messageBrokerElement.getAttribute("validator"));
} }
else if (javaxValidationPresent) { else if (BEAN_VALIDATION_PRESENT) {
RootBeanDefinition validatorDef = new RootBeanDefinition( RootBeanDefinition validatorDef = new RootBeanDefinition(
"org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean"); "org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean");
validatorDef.setSource(source); validatorDef.setSource(source);

4
spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketNamespaceHandler.java

@ -28,14 +28,14 @@ import org.springframework.util.ClassUtils;
*/ */
public class WebSocketNamespaceHandler extends NamespaceHandlerSupport { public class WebSocketNamespaceHandler extends NamespaceHandlerSupport {
private static final boolean isSpringMessagingPresent = ClassUtils.isPresent( private static final boolean SPRING_MESSAGING_PRESENT = ClassUtils.isPresent(
"org.springframework.messaging.Message", WebSocketNamespaceHandler.class.getClassLoader()); "org.springframework.messaging.Message", WebSocketNamespaceHandler.class.getClassLoader());
@Override @Override
public void init() { public void init() {
registerBeanDefinitionParser("handlers", new HandlersBeanDefinitionParser()); registerBeanDefinitionParser("handlers", new HandlersBeanDefinitionParser());
if (isSpringMessagingPresent) { if (SPRING_MESSAGING_PRESENT) {
registerBeanDefinitionParser("message-broker", new MessageBrokerBeanDefinitionParser()); registerBeanDefinitionParser("message-broker", new MessageBrokerBeanDefinitionParser());
} }
} }

4
spring-websocket/src/main/java/org/springframework/web/socket/server/support/DefaultHandshakeHandler.java

@ -36,13 +36,13 @@ import org.springframework.web.socket.server.standard.StandardWebSocketUpgradeSt
*/ */
public class DefaultHandshakeHandler extends AbstractHandshakeHandler implements ServletContextAware { public class DefaultHandshakeHandler extends AbstractHandshakeHandler implements ServletContextAware {
private static final boolean jettyWsPresent = ClassUtils.isPresent( private static final boolean JETTY_WS_PRESENT = ClassUtils.isPresent(
"org.eclipse.jetty.ee11.websocket.server.JettyWebSocketServerContainer", "org.eclipse.jetty.ee11.websocket.server.JettyWebSocketServerContainer",
DefaultHandshakeHandler.class.getClassLoader()); DefaultHandshakeHandler.class.getClassLoader());
public DefaultHandshakeHandler() { public DefaultHandshakeHandler() {
super(jettyWsPresent ? new JettyRequestUpgradeStrategy() : new StandardWebSocketUpgradeStrategy()); super(JETTY_WS_PRESENT ? new JettyRequestUpgradeStrategy() : new StandardWebSocketUpgradeStrategy());
} }
public DefaultHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) { public DefaultHandshakeHandler(RequestUpgradeStrategy requestUpgradeStrategy) {

8
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java

@ -63,10 +63,10 @@ import org.springframework.web.util.UriComponentsBuilder;
*/ */
public class SockJsClient implements WebSocketClient, Lifecycle { public class SockJsClient implements WebSocketClient, Lifecycle {
private static final boolean jacksonPresent = ClassUtils.isPresent( private static final boolean JACKSON_PRESENT = ClassUtils.isPresent(
"tools.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader()); "tools.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader());
private static final boolean jackson2Present = ClassUtils.isPresent( private static final boolean JACKSON_2_PRESENT = ClassUtils.isPresent(
"com.fasterxml.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader()); "com.fasterxml.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader());
private static final Log logger = LogFactory.getLog(SockJsClient.class); private static final Log logger = LogFactory.getLog(SockJsClient.class);
@ -102,10 +102,10 @@ public class SockJsClient implements WebSocketClient, Lifecycle {
Assert.notEmpty(transports, "No transports provided"); Assert.notEmpty(transports, "No transports provided");
this.transports = new ArrayList<>(transports); this.transports = new ArrayList<>(transports);
this.infoReceiver = initInfoReceiver(transports); this.infoReceiver = initInfoReceiver(transports);
if (jacksonPresent) { if (JACKSON_PRESENT) {
this.messageCodec = new JacksonJsonSockJsMessageCodec(); this.messageCodec = new JacksonJsonSockJsMessageCodec();
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
this.messageCodec = new Jackson2SockJsMessageCodec(); this.messageCodec = new Jackson2SockJsMessageCodec();
} }
} }

8
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java

@ -71,10 +71,10 @@ import org.springframework.web.socket.sockjs.support.AbstractSockJsService;
*/ */
public class TransportHandlingSockJsService extends AbstractSockJsService implements SockJsServiceConfig, Lifecycle { public class TransportHandlingSockJsService extends AbstractSockJsService implements SockJsServiceConfig, Lifecycle {
private static final boolean jacksonPresent = ClassUtils.isPresent( private static final boolean JACKSON_PRESENT = ClassUtils.isPresent(
"tools.jackson.databind.ObjectMapper", TransportHandlingSockJsService.class.getClassLoader()); "tools.jackson.databind.ObjectMapper", TransportHandlingSockJsService.class.getClassLoader());
private static final boolean jackson2Present = ClassUtils.isPresent( private static final boolean JACKSON_2_PRESENT = ClassUtils.isPresent(
"com.fasterxml.jackson.databind.ObjectMapper", TransportHandlingSockJsService.class.getClassLoader()); "com.fasterxml.jackson.databind.ObjectMapper", TransportHandlingSockJsService.class.getClassLoader());
@ -123,10 +123,10 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem
} }
} }
if (jacksonPresent) { if (JACKSON_PRESENT) {
this.messageCodec = new JacksonJsonSockJsMessageCodec(); this.messageCodec = new JacksonJsonSockJsMessageCodec();
} }
else if (jackson2Present) { else if (JACKSON_2_PRESENT) {
this.messageCodec = new Jackson2SockJsMessageCodec(); this.messageCodec = new Jackson2SockJsMessageCodec();
} }
} }

Loading…
Cancel
Save