我有一个控制器,其中包含以下内容:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.Validator;
@RestController
@RequestMapping("/")
public class MyController {
@Autowired
private Validator validator;
//..elided...
@GetMapping
public String getSomething(@Valid @RequestBody MyRequest) {
//This is null
if ( validator == null ) {
throw new Exception("is null");
}
}
}
我的配置类:
package com.app.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan("com.app")
public class ValidationConfig {
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
/* //Including this doesn't help
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}*/
}
摇篮:
buildscript {
ext {
springBootVersion = "1.5.6.RELEASE"
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "org.springframework.boot"
apply plugin: "idea"
apply plugin: "jacoco"
jar {
baseName = "my-service"
version = "0.0.1-SNAPSHOT"
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
//Spring Boot
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-actuator")
//Testing
testCompile("org.hamcrest:hamcrest-all:1.3")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
无论我做什么,我控制器中的验证器都是空的!
答案 0 :(得分:1)
在您的控制器中,您需要javax.validation.Validator
,但在您使用的配置中org.springframework.validation.Validator