微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring \ Spring Boot:是否需要自定义验证器?

如何解决Spring \ Spring Boot:是否需要自定义验证器?

假设我具有此控制器映射功能

@GetMapping("/result")
public Stats result(@RequestParam Integer homeId,@RequestParam Integer awayId)
        throws MissingTeamException,InvalidTeamIdExcpetion {

    //Validation starts here
    int numOfAvailableTeams = teamResource.retrieveAllTeams().size();
    
    if( homeId < 0 || homeId >= numOfAvailableTeams)
            throw new InvalidTeamIdExcpetion(homeId);

    if(awayId < 0 || awayId >= numOfAvailableTeams)
            throw new InvalidTeamIdExcpetion(awayId);
    //end of validation

    return generateResult(homeId,awayId);
}

您可以看到我正在验证住家和出家证。

除了创建自定义验证器类之外,我还能以更简洁的方式做到这一点吗?

谢谢!

解决方法

通常,在每种情况下,逻辑都应该在服务类(由@Service标记)中编写,而不是在控制器中编写。因此,您可以使用方法validating()创建带有验证所需参数的服务类。服务示例:

@Service
public class YourService {

    //This variable and constructor are optional because I didn't see your whole code.
    //But if you will to create TeamResource field in service,Spring Boot will automatically
    //inject teamResource if you have suitable Bean.
    private TeamResource teamResource;

    public YourService(TeamResource teamResource) {
        this.teamResource = teamResource;
    }

    public TypeOfMethodGenerateResult validate(Integer homeId,Integer awayId) {

        int numOfAvailableTeams = teamResource.retrieveAllTeams().size();

        if (homeId < 0 || homeId >= numOfAvailableTeams)
            throw new InvalidTeamIdExcpetion(homeId);

        if(awayId < 0 || awayId >= numOfAvailableTeams)
            throw new InvalidTeamIdExcpetion(awayId);

        return generateResult(homeId,awayId);
    }
}

和控制器:

//Autoinject like in service.
private YourService yourService;

public YourService(YourService yourService) {
    this.yourService = yourService;
}

@GetMapping("/result")
public Stats result(@RequestParam Integer homeId,@RequestParam Integer awayId)
        throws MissingTeamException,InvalidTeamIdExcpetion {

    return yourService.validate(homeId,awayId);
}
,

要验证@RequestParam,可以使用 @Valid @Validated 批注。

@GetMapping("/result")
    public String result(@RequestParam @Valid @Size(min = 1) Integer homeId,@RequestParam @Valid @Size(min = 1) Integer awayId)

在类本身上使用 @Validated

进口供参考:

导入org.springframework.validation.annotation.Validated;

import javax.validation.Valid;

import javax.validation.constraints.Size;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。