这里不考虑@Valid
,我可以用每个字符串调用API:
import javax.validation.Valid;
@RequiredArgsConstructor
@RestController
@RequestMapping("/account")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class AccountController {
private final AccountService accountService;
@GetMapping
@ResponseBody
public Account getAccountDetails(@Valid @Email @RequestParam final String email) {
return accountService.getAccount(email);
}
}
下面是我的main()
:
@SpringBootApplication
@EnableScheduling
@EnableCaching
@EnableAsync
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
以下是我的Sping Boot 依赖项:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.8</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
...
</dependencies>
我是否需要在某处启用Sping Boot 验证?
3条答案
按热度按时间fsi0uk1n1#
您可能使用了模棱两可的导入。
使用
import javax.validation.Valid
,因为Sping Boot 2.7使用JavaEE而不是对Sping Boot 3有效的
import jakarta.validation.Valid
。lyfkaqu12#
缺少的只是控制器类上的
@Validated
注解(感谢@Boško):(btw
@Valid
注解在这里不起作用!)1l5u6lss3#
您需要配置一个验证器bean:
然后应用
@Validated
注解并向getAccountDetails()
方法添加BindingResult
参数,如下所示:如果出现任何验证错误,则会填充
BindingResult
参数。您可以在此处阅读有关该参数的详细信息:https://spring.io/guides/gs/validating-form-input/