【问题标题】:Java pass variable into mapped DTO method?Java将变量传递给映射的DTO方法?
【发布时间】:2019-12-12 12:04:54
【问题描述】:

我有 Spring Boot 应用程序,其实现包含具有以下功能的方法。该实现使用 2 个 DTO 来绑定数据。有没有合适的方法可以将值从 JAY 传递到 '10.00' 硬编码的值?我对 'this::convertProfileToProfileCreditDTO' 有主要问题,是否可以在此表达式中传递参数?
我已经使用Java DTO Object search mechanism? 进行启发


如果我尝试在以下代码中添加参数 this::convertProfileToProfileCreditDTO 抱怨返回类型错误

convertProfileToProfileCreditDTO(final Profile theProfile, Double JAY)


实施

 @Override
    public Double testThisParam(Double profileCredit) {
        Double JAY = profileCredit;
        log.error(String.valueOf(JAY));
        return JAY;
    }

    @Override
    public Page<ProfileCreditDTO> findProfileBySelectedParameters(String username, Pageable pageable) {

        Page<Profile> searchData= profileRepository.findByAllParameters(username, pageable);

        Page<ProfileCreditDTO> searchProfileData=null;

        if(searchData != null)
            searchProfileData=searchData.map(this::convertProfileToProfileCreditDTO);
        return searchProfileData;
    }        

public ProfileCreditDTO convertProfileToProfileCreditDTO(final Profile theProfile ){

        if(theProfile == null)
            return null;
        ProfileCreditDTO theDTO= new ProfileCreditDTO();

        theDTO.setProfile(theProfile);

        CreditDTO theCreditDto = profileCreditClient.findClientByProfileId(theProfile.getId(), 10.00);

        if(theCreditDto != null )
            theDTO.setCredit(theCreditDto);
        else {

            return null;

        }

        return theDTO;
    }

【问题讨论】:

  • 您可以使用 lambda 表达式并传递您想要传递的任何参数。像- map(profile -> convertProfileToProfileCreditDTO(profile, otherParameters).

标签: java spring microservices dto


【解决方案1】:

您总是可以向 lambda 表达式传递更多参数

searchProfileData = searchData.map(x -> this.convertProfileToProfileCreditDTO(x, JAY));

附带说明,如果您想使用this:: 风格保持函数调用简单,您可以创建一个数据对象来携带您所需的参数

class MyObject {
    Profile theProfile;
    Double JAY;
    // public constructor with parameters
}

// then construct and use this

MyObject o = new MyObject(theProfile, testThisParam(...));

// and then change parameter of target method

convertProfileToProfileCreditDTO(MyObject myObject) ...

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 2018-04-30
    • 1970-01-01
    • 2012-08-21
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    相关资源
    最近更新 更多