我一直在寻找其他问题,但我仍然不明白这里发生了什么。 我有这门课:
package com.test.service.database.converter;
import com.test.service.database.dao.DocumentType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class DocumentStringConverter implements Converter<DocumentType, String> {
@Override
public String convert(DocumentType documentType) {
return Optional.ofNullable(documentType).map(DocumentType::type).orElse(null);
}
}
它实现了这个 Spring 接口:
package org.springframework.core.convert.converter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@FunctionalInterface
public interface Converter<S, T> {
@Nullable
T convert(S source);
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
Assert.notNull(after, "After Converter must not be null");
return (S s) -> {
T initialResult = convert(s);
return (initialResult != null ? after.convert(initialResult) : null);
};
}
}
IntelliJ 对
中的参数发出警告public String convert(DocumentType documentType) {
说明
未注释的参数覆盖@NonNullApi参数
documentType – 要转换的源对象,必须是 S 的实例(绝不为 null)
这是为什么呢?既然 Converter 带有
@Nullable
注释,这意味着什么?我该如何解决这个警告?
来自Spring官方文档:
这是一个常见的 Spring 注释,用于声明 默认情况下,对于给定的包,参数和返回值将被视为不可为空。
org/springframework/core/convert/converter/package-info.java
:
/**
* SPI to implement Converters for the type conversion system.
*/
@NonNullApi // !!!!!!!!!!!!
@NonNullFields
package org.springframework.core.convert.converter;
可以使用
@NonNullApi
注释在方法级别覆盖
@Nullable
,以防止对可能返回 null 的方法发出警告,这就是您在
org.springframework.core.convert.converter.Converter
:中看到的内容
@FunctionalInterface
public interface Converter<S, T> {
/**
* Convert the source object of type {@code S} to target type {@code T}.
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
@Nullable // !!!!!!!!!!
T convert(S source);
在重写的方法上,您没有指定 @Nullable
注释,因此没有指定警告。