简体   繁体   English

强制mapstruct不调用has *方法

[英]Force mapstruct not to call has* methods

I wrote a mapstruct mapper that uses a mapping like this: 我写了一个mapstruct映射器,它使用如下映射:

@Mapping(target = "userId", source = "id.userId")

When I looked at the autogenerated mapstruct class I stubled upon that code: 当我查看自动生成的mapstruct类时,我在该代码上添加了代码:

if ( !foobar.hasId() ) {
    return null;
}

This is a problem for me as hasId() does not what mapstruct expects here. 这对我来说是个问题,因为hasId()不是mapstruct在这里期望的。 Can I force mapstruct somehow to not generate code that uses this method but checks for id != null or something? 我可以以某种方式强制mapstruct不生成使用此方法但是检查id != null或其他内容的代码吗?

I could use a mapping like @Mapping(target = "userId", expression= "java(...)") but I think there should be another way. 我可以使用类似@Mapping(target = "userId", expression= "java(...)")的映射@Mapping(target = "userId", expression= "java(...)")但我认为应该有另一种方法。

Yes you can force MapStruct not to use those presenceCheckers . 是的,您可以强制MapStruct不使用这些presenceCheckers You can find more information in source presence checking in the documentation. 您可以在文档中的源状态检查中找到更多信息。

Basically the only way to do this is to provide an implementation of the MapStruct AccessorNamingStrategy . 基本上,唯一的方法就是提供MapStruct AccessorNamingStrategy的实现。 You can just extend the DefaultAccessorNamingStrategy and override its isPresenceCheckMethod . 您可以扩展DefaultAccessorNamingStrategy并覆盖其isPresenceCheckMethod

You have access to the method ExecutableElement and you can check the type of class it is in and other things as well. 您可以访问方法ExecutableElement ,还可以检查其所在类的类型以及其他内容。

MyAccessorNamingStrategy extends DefaultAccessorNamingStrategy {

    @Override
    public boolean isPresenceCheckMethod(ExecutableElement element) {
        //You can do your checks here. You can ignore certain methods, from certain classes

    }

Remember to register your SPI with a file META-INF-/services/com.example.MyAccessorNamingStrategy 请记住将SPI注册到文件META-INF-/services/com.example.MyAccessorNamingStrategy

There is also the examples where you can find an example for the SPI. 还有一些示例 ,您可以在其中找到SPI的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM