私は、次のとコントローラを持っています。私のスプリングブートコントローラがバリデーターを自動配線しないのはなぜですか?
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;
}*/
}
のGradle:
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")
}
はどんなに私は何をすべきか、私のコントローラ内のバリデータがnullではありません!
を使用していますか?それを見ることは、さらなる洞察を提供するかもしれない。 –
@ nicholas.hauschildどういう意味ですか? @RunWith(SpringRunner.class)で実行しています。 @SpringBootTest public class TestMyController {'。 –
@ nicholas.hauschildありがとうございました!あなたは私がこの問題を発見するのを手伝った。私は '@InjectMocks private MyController controller'を使っていましたが、' @ Autowired'フィールドにはnullが残っていました。 '@Autowired @InjectMocks private MyController controller'に変更しました!これを答え(あなたのコメントと一緒に)に追加すると、私はそれに答えてマークします –