Perform NullAway build-time checks in more modules

This commit enables null-safety build-time checks in
all remaining modules except spring-test.

See gh-32475
This commit is contained in:
Sébastien Deleuze
2024-03-26 15:53:01 +01:00
parent 2fea3d7921
commit 8b51b36729
53 changed files with 93 additions and 31 deletions

View File

@@ -43,6 +43,7 @@ final class BeanMethod extends ConfigurationMethod {
@Override
@SuppressWarnings("NullAway")
public void validate(ProblemReporter problemReporter) {
if ("void".equals(getMetadata().getReturnTypeName())) {
// declared as void: potential misuse of @Bean, maybe meant as init method instead?

View File

@@ -40,6 +40,7 @@ import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
@@ -112,14 +113,18 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
parseBeanNameGenerator(element, scanner);
}
catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error(message, parserContext.extractSource(element), ex.getCause());
}
try {
parseScope(element, scanner);
}
catch (Exception ex) {
parserContext.getReaderContext().error(ex.getMessage(), parserContext.extractSource(element), ex.getCause());
String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error(message, parserContext.extractSource(element), ex.getCause());
}
parseTypeFilters(element, scanner, parserContext);
@@ -214,8 +219,10 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
"Ignoring non-present type filter class: " + ex, parserContext.extractSource(element));
}
catch (Exception ex) {
String message = ex.getMessage();
Assert.state(message != null, "Exception message must not be null");
parserContext.getReaderContext().error(
ex.getMessage(), parserContext.extractSource(element), ex.getCause());
message, parserContext.extractSource(element), ex.getCause());
}
}
}

View File

@@ -219,6 +219,7 @@ final class ConfigurationClass {
return this.importBeanDefinitionRegistrars;
}
@SuppressWarnings("NullAway")
void validate(ProblemReporter problemReporter) {
Map<String, Object> attributes = this.metadata.getAnnotationAttributes(Configuration.class.getName());

View File

@@ -819,6 +819,7 @@ class ConfigurationClassParser {
deferredImport.getConfigurationClass());
}
@SuppressWarnings("NullAway")
void processGroupImports() {
for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
Predicate<String> filter = grouping.getCandidateFilter();

View File

@@ -325,6 +325,7 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
@Override
@Nullable
@SuppressWarnings("NullAway")
public BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {
boolean hasPropertySourceDescriptors = !CollectionUtils.isEmpty(this.propertySourceDescriptors);
boolean hasImportRegistry = beanFactory.containsBean(IMPORT_REGISTRY_BEAN_NAME);
@@ -556,6 +557,7 @@ public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPo
}
@Override
@Nullable
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans.

View File

@@ -98,6 +98,7 @@ public class ContextAnnotationAutowireCandidateResolver extends QualifierAnnotat
return descriptor.getDependencyType();
}
@Override
@SuppressWarnings("NullAway")
public Object getTarget() {
Set<String> autowiredBeanNames = (beanName != null ? new LinkedHashSet<>(1) : null);
Object target = dlbf.doResolveDependency(descriptor, beanName, autowiredBeanNames, null);

View File

@@ -31,6 +31,7 @@ import org.springframework.util.MultiValueMap;
class ProfileCondition implements Condition {
@Override
@SuppressWarnings("NullAway")
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {

View File

@@ -40,6 +40,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
/**
@@ -229,6 +230,7 @@ public abstract class AbstractApplicationEventMulticaster
* @param retriever the ListenerRetriever, if supposed to populate one (for caching purposes)
* @return the pre-filtered list of application listeners for the given event and source type
*/
@SuppressWarnings("NullAway")
private Collection<ApplicationListener<?>> retrieveApplicationListeners(
ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable CachedListenerRetriever retriever) {
@@ -313,7 +315,7 @@ public abstract class AbstractApplicationEventMulticaster
AnnotationAwareOrderComparator.sort(allListeners);
if (retriever != null) {
if (filteredListenerBeans.isEmpty()) {
if (CollectionUtils.isEmpty(filteredListenerBeans)) {
retriever.applicationListeners = new LinkedHashSet<>(allListeners);
retriever.applicationListenerBeans = filteredListenerBeans;
}

View File

@@ -460,6 +460,7 @@ public class ApplicationListenerMethodAdapter implements GenericApplicationListe
}
}
@SuppressWarnings("NullAway")
private String getInvocationErrorMessage(Object bean, @Nullable String message, @Nullable Object[] resolvedArgs) {
StringBuilder sb = new StringBuilder(getDetailedErrorMessage(bean, message));
sb.append("Resolved arguments: \n");

View File

@@ -111,7 +111,7 @@ public class EventListenerMethodProcessor
@Override
public void afterSingletonsInstantiated() {
ConfigurableListableBeanFactory beanFactory = this.beanFactory;
Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
Assert.state(beanFactory != null, "No ConfigurableListableBeanFactory set");
String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) {

View File

@@ -18,6 +18,8 @@ package org.springframework.context.i18n;
import io.micrometer.context.ThreadLocalAccessor;
import org.springframework.lang.Nullable;
/**
* Adapt {@link LocaleContextHolder} to the {@link ThreadLocalAccessor} contract
* to assist the Micrometer Context Propagation library with {@link LocaleContext}
@@ -40,6 +42,7 @@ public class LocaleContextThreadLocalAccessor implements ThreadLocalAccessor<Loc
}
@Override
@Nullable
public LocaleContext getValue() {
return LocaleContextHolder.getLocaleContext();
}

View File

@@ -51,6 +51,7 @@ import org.springframework.format.annotation.DateTimeFormat.ISO;
* @see org.springframework.format.FormatterRegistrar#registerFormatters
* @see org.springframework.format.datetime.DateFormatterRegistrar
*/
@SuppressWarnings("NullAway")
public class DateTimeFormatterRegistrar implements FormatterRegistrar {
private enum Type {DATE, TIME, DATE_TIME}

View File

@@ -993,6 +993,7 @@ public class MBeanExporter extends MBeanRegistrationSupport implements MBeanExpo
* Unregister the configured {@link NotificationListener NotificationListeners}
* from the {@link MBeanServer}.
*/
@SuppressWarnings("NullAway")
private void unregisterNotificationListeners() {
if (this.server != null) {
this.registeredNotificationListeners.forEach((bean, mappedObjectNames) -> {

View File

@@ -43,6 +43,7 @@ import org.springframework.core.annotation.RepeatableContainers;
import org.springframework.jmx.export.metadata.InvalidMetadataException;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
/**
@@ -117,7 +118,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac
pvs.removePropertyValue("defaultValue");
PropertyAccessorFactory.forBeanPropertyAccess(bean).setPropertyValues(pvs);
String defaultValue = (String) map.get("defaultValue");
if (!defaultValue.isEmpty()) {
if (StringUtils.hasLength(defaultValue)) {
bean.setDefaultValue(defaultValue);
}
return bean;

View File

@@ -682,7 +682,8 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
}
}
private void assertValidators(Validator... validators) {
@SuppressWarnings("NullAway")
private void assertValidators(@Nullable Validator... validators) {
Object target = getTarget();
for (Validator validator : validators) {
if (validator != null && (target != null && !validator.supports(target.getClass()))) {
@@ -741,6 +742,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
* {@link #setExcludedValidators(Predicate) exclude predicate}.
* @since 6.1
*/
@SuppressWarnings("NullAway")
public List<Validator> getValidatorsToApply() {
return (this.excludedValidators != null ?
this.validators.stream().filter(validator -> !this.excludedValidators.test(validator)).toList() :
@@ -1168,6 +1170,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
* @see #getBindingErrorProcessor
* @see BindingErrorProcessor#processMissingFieldError
*/
@SuppressWarnings("NullAway")
protected void checkRequiredFields(MutablePropertyValues mpvs) {
String[] requiredFields = getRequiredFields();
if (!ObjectUtils.isEmpty(requiredFields)) {

View File

@@ -242,7 +242,8 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial
* {@link DefaultMessageCodesResolver#CODE_SEPARATOR}, skipping zero-length or
* null elements altogether.
*/
public static String toDelimitedString(String... elements) {
@SuppressWarnings("NullAway")
public static String toDelimitedString(@Nullable String... elements) {
StringJoiner rtn = new StringJoiner(CODE_SEPARATOR);
for (String element : elements) {
if (StringUtils.hasLength(element)) {

View File

@@ -107,8 +107,7 @@ public class FieldError extends ObjectError {
if (!super.equals(other)) {
return false;
}
FieldError otherError = (FieldError) other;
return (getField().equals(otherError.getField()) &&
return (other instanceof FieldError otherError && getField().equals(otherError.getField()) &&
ObjectUtils.nullSafeEquals(getRejectedValue(), otherError.getRejectedValue()) &&
isBindingFailure() == otherError.isBindingFailure());
}

View File

@@ -173,8 +173,8 @@ public class ParameterValidationResult {
if (!super.equals(other)) {
return false;
}
ParameterValidationResult otherResult = (ParameterValidationResult) other;
return (getMethodParameter().equals(otherResult.getMethodParameter()) &&
return (other instanceof ParameterValidationResult otherResult &&
getMethodParameter().equals(otherResult.getMethodParameter()) &&
ObjectUtils.nullSafeEquals(getArgument(), otherResult.getArgument()) &&
ObjectUtils.nullSafeEquals(getContainerIndex(), otherResult.getContainerIndex()) &&
ObjectUtils.nullSafeEquals(getContainerKey(), otherResult.getContainerKey()));