【推荐】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了,所以我们可以在任何地方注入了
来源:oschina
链接:https://my.oschina.net/u/1865350/blog/1935730