java - Spring接口(interface)转换器

标签 java spring spring-boot spring-mvc functional-programming

我有 ClassA 和 ClassB,我想将它们转换为 ClassC,但如果我想使用 Spring 转换器:

org.springframework.core.convert.converter
Interface Converter<S,T>
Type Parameters:
S - the source type
T - the target type

我应该创建另一个 classD,例如

ClassD classD {
      ClassA classA;
      ClassB classB;
}

然后从D类到C类?

最佳答案

作为 Spring 的文档 Converter 说:

A converter converts a source object of type S to a target of type T

所以S是源类型且 T是目标类型。

所以如果你想转换ClassAClassB您将创建Converter<ClassA, ClassB>执行。您无法使用 Converter 将两种类型转换为单一类型立刻。您必须创建两个转换器才能按此顺序进行转换,例如 ClassA -> ClassB -> ClassC

或者为 ClassA 创建一些包装类型和ClassB :

public class Wrapper {
    private ClassA a;
    private ClassB b;
}

然后创建一个转换器Converter<Wrapper, ClassD>实现:

Converter<Wrapper, ClassC> converter = wrapper -> {
        //access wrapper
        wrapper.getA();
        wrapper.getB();
        return new ClassC();
};

关于java - Spring接口(interface)转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832151/

相关文章:

java - 请帮助理解这段 Java 代码 :-)

java - 我如何知道我的消息已通过 spring amqp 成功发送?

spring-boot - spring-boot 应用程序的 keep-alive 配置(带有嵌入式 tomcat)

java - DynamoDB Spring Boot 数据剩余 "PersistentEntity must not be null!"

java - 简单地测试 Spring Boot 安全性

java - 阻塞模式下SocketChannel读取返回0

java - Jackson ObjectMapper 如何将 byte[] 传输到 String 以及如何在没有对象类的情况下翻译它?

JavaFx Shape Intersect 始终返回 false/true

java - 当您有单独的身份验证服务器(用户密码授予)时,如何在 Spring MVC 中实现自定义登录/注销(身份验证)

java - 在 Cacheable 方法类中调用 Spring Cacheable 方法抛出异常