我的 WebService 基于 Spring 4,并且我正在使用 Hibernate Validator(超越 MethodValidationPostProcessor)。我的问题是我有我的ClientService界面及其实现。因此,我在实现上放置了 Bean Validation 约束,这迫使我将该约束放置在接口上(抛出ConstraintDeclarationException)(或在两者中)。
关于这件事我想知道两件事:
提前致谢!问候
我使用 Spring 框架和 bean 验证规范(hibernate 实现)。考虑下面的代码片段,我使用以下方法进行了观察@ReportAsSingleViolation:
@ReportAsSingleViolation添加时仅返回默认消息。我的期望是触发失败的消息而不是默认消息。
当我删除@ReportAsSingleViolation注释时,一切都会按预期进行。与违反的约束相对应的所有错误消息都会正确返回。
此行为描述了 Bean 验证规范的一部分还是一个实现问题?
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
//@ReportAsSingleViolation
@NotBlank(message = "The input cannot be blank")
@Pattern(regexp = "[0-9A-Z_]+", message = "The input must content only uppercase, numbers and undescore")
@Size(max = 30, message = "The input must be maximal 30")
@Documented
public @interface MyAnnotation{
String message() default "{com.example.MyAnnotation.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Run Code Online (Sandbox Code Playgroud) 我试图在我的表单中显示验证错误,但我无法实现它。我正在尝试传递空值,我收到了休眠验证消息,但我看不到表单验证?
这是我的代码:
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String saveForm(@Valid Users users,Model model,Errors errors) {
if(errors.hasErrors()) {
return "registerPage";
}
else {
model.addAttribute("message","Registered................");
System.out.println("Save Users TEST------------------------------------>");
userRepository.save(users);
return "register-success";
}
}
Run Code Online (Sandbox Code Playgroud)
这是例外:
字段 'salary' 上的对象 'users' 中的字段错误:拒绝值 [null];代码 [NotNull.users.salary,NotNull.salary,NotNull.java.lang.Integer,NotNull]; 参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [users.salary,salary]; 参数 []; 默认消息[薪水]];默认消息 [不得为空] 字段 'dept' 上的对象 'users' 中的字段错误:拒绝值 [];代码 [Size.users.dept,Size.dept,Size.java.lang.String,Size]; 参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [users.dept,dept]; 参数 []; 默认消息 [dept],10,2]; 默认消息 [长度应在 2 到 10 之间] 字段“名称”上的对象“用户”中的字段错误:拒绝值 [];代码 [Size.users.name,Size.name,Size.java.lang.String, 尺寸]; 参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [users.name,name]; 参数 []; 默认消息 …
validation spring-mvc hibernate-validator thymeleaf spring-boot
我写自定义注释
package ru.tinkoff.bpm.verificationcheckservice.support.validation
import org.hibernate.validator.constraints.CompositionType
import org.hibernate.validator.constraints.ConstraintComposition
import org.hibernate.validator.constraints.URL
import javax.validation.Constraint
import javax.validation.Payload
import javax.validation.ReportAsSingleViolation
import javax.validation.constraints.NotBlank
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.FIELD
import kotlin.reflect.KClass
@ConstraintComposition(CompositionType.AND)
@URL
@NotBlank
@ReportAsSingleViolation
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = [])
annotation class NotBlankUrl(
val message: String = "must be not blank and valid URL",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
Run Code Online (Sandbox Code Playgroud)
我添加了 build.gradle.kts 的依赖项
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.hibernate:hibernate-validator:7.0.1.Final")
Run Code Online (Sandbox Code Playgroud)
Gradle 在报告中解决它 https://scans.gradle.com/s/ddjce3iwnldt4/dependency?dependencies=valida&expandAll&focusedDependency=WzEsOCwxNDk2LFswLDEsWzE5XV1d
但是当我启动应用程序时我看到错误
The Bean Validation API is on the classpath but no implementation could …Run Code Online (Sandbox Code Playgroud) 我的应用程序在这里遇到了一些问题.我想检查字段密码和确认密码是否匹配在一起,所以我尝试在这个问题的第一个答案中这样做:使用Hibernate Validator进行交叉字段验证(JSR 303)
问题是它实际上不起作用,我没有想法为什么.请帮我!这是我在这里的第一篇文章,所以请不要对我太苛刻.
这是我的注释:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints;
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
*
* @author lukasz
*/
@Documented
@Constraint(validatedBy = FieldMatchValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldMatch {
String message() default "{pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints.FieldMatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String first();
String second();
}
Run Code Online (Sandbox Code Playgroud)
这是我的ValidatorClass:
/*
* To change this template, choose Tools | Templates
* …Run Code Online (Sandbox Code Playgroud) validation hibernate-validator bean-validation jsf-2 managed-bean
尝试按照指南在 Spring Boot 中对 JPA 层执行测试切片,但验证约束似乎没有触发。我的设置如下
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "com.myapp.core.dao")
@EntityScan(basePackages = {"com.myapp.core.entity"})
public class CoreConfig {
}
@Entity
@Table(name = "users")
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@NotNull
@Size(min = 1, max = 50)
@Column(name = "username")
private String username;
...
}
public interface UsersDAO extends CrudRepository<Users, String> {
}
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public …Run Code Online (Sandbox Code Playgroud) java spring integration-testing hibernate-validator spring-boot
我已经使用 Rest 控制器创建了一个 Spring Boot 应用程序(用户 spring-boot-starter-parent V.2.2.2.RELEASE),工作正常,现在我添加了一个依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并在我的控制器类上添加了@Validated,以便验证其中的所有方法:
@RestController
@Validated
public class UserController {
@Autowired
private UserService userService;
@PostConstruct
public void init() {
System.out.println("test");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,控制器方法在调用时开始抛出 NullPointerExceptions,因为 userService 为 null;我做了一个@PostConstruct 作为测试。显然,它是在一个正常的未增强的 bean 上调用的,该 bean 的字段已正确自动连接。但是,当通过 HTTP 调用控制器时,不会调用这个未增强的 bean,但它是类 UserController$$EnhancerBySpringCGLIB$$ 的 bean,并且它的 userController 未自动装配。我真的不知道为什么,因为这应该很简单,据我所知,没有太多需要配置的。所以我猜由于某种原因,spring 不会将依赖项注入到 CGLIB 增强类中,或者只是将其注入到错误的类中。当我删除@Validated时,一切都再次正常工作,但当然没有验证。
spring-boot ×4
java ×3
validation ×3
spring ×2
cglib ×1
hibernate ×1
jsf-2 ×1
managed-bean ×1
spring-mvc ×1
thymeleaf ×1