繁体   English   中英

为什么我的Spring Boot控制器不自动连接验证器?

[英]Why is my spring boot controller not auto-wiring the Validator?

我有一个具有以下功能的控制器:

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")
}

无论我做什么,控制器中的验证器都是null!

在控制器中,您期望使用javax.validation.Validator但在配置中,您使用的是org.springframework.validation.Validator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM