kotlin使用mapstruct(四)

我们两清 提交于 2019-12-16 11:36:25

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

这节主要介绍下集成spring

1.修改上一节中的AppleConverter,给@Mapper添加componentModel字段赋值为spring

@Mapper(componentModel = "spring")
abstract class AppleConverter {}

2.这么easy就可以使用了

@RestController
class MyController{

    @Autowired
    lateinit var appleConverter: AppleConverter
    @GetMapping("/hello")
    fun sayHello():String{

        val apple = Apple(1,"my apple",true)
        println(apple)
        val appleDto = appleConverter.convertToDto(apple)
        println(appleDto)
        val appleModel = appleConverter.convertToModel(appleDto)
        println(appleModel)

        return "hello"
    }
}

3.访问一下输出,跟我们期待的效果一样

Apple(appleId=1, appleName=my apple, real=true)
AppleDto(appleId=1, appleName=my apple, description=水果)
Apple(appleId=1, appleName=my apple, real=true)

4.让我们看一下mapstruct给我们生成了什么

import javax.annotation.Generated;
import org.springframework.stereotype.Component;

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2018-08-29T10:19:12+0800",
    comments = "version: 1.3.0.Beta1, compiler: javac, environment: Java 1.8.0_172 (Oracle Corporation)"
)
@Component
public class AppleConverterImpl extends AppleConverter {

    @Override
    public AppleDto convertToDto(Apple apple) {
        if ( apple == null ) {
            return null;
        }

        AppleDto appleDto = new AppleDto();

        appleDto.setAppleId( apple.getAppleId() );
        appleDto.setAppleName( apple.getAppleName() );

        afterConvertToDto( apple, appleDto );

        return appleDto;
    }

    @Override
    public Apple convertToModel(AppleDto appleDto) {
        if ( appleDto == null ) {
            return null;
        }

        Apple apple = new Apple();

        apple.setAppleId( appleDto.getAppleId() );
        apple.setAppleName( appleDto.getAppleName() );

        afterConvertToModel( appleDto, apple );

        return apple;
    }
}

我们可以看到,生成的代码加上了Component注解,AppleConverterImpl就成为受spring管理的bean了,所以我们可以在任何地方注入了

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!