java - ConversionService bean 与用于转换对象的常规转换器 bean

标签 java spring-boot

我想将 Entity 转换为另一个对象以进行响应(例如:ActionEntityActionResponse)。

在 Spring 中我们可以创建这样的 bean:

@Component
public class EntityToResponseConverter implements Converter<ActionEntity,
ActionResponse>{
    @Override
    public RequestResponse convert(ActionEntity entity) {
        ActionResponse response = new ActionResponse();
        response.setId(entity.getId());
        response.setOrigId(entity.getOrigId());       
        return response;
    }
}

然后我 Autowiring 一个 ConversionService 来使用。

另一种创建新 bean 的方法如下:

@Component
public class EntityToResponseConverter {

    public ActionResponse convert(ActionEntity entity) {
        ActionResponse response = new ActionResponse();
        response.setId(entity.getId());
        response.setOrigId(entity.getOrigId());       
        return response;
    }
}

然后我 Autowiring 这个 bean 来使用。 我们什么时候应该实现 Converter 而不是创建常规 bean?

最佳答案

Converter 是一个可用于自动转换的接口(interface):

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new YourCustomConverter());
    }
}

当转换器注册时,如果数据类型匹配,Spring将自动转换 Controller 的请求数据。

关于java - ConversionService bean 与用于转换对象的常规转换器 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243623/

相关文章:

java - HQL改造

java - 通过 Tomcat 7.0/Axis2 的安全连接抛出异常

java - 设计决策 : extending an interface vs. 新界面

java - 如何在Java代码中运行JMeter JMX文件?

java - MyBatis 映射器类未在具有两个数据源的 Spring Boot 应用程序中注册

java - 无法在 Spring Boot 应用程序中配置 ViewResolver

java - 如何在 Java 中使用 sendgrid API 获取 Processed、Delivered、Bounced、Dropped 等事件?

Java:如何为 URL 启动系统的注册应用程序

java - 如何在@SpringBootTest 之前添加设置并且只运行一次?

java - Spring Boot 中的 "Content type ' 图像/jpeg ' not supported for bodyType=org.springframework.web.multipart.MultipartFile"