2017-02-17 52 views
0

我寫了使用這樣的映射mapstruct映射:力mapstruct不叫有*方法

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

當我看到自動生成的mapstruct I類stubled在代碼:

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

這對我來說是個問題,因爲hasId()不是映射結構在這裏期望的。我可以強制映射不知何故不生成使用此方法的代碼,但檢查id != null什麼的?

我可以使用像@Mapping(target = "userId", expression= "java(...)")這樣的映射,但我認爲應該有另一種方法。

回答

2

是的,你可以強制MapStruct不使用那些presenceCheckers。您可以在文檔中找到source presence checking的更多信息。

基本上這樣做的唯一方法是提供一個MapStruct AccessorNamingStrategy的實現。您只能擴展DefaultAccessorNamingStrategy並覆蓋其isPresenceCheckMethod

您可以訪問方法ExecutableElement,您也可以檢查它所在的類的類型以及其他內容。

MyAccessorNamingStrategy extends DefaultAccessorNamingStrategy { 

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

    } 

記住與文件META-INF-/services/com.example.MyAccessorNamingStrategy

註冊您的SPI也有examples在那裏你可以找到一個SPI的例子。