Redis 存储库和多态性不能一起工作

Twi*_*her 5 java spring redis spring-data

我有这个代码:

@Getter
@Setter
@RedisHash
class Root {
  private Base base;
}

public interface Base {

}

@Getter
@Setter
public class Implementor implements Base {
  // ...
}

public class CustomKeyspaceConfiguration extends KeyspaceConfiguration {
    private final String prefix;
    
    public SagtKeyspaceConfiguration(String prefix) {
        super();
        
        this.prefix = prefix;
    }
    
    @Override
    public boolean hasSettingsFor(Class<?> type) {
        if (super.hasSettingsFor(type) == false) {
            KeyspaceSettings settings = new KeyspaceSettings(type, prefix + ClassUtils.getUserClass(type).getName());
            addKeyspaceSettings(settings);
        }
        
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个CrudRepositoryforRoot类,它允许我在 Redis 中成功存储该类型的对象。

但是当我使用 simple 检索对象时findById,出现此错误:

无法使用带参数的构造函数 NO_CONSTRUCTOR 实例化 some.package.name.Base

但是,该_class属性在 Redis 中已正确设置:

base._class: some.package.name.Implementor
Run Code Online (Sandbox Code Playgroud)

为什么在 Redis HashMap 中正确设置实际类时它会尝试实例化接口?

编辑:

我尝试使用相同版本的 spring-data-redis (2.6.4) 创建一个最小的可重现示例,但它有效......

我的项目中肯定还有其他东西,但我不知道是什么。

Twi*_*her 2

我的问题与 Spring Boot 开发工具有关。

Spring Data 有这段代码

Class<?> documentsTargetType = getDefaultedTypeToBeUsed(source);

if (documentsTargetType == null) {
    return basicType;
}

Class<T> rawType = basicType.getType();

boolean isMoreConcreteCustomType = (rawType == null)
    || (rawType.isAssignableFrom(documentsTargetType) && !rawType.equals(documentsTargetType));

if (!isMoreConcreteCustomType) {
    return basicType;
}
Run Code Online (Sandbox Code Playgroud)

就我而言,documentsTargetType包含ImplementorbasicType包含Base。条件rawType.isAssignableFrom(documentsTargetType)应该返回true,但在我的情况下它正在返回false,因为BaseImplementor由于开发工具而被不同的类加载器加载。

所以这段代码返回Base而不是Implementor.

spring-boot-devtools通过从项目的依赖项中删除来解决问题。